filename
stringlengths 3
9
| code
stringlengths 4
1.87M
|
---|---|
859069.c | /*-
* Copyright (c) 1999-2002, 2007-2011 Robert N. M. Watson
* Copyright (c) 2001-2005 McAfee, Inc.
* Copyright (c) 2006 SPARTA, Inc.
* All rights reserved.
*
* This software was developed by Robert Watson for the TrustedBSD Project.
*
* This software was developed for the FreeBSD Project in part by McAfee
* Research, the Security Research Division of McAfee, Inc. under
* DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA
* CHATS research program.
*
* This software was enhanced by SPARTA ISSO under SPAWAR contract
* N66001-04-C-6019 ("SEFOS").
*
* This software was developed at the University of Cambridge Computer
* Laboratory with support from a grant from Google, Inc.
*
* 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.
*
* $FreeBSD: releng/9.3/sys/security/mac_biba/mac_biba.c 248085 2013-03-09 02:36:32Z marius $
*/
/*
* Developed by the TrustedBSD Project.
*
* Biba fixed label mandatory integrity policy.
*/
#include <sys/param.h>
#include <sys/conf.h>
#include <sys/extattr.h>
#include <sys/kernel.h>
#include <sys/ksem.h>
#include <sys/malloc.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/priv.h>
#include <sys/proc.h>
#include <sys/sbuf.h>
#include <sys/systm.h>
#include <sys/sysproto.h>
#include <sys/sysent.h>
#include <sys/systm.h>
#include <sys/vnode.h>
#include <sys/file.h>
#include <sys/socket.h>
#include <sys/socketvar.h>
#include <sys/pipe.h>
#include <sys/sx.h>
#include <sys/sysctl.h>
#include <sys/msg.h>
#include <sys/sem.h>
#include <sys/shm.h>
#include <fs/devfs/devfs.h>
#include <net/bpfdesc.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/if_var.h>
#include <netinet/in.h>
#include <netinet/in_pcb.h>
#include <netinet/ip_var.h>
#include <vm/uma.h>
#include <vm/vm.h>
#include <security/mac/mac_policy.h>
#include <security/mac_biba/mac_biba.h>
SYSCTL_DECL(_security_mac);
static SYSCTL_NODE(_security_mac, OID_AUTO, biba, CTLFLAG_RW, 0,
"TrustedBSD mac_biba policy controls");
static int biba_label_size = sizeof(struct mac_biba);
SYSCTL_INT(_security_mac_biba, OID_AUTO, label_size, CTLFLAG_RD,
&biba_label_size, 0, "Size of struct mac_biba");
static int biba_enabled = 1;
SYSCTL_INT(_security_mac_biba, OID_AUTO, enabled, CTLFLAG_RW, &biba_enabled,
0, "Enforce MAC/Biba policy");
TUNABLE_INT("security.mac.biba.enabled", &biba_enabled);
static int destroyed_not_inited;
SYSCTL_INT(_security_mac_biba, OID_AUTO, destroyed_not_inited, CTLFLAG_RD,
&destroyed_not_inited, 0, "Count of labels destroyed but not inited");
static int trust_all_interfaces = 0;
SYSCTL_INT(_security_mac_biba, OID_AUTO, trust_all_interfaces, CTLFLAG_RD,
&trust_all_interfaces, 0, "Consider all interfaces 'trusted' by MAC/Biba");
TUNABLE_INT("security.mac.biba.trust_all_interfaces", &trust_all_interfaces);
static char trusted_interfaces[128];
SYSCTL_STRING(_security_mac_biba, OID_AUTO, trusted_interfaces, CTLFLAG_RD,
trusted_interfaces, 0, "Interfaces considered 'trusted' by MAC/Biba");
TUNABLE_STR("security.mac.biba.trusted_interfaces", trusted_interfaces,
sizeof(trusted_interfaces));
static int max_compartments = MAC_BIBA_MAX_COMPARTMENTS;
SYSCTL_INT(_security_mac_biba, OID_AUTO, max_compartments, CTLFLAG_RD,
&max_compartments, 0, "Maximum supported compartments");
static int ptys_equal = 0;
SYSCTL_INT(_security_mac_biba, OID_AUTO, ptys_equal, CTLFLAG_RW, &ptys_equal,
0, "Label pty devices as biba/equal on create");
TUNABLE_INT("security.mac.biba.ptys_equal", &ptys_equal);
static int interfaces_equal = 1;
SYSCTL_INT(_security_mac_biba, OID_AUTO, interfaces_equal, CTLFLAG_RW,
&interfaces_equal, 0, "Label network interfaces as biba/equal on create");
TUNABLE_INT("security.mac.biba.interfaces_equal", &interfaces_equal);
static int revocation_enabled = 0;
SYSCTL_INT(_security_mac_biba, OID_AUTO, revocation_enabled, CTLFLAG_RW,
&revocation_enabled, 0, "Revoke access to objects on relabel");
TUNABLE_INT("security.mac.biba.revocation_enabled", &revocation_enabled);
static int biba_slot;
#define SLOT(l) ((struct mac_biba *)mac_label_get((l), biba_slot))
#define SLOT_SET(l, val) mac_label_set((l), biba_slot, (uintptr_t)(val))
static uma_zone_t zone_biba;
static __inline int
biba_bit_set_empty(u_char *set) {
int i;
for (i = 0; i < MAC_BIBA_MAX_COMPARTMENTS >> 3; i++)
if (set[i] != 0)
return (0);
return (1);
}
static struct mac_biba *
biba_alloc(int flag)
{
return (uma_zalloc(zone_biba, flag | M_ZERO));
}
static void
biba_free(struct mac_biba *mb)
{
if (mb != NULL)
uma_zfree(zone_biba, mb);
else
atomic_add_int(&destroyed_not_inited, 1);
}
static int
biba_atmostflags(struct mac_biba *mb, int flags)
{
if ((mb->mb_flags & flags) != mb->mb_flags)
return (EINVAL);
return (0);
}
static int
biba_dominate_element(struct mac_biba_element *a, struct mac_biba_element *b)
{
int bit;
switch (a->mbe_type) {
case MAC_BIBA_TYPE_EQUAL:
case MAC_BIBA_TYPE_HIGH:
return (1);
case MAC_BIBA_TYPE_LOW:
switch (b->mbe_type) {
case MAC_BIBA_TYPE_GRADE:
case MAC_BIBA_TYPE_HIGH:
return (0);
case MAC_BIBA_TYPE_EQUAL:
case MAC_BIBA_TYPE_LOW:
return (1);
default:
panic("biba_dominate_element: b->mbe_type invalid");
}
case MAC_BIBA_TYPE_GRADE:
switch (b->mbe_type) {
case MAC_BIBA_TYPE_EQUAL:
case MAC_BIBA_TYPE_LOW:
return (1);
case MAC_BIBA_TYPE_HIGH:
return (0);
case MAC_BIBA_TYPE_GRADE:
for (bit = 1; bit <= MAC_BIBA_MAX_COMPARTMENTS; bit++)
if (!MAC_BIBA_BIT_TEST(bit,
a->mbe_compartments) &&
MAC_BIBA_BIT_TEST(bit, b->mbe_compartments))
return (0);
return (a->mbe_grade >= b->mbe_grade);
default:
panic("biba_dominate_element: b->mbe_type invalid");
}
default:
panic("biba_dominate_element: a->mbe_type invalid");
}
return (0);
}
static int
biba_subject_dominate_high(struct mac_biba *mb)
{
struct mac_biba_element *element;
KASSERT((mb->mb_flags & MAC_BIBA_FLAG_EFFECTIVE) != 0,
("biba_effective_in_range: mb not effective"));
element = &mb->mb_effective;
return (element->mbe_type == MAC_BIBA_TYPE_EQUAL ||
element->mbe_type == MAC_BIBA_TYPE_HIGH);
}
static int
biba_range_in_range(struct mac_biba *rangea, struct mac_biba *rangeb)
{
return (biba_dominate_element(&rangeb->mb_rangehigh,
&rangea->mb_rangehigh) &&
biba_dominate_element(&rangea->mb_rangelow,
&rangeb->mb_rangelow));
}
static int
biba_effective_in_range(struct mac_biba *effective, struct mac_biba *range)
{
KASSERT((effective->mb_flags & MAC_BIBA_FLAG_EFFECTIVE) != 0,
("biba_effective_in_range: a not effective"));
KASSERT((range->mb_flags & MAC_BIBA_FLAG_RANGE) != 0,
("biba_effective_in_range: b not range"));
return (biba_dominate_element(&range->mb_rangehigh,
&effective->mb_effective) &&
biba_dominate_element(&effective->mb_effective,
&range->mb_rangelow));
return (1);
}
static int
biba_dominate_effective(struct mac_biba *a, struct mac_biba *b)
{
KASSERT((a->mb_flags & MAC_BIBA_FLAG_EFFECTIVE) != 0,
("biba_dominate_effective: a not effective"));
KASSERT((b->mb_flags & MAC_BIBA_FLAG_EFFECTIVE) != 0,
("biba_dominate_effective: b not effective"));
return (biba_dominate_element(&a->mb_effective, &b->mb_effective));
}
static int
biba_equal_element(struct mac_biba_element *a, struct mac_biba_element *b)
{
if (a->mbe_type == MAC_BIBA_TYPE_EQUAL ||
b->mbe_type == MAC_BIBA_TYPE_EQUAL)
return (1);
return (a->mbe_type == b->mbe_type && a->mbe_grade == b->mbe_grade);
}
static int
biba_equal_effective(struct mac_biba *a, struct mac_biba *b)
{
KASSERT((a->mb_flags & MAC_BIBA_FLAG_EFFECTIVE) != 0,
("biba_equal_effective: a not effective"));
KASSERT((b->mb_flags & MAC_BIBA_FLAG_EFFECTIVE) != 0,
("biba_equal_effective: b not effective"));
return (biba_equal_element(&a->mb_effective, &b->mb_effective));
}
static int
biba_contains_equal(struct mac_biba *mb)
{
if (mb->mb_flags & MAC_BIBA_FLAG_EFFECTIVE) {
if (mb->mb_effective.mbe_type == MAC_BIBA_TYPE_EQUAL)
return (1);
}
if (mb->mb_flags & MAC_BIBA_FLAG_RANGE) {
if (mb->mb_rangelow.mbe_type == MAC_BIBA_TYPE_EQUAL)
return (1);
if (mb->mb_rangehigh.mbe_type == MAC_BIBA_TYPE_EQUAL)
return (1);
}
return (0);
}
static int
biba_subject_privileged(struct mac_biba *mb)
{
KASSERT((mb->mb_flags & MAC_BIBA_FLAGS_BOTH) == MAC_BIBA_FLAGS_BOTH,
("biba_subject_privileged: subject doesn't have both labels"));
/* If the effective is EQUAL, it's ok. */
if (mb->mb_effective.mbe_type == MAC_BIBA_TYPE_EQUAL)
return (0);
/* If either range endpoint is EQUAL, it's ok. */
if (mb->mb_rangelow.mbe_type == MAC_BIBA_TYPE_EQUAL ||
mb->mb_rangehigh.mbe_type == MAC_BIBA_TYPE_EQUAL)
return (0);
/* If the range is low-high, it's ok. */
if (mb->mb_rangelow.mbe_type == MAC_BIBA_TYPE_LOW &&
mb->mb_rangehigh.mbe_type == MAC_BIBA_TYPE_HIGH)
return (0);
/* It's not ok. */
return (EPERM);
}
static int
biba_high_effective(struct mac_biba *mb)
{
KASSERT((mb->mb_flags & MAC_BIBA_FLAG_EFFECTIVE) != 0,
("biba_equal_effective: mb not effective"));
return (mb->mb_effective.mbe_type == MAC_BIBA_TYPE_HIGH);
}
static int
biba_valid(struct mac_biba *mb)
{
if (mb->mb_flags & MAC_BIBA_FLAG_EFFECTIVE) {
switch (mb->mb_effective.mbe_type) {
case MAC_BIBA_TYPE_GRADE:
break;
case MAC_BIBA_TYPE_EQUAL:
case MAC_BIBA_TYPE_HIGH:
case MAC_BIBA_TYPE_LOW:
if (mb->mb_effective.mbe_grade != 0 ||
!MAC_BIBA_BIT_SET_EMPTY(
mb->mb_effective.mbe_compartments))
return (EINVAL);
break;
default:
return (EINVAL);
}
} else {
if (mb->mb_effective.mbe_type != MAC_BIBA_TYPE_UNDEF)
return (EINVAL);
}
if (mb->mb_flags & MAC_BIBA_FLAG_RANGE) {
switch (mb->mb_rangelow.mbe_type) {
case MAC_BIBA_TYPE_GRADE:
break;
case MAC_BIBA_TYPE_EQUAL:
case MAC_BIBA_TYPE_HIGH:
case MAC_BIBA_TYPE_LOW:
if (mb->mb_rangelow.mbe_grade != 0 ||
!MAC_BIBA_BIT_SET_EMPTY(
mb->mb_rangelow.mbe_compartments))
return (EINVAL);
break;
default:
return (EINVAL);
}
switch (mb->mb_rangehigh.mbe_type) {
case MAC_BIBA_TYPE_GRADE:
break;
case MAC_BIBA_TYPE_EQUAL:
case MAC_BIBA_TYPE_HIGH:
case MAC_BIBA_TYPE_LOW:
if (mb->mb_rangehigh.mbe_grade != 0 ||
!MAC_BIBA_BIT_SET_EMPTY(
mb->mb_rangehigh.mbe_compartments))
return (EINVAL);
break;
default:
return (EINVAL);
}
if (!biba_dominate_element(&mb->mb_rangehigh,
&mb->mb_rangelow))
return (EINVAL);
} else {
if (mb->mb_rangelow.mbe_type != MAC_BIBA_TYPE_UNDEF ||
mb->mb_rangehigh.mbe_type != MAC_BIBA_TYPE_UNDEF)
return (EINVAL);
}
return (0);
}
static void
biba_set_range(struct mac_biba *mb, u_short typelow, u_short gradelow,
u_char *compartmentslow, u_short typehigh, u_short gradehigh,
u_char *compartmentshigh)
{
mb->mb_rangelow.mbe_type = typelow;
mb->mb_rangelow.mbe_grade = gradelow;
if (compartmentslow != NULL)
memcpy(mb->mb_rangelow.mbe_compartments, compartmentslow,
sizeof(mb->mb_rangelow.mbe_compartments));
mb->mb_rangehigh.mbe_type = typehigh;
mb->mb_rangehigh.mbe_grade = gradehigh;
if (compartmentshigh != NULL)
memcpy(mb->mb_rangehigh.mbe_compartments, compartmentshigh,
sizeof(mb->mb_rangehigh.mbe_compartments));
mb->mb_flags |= MAC_BIBA_FLAG_RANGE;
}
static void
biba_set_effective(struct mac_biba *mb, u_short type, u_short grade,
u_char *compartments)
{
mb->mb_effective.mbe_type = type;
mb->mb_effective.mbe_grade = grade;
if (compartments != NULL)
memcpy(mb->mb_effective.mbe_compartments, compartments,
sizeof(mb->mb_effective.mbe_compartments));
mb->mb_flags |= MAC_BIBA_FLAG_EFFECTIVE;
}
static void
biba_copy_range(struct mac_biba *labelfrom, struct mac_biba *labelto)
{
KASSERT((labelfrom->mb_flags & MAC_BIBA_FLAG_RANGE) != 0,
("biba_copy_range: labelfrom not range"));
labelto->mb_rangelow = labelfrom->mb_rangelow;
labelto->mb_rangehigh = labelfrom->mb_rangehigh;
labelto->mb_flags |= MAC_BIBA_FLAG_RANGE;
}
static void
biba_copy_effective(struct mac_biba *labelfrom, struct mac_biba *labelto)
{
KASSERT((labelfrom->mb_flags & MAC_BIBA_FLAG_EFFECTIVE) != 0,
("biba_copy_effective: labelfrom not effective"));
labelto->mb_effective = labelfrom->mb_effective;
labelto->mb_flags |= MAC_BIBA_FLAG_EFFECTIVE;
}
static void
biba_copy(struct mac_biba *source, struct mac_biba *dest)
{
if (source->mb_flags & MAC_BIBA_FLAG_EFFECTIVE)
biba_copy_effective(source, dest);
if (source->mb_flags & MAC_BIBA_FLAG_RANGE)
biba_copy_range(source, dest);
}
/*
* Policy module operations.
*/
static void
biba_init(struct mac_policy_conf *conf)
{
zone_biba = uma_zcreate("mac_biba", sizeof(struct mac_biba), NULL,
NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
}
/*
* Label operations.
*/
static void
biba_init_label(struct label *label)
{
SLOT_SET(label, biba_alloc(M_WAITOK));
}
static int
biba_init_label_waitcheck(struct label *label, int flag)
{
SLOT_SET(label, biba_alloc(flag));
if (SLOT(label) == NULL)
return (ENOMEM);
return (0);
}
static void
biba_destroy_label(struct label *label)
{
biba_free(SLOT(label));
SLOT_SET(label, NULL);
}
/*
* biba_element_to_string() accepts an sbuf and Biba element. It converts
* the Biba element to a string and stores the result in the sbuf; if there
* isn't space in the sbuf, -1 is returned.
*/
static int
biba_element_to_string(struct sbuf *sb, struct mac_biba_element *element)
{
int i, first;
switch (element->mbe_type) {
case MAC_BIBA_TYPE_HIGH:
return (sbuf_printf(sb, "high"));
case MAC_BIBA_TYPE_LOW:
return (sbuf_printf(sb, "low"));
case MAC_BIBA_TYPE_EQUAL:
return (sbuf_printf(sb, "equal"));
case MAC_BIBA_TYPE_GRADE:
if (sbuf_printf(sb, "%d", element->mbe_grade) == -1)
return (-1);
first = 1;
for (i = 1; i <= MAC_BIBA_MAX_COMPARTMENTS; i++) {
if (MAC_BIBA_BIT_TEST(i, element->mbe_compartments)) {
if (first) {
if (sbuf_putc(sb, ':') == -1)
return (-1);
if (sbuf_printf(sb, "%d", i) == -1)
return (-1);
first = 0;
} else {
if (sbuf_printf(sb, "+%d", i) == -1)
return (-1);
}
}
}
return (0);
default:
panic("biba_element_to_string: invalid type (%d)",
element->mbe_type);
}
}
/*
* biba_to_string() converts a Biba label to a string, and places the results
* in the passed sbuf. It returns 0 on success, or EINVAL if there isn't
* room in the sbuf. Note: the sbuf will be modified even in a failure case,
* so the caller may need to revert the sbuf by restoring the offset if
* that's undesired.
*/
static int
biba_to_string(struct sbuf *sb, struct mac_biba *mb)
{
if (mb->mb_flags & MAC_BIBA_FLAG_EFFECTIVE) {
if (biba_element_to_string(sb, &mb->mb_effective) == -1)
return (EINVAL);
}
if (mb->mb_flags & MAC_BIBA_FLAG_RANGE) {
if (sbuf_putc(sb, '(') == -1)
return (EINVAL);
if (biba_element_to_string(sb, &mb->mb_rangelow) == -1)
return (EINVAL);
if (sbuf_putc(sb, '-') == -1)
return (EINVAL);
if (biba_element_to_string(sb, &mb->mb_rangehigh) == -1)
return (EINVAL);
if (sbuf_putc(sb, ')') == -1)
return (EINVAL);
}
return (0);
}
static int
biba_externalize_label(struct label *label, char *element_name,
struct sbuf *sb, int *claimed)
{
struct mac_biba *mb;
if (strcmp(MAC_BIBA_LABEL_NAME, element_name) != 0)
return (0);
(*claimed)++;
mb = SLOT(label);
return (biba_to_string(sb, mb));
}
static int
biba_parse_element(struct mac_biba_element *element, char *string)
{
char *compartment, *end, *grade;
int value;
if (strcmp(string, "high") == 0 || strcmp(string, "hi") == 0) {
element->mbe_type = MAC_BIBA_TYPE_HIGH;
element->mbe_grade = MAC_BIBA_TYPE_UNDEF;
} else if (strcmp(string, "low") == 0 || strcmp(string, "lo") == 0) {
element->mbe_type = MAC_BIBA_TYPE_LOW;
element->mbe_grade = MAC_BIBA_TYPE_UNDEF;
} else if (strcmp(string, "equal") == 0 ||
strcmp(string, "eq") == 0) {
element->mbe_type = MAC_BIBA_TYPE_EQUAL;
element->mbe_grade = MAC_BIBA_TYPE_UNDEF;
} else {
element->mbe_type = MAC_BIBA_TYPE_GRADE;
/*
* Numeric grade piece of the element.
*/
grade = strsep(&string, ":");
value = strtol(grade, &end, 10);
if (end == grade || *end != '\0')
return (EINVAL);
if (value < 0 || value > 65535)
return (EINVAL);
element->mbe_grade = value;
/*
* Optional compartment piece of the element. If none are
* included, we assume that the label has no compartments.
*/
if (string == NULL)
return (0);
if (*string == '\0')
return (0);
while ((compartment = strsep(&string, "+")) != NULL) {
value = strtol(compartment, &end, 10);
if (compartment == end || *end != '\0')
return (EINVAL);
if (value < 1 || value > MAC_BIBA_MAX_COMPARTMENTS)
return (EINVAL);
MAC_BIBA_BIT_SET(value, element->mbe_compartments);
}
}
return (0);
}
/*
* Note: destructively consumes the string, make a local copy before calling
* if that's a problem.
*/
static int
biba_parse(struct mac_biba *mb, char *string)
{
char *rangehigh, *rangelow, *effective;
int error;
effective = strsep(&string, "(");
if (*effective == '\0')
effective = NULL;
if (string != NULL) {
rangelow = strsep(&string, "-");
if (string == NULL)
return (EINVAL);
rangehigh = strsep(&string, ")");
if (string == NULL)
return (EINVAL);
if (*string != '\0')
return (EINVAL);
} else {
rangelow = NULL;
rangehigh = NULL;
}
KASSERT((rangelow != NULL && rangehigh != NULL) ||
(rangelow == NULL && rangehigh == NULL),
("biba_parse: range mismatch"));
bzero(mb, sizeof(*mb));
if (effective != NULL) {
error = biba_parse_element(&mb->mb_effective, effective);
if (error)
return (error);
mb->mb_flags |= MAC_BIBA_FLAG_EFFECTIVE;
}
if (rangelow != NULL) {
error = biba_parse_element(&mb->mb_rangelow, rangelow);
if (error)
return (error);
error = biba_parse_element(&mb->mb_rangehigh, rangehigh);
if (error)
return (error);
mb->mb_flags |= MAC_BIBA_FLAG_RANGE;
}
error = biba_valid(mb);
if (error)
return (error);
return (0);
}
static int
biba_internalize_label(struct label *label, char *element_name,
char *element_data, int *claimed)
{
struct mac_biba *mb, mb_temp;
int error;
if (strcmp(MAC_BIBA_LABEL_NAME, element_name) != 0)
return (0);
(*claimed)++;
error = biba_parse(&mb_temp, element_data);
if (error)
return (error);
mb = SLOT(label);
*mb = mb_temp;
return (0);
}
static void
biba_copy_label(struct label *src, struct label *dest)
{
*SLOT(dest) = *SLOT(src);
}
/*
* Object-specific entry point implementations are sorted alphabetically by
* object type name and then by operation.
*/
static int
biba_bpfdesc_check_receive(struct bpf_d *d, struct label *dlabel,
struct ifnet *ifp, struct label *ifplabel)
{
struct mac_biba *a, *b;
if (!biba_enabled)
return (0);
a = SLOT(dlabel);
b = SLOT(ifplabel);
if (biba_equal_effective(a, b))
return (0);
return (EACCES);
}
static void
biba_bpfdesc_create(struct ucred *cred, struct bpf_d *d,
struct label *dlabel)
{
struct mac_biba *source, *dest;
source = SLOT(cred->cr_label);
dest = SLOT(dlabel);
biba_copy_effective(source, dest);
}
static void
biba_bpfdesc_create_mbuf(struct bpf_d *d, struct label *dlabel,
struct mbuf *m, struct label *mlabel)
{
struct mac_biba *source, *dest;
source = SLOT(dlabel);
dest = SLOT(mlabel);
biba_copy_effective(source, dest);
}
static void
biba_cred_associate_nfsd(struct ucred *cred)
{
struct mac_biba *label;
label = SLOT(cred->cr_label);
biba_set_effective(label, MAC_BIBA_TYPE_LOW, 0, NULL);
biba_set_range(label, MAC_BIBA_TYPE_LOW, 0, NULL, MAC_BIBA_TYPE_HIGH,
0, NULL);
}
static int
biba_cred_check_relabel(struct ucred *cred, struct label *newlabel)
{
struct mac_biba *subj, *new;
int error;
subj = SLOT(cred->cr_label);
new = SLOT(newlabel);
/*
* If there is a Biba label update for the credential, it may
* be an update of the effective, range, or both.
*/
error = biba_atmostflags(new, MAC_BIBA_FLAGS_BOTH);
if (error)
return (error);
/*
* If the Biba label is to be changed, authorize as appropriate.
*/
if (new->mb_flags & MAC_BIBA_FLAGS_BOTH) {
/*
* If the change request modifies both the Biba label
* effective and range, check that the new effective will be
* in the new range.
*/
if ((new->mb_flags & MAC_BIBA_FLAGS_BOTH) ==
MAC_BIBA_FLAGS_BOTH &&
!biba_effective_in_range(new, new))
return (EINVAL);
/*
* To change the Biba effective label on a credential, the
* new effective label must be in the current range.
*/
if (new->mb_flags & MAC_BIBA_FLAG_EFFECTIVE &&
!biba_effective_in_range(new, subj))
return (EPERM);
/*
* To change the Biba range on a credential, the new range
* label must be in the current range.
*/
if (new->mb_flags & MAC_BIBA_FLAG_RANGE &&
!biba_range_in_range(new, subj))
return (EPERM);
/*
* To have EQUAL in any component of the new credential Biba
* label, the subject must already have EQUAL in their label.
*/
if (biba_contains_equal(new)) {
error = biba_subject_privileged(subj);
if (error)
return (error);
}
}
return (0);
}
static int
biba_cred_check_visible(struct ucred *u1, struct ucred *u2)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(u1->cr_label);
obj = SLOT(u2->cr_label);
/* XXX: range */
if (!biba_dominate_effective(obj, subj))
return (ESRCH);
return (0);
}
static void
biba_cred_create_init(struct ucred *cred)
{
struct mac_biba *dest;
dest = SLOT(cred->cr_label);
biba_set_effective(dest, MAC_BIBA_TYPE_HIGH, 0, NULL);
biba_set_range(dest, MAC_BIBA_TYPE_LOW, 0, NULL, MAC_BIBA_TYPE_HIGH,
0, NULL);
}
static void
biba_cred_create_swapper(struct ucred *cred)
{
struct mac_biba *dest;
dest = SLOT(cred->cr_label);
biba_set_effective(dest, MAC_BIBA_TYPE_EQUAL, 0, NULL);
biba_set_range(dest, MAC_BIBA_TYPE_LOW, 0, NULL, MAC_BIBA_TYPE_HIGH,
0, NULL);
}
static void
biba_cred_relabel(struct ucred *cred, struct label *newlabel)
{
struct mac_biba *source, *dest;
source = SLOT(newlabel);
dest = SLOT(cred->cr_label);
biba_copy(source, dest);
}
static void
biba_devfs_create_device(struct ucred *cred, struct mount *mp,
struct cdev *dev, struct devfs_dirent *de, struct label *delabel)
{
struct mac_biba *mb;
const char *dn;
int biba_type;
mb = SLOT(delabel);
dn = devtoname(dev);
if (strcmp(dn, "null") == 0 ||
strcmp(dn, "zero") == 0 ||
strcmp(dn, "random") == 0 ||
strncmp(dn, "fd/", strlen("fd/")) == 0)
biba_type = MAC_BIBA_TYPE_EQUAL;
else if (ptys_equal &&
(strncmp(dn, "ttyp", strlen("ttyp")) == 0 ||
strncmp(dn, "pts/", strlen("pts/")) == 0 ||
strncmp(dn, "ptyp", strlen("ptyp")) == 0))
biba_type = MAC_BIBA_TYPE_EQUAL;
else
biba_type = MAC_BIBA_TYPE_HIGH;
biba_set_effective(mb, biba_type, 0, NULL);
}
static void
biba_devfs_create_directory(struct mount *mp, char *dirname, int dirnamelen,
struct devfs_dirent *de, struct label *delabel)
{
struct mac_biba *mb;
mb = SLOT(delabel);
biba_set_effective(mb, MAC_BIBA_TYPE_HIGH, 0, NULL);
}
static void
biba_devfs_create_symlink(struct ucred *cred, struct mount *mp,
struct devfs_dirent *dd, struct label *ddlabel, struct devfs_dirent *de,
struct label *delabel)
{
struct mac_biba *source, *dest;
source = SLOT(cred->cr_label);
dest = SLOT(delabel);
biba_copy_effective(source, dest);
}
static void
biba_devfs_update(struct mount *mp, struct devfs_dirent *de,
struct label *delabel, struct vnode *vp, struct label *vplabel)
{
struct mac_biba *source, *dest;
source = SLOT(vplabel);
dest = SLOT(delabel);
biba_copy(source, dest);
}
static void
biba_devfs_vnode_associate(struct mount *mp, struct label *mntlabel,
struct devfs_dirent *de, struct label *delabel, struct vnode *vp,
struct label *vplabel)
{
struct mac_biba *source, *dest;
source = SLOT(delabel);
dest = SLOT(vplabel);
biba_copy_effective(source, dest);
}
static int
biba_ifnet_check_relabel(struct ucred *cred, struct ifnet *ifp,
struct label *ifplabel, struct label *newlabel)
{
struct mac_biba *subj, *new;
int error;
subj = SLOT(cred->cr_label);
new = SLOT(newlabel);
/*
* If there is a Biba label update for the interface, it may be an
* update of the effective, range, or both.
*/
error = biba_atmostflags(new, MAC_BIBA_FLAGS_BOTH);
if (error)
return (error);
/*
* Relabling network interfaces requires Biba privilege.
*/
error = biba_subject_privileged(subj);
if (error)
return (error);
return (0);
}
static int
biba_ifnet_check_transmit(struct ifnet *ifp, struct label *ifplabel,
struct mbuf *m, struct label *mlabel)
{
struct mac_biba *p, *i;
if (!biba_enabled)
return (0);
p = SLOT(mlabel);
i = SLOT(ifplabel);
return (biba_effective_in_range(p, i) ? 0 : EACCES);
}
static void
biba_ifnet_create(struct ifnet *ifp, struct label *ifplabel)
{
char tifname[IFNAMSIZ], *p, *q;
char tiflist[sizeof(trusted_interfaces)];
struct mac_biba *dest;
int len, type;
dest = SLOT(ifplabel);
if (ifp->if_type == IFT_LOOP || interfaces_equal != 0) {
type = MAC_BIBA_TYPE_EQUAL;
goto set;
}
if (trust_all_interfaces) {
type = MAC_BIBA_TYPE_HIGH;
goto set;
}
type = MAC_BIBA_TYPE_LOW;
if (trusted_interfaces[0] == '\0' ||
!strvalid(trusted_interfaces, sizeof(trusted_interfaces)))
goto set;
bzero(tiflist, sizeof(tiflist));
for (p = trusted_interfaces, q = tiflist; *p != '\0'; p++, q++)
if(*p != ' ' && *p != '\t')
*q = *p;
for (p = q = tiflist;; p++) {
if (*p == ',' || *p == '\0') {
len = p - q;
if (len < IFNAMSIZ) {
bzero(tifname, sizeof(tifname));
bcopy(q, tifname, len);
if (strcmp(tifname, ifp->if_xname) == 0) {
type = MAC_BIBA_TYPE_HIGH;
break;
}
} else {
*p = '\0';
printf("mac_biba warning: interface name "
"\"%s\" is too long (must be < %d)\n",
q, IFNAMSIZ);
}
if (*p == '\0')
break;
q = p + 1;
}
}
set:
biba_set_effective(dest, type, 0, NULL);
biba_set_range(dest, type, 0, NULL, type, 0, NULL);
}
static void
biba_ifnet_create_mbuf(struct ifnet *ifp, struct label *ifplabel,
struct mbuf *m, struct label *mlabel)
{
struct mac_biba *source, *dest;
source = SLOT(ifplabel);
dest = SLOT(mlabel);
biba_copy_effective(source, dest);
}
static void
biba_ifnet_relabel(struct ucred *cred, struct ifnet *ifp,
struct label *ifplabel, struct label *newlabel)
{
struct mac_biba *source, *dest;
source = SLOT(newlabel);
dest = SLOT(ifplabel);
biba_copy(source, dest);
}
static int
biba_inpcb_check_deliver(struct inpcb *inp, struct label *inplabel,
struct mbuf *m, struct label *mlabel)
{
struct mac_biba *p, *i;
if (!biba_enabled)
return (0);
p = SLOT(mlabel);
i = SLOT(inplabel);
return (biba_equal_effective(p, i) ? 0 : EACCES);
}
static int
biba_inpcb_check_visible(struct ucred *cred, struct inpcb *inp,
struct label *inplabel)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(inplabel);
if (!biba_dominate_effective(obj, subj))
return (ENOENT);
return (0);
}
static void
biba_inpcb_create(struct socket *so, struct label *solabel,
struct inpcb *inp, struct label *inplabel)
{
struct mac_biba *source, *dest;
source = SLOT(solabel);
dest = SLOT(inplabel);
SOCK_LOCK(so);
biba_copy_effective(source, dest);
SOCK_UNLOCK(so);
}
static void
biba_inpcb_create_mbuf(struct inpcb *inp, struct label *inplabel,
struct mbuf *m, struct label *mlabel)
{
struct mac_biba *source, *dest;
source = SLOT(inplabel);
dest = SLOT(mlabel);
biba_copy_effective(source, dest);
}
static void
biba_inpcb_sosetlabel(struct socket *so, struct label *solabel,
struct inpcb *inp, struct label *inplabel)
{
struct mac_biba *source, *dest;
SOCK_LOCK_ASSERT(so);
source = SLOT(solabel);
dest = SLOT(inplabel);
biba_copy(source, dest);
}
static void
biba_ip6q_create(struct mbuf *m, struct label *mlabel, struct ip6q *q6,
struct label *q6label)
{
struct mac_biba *source, *dest;
source = SLOT(mlabel);
dest = SLOT(q6label);
biba_copy_effective(source, dest);
}
static int
biba_ip6q_match(struct mbuf *m, struct label *mlabel, struct ip6q *q6,
struct label *q6label)
{
struct mac_biba *a, *b;
a = SLOT(q6label);
b = SLOT(mlabel);
return (biba_equal_effective(a, b));
}
static void
biba_ip6q_reassemble(struct ip6q *q6, struct label *q6label, struct mbuf *m,
struct label *mlabel)
{
struct mac_biba *source, *dest;
source = SLOT(q6label);
dest = SLOT(mlabel);
/* Just use the head, since we require them all to match. */
biba_copy_effective(source, dest);
}
static void
biba_ip6q_update(struct mbuf *m, struct label *mlabel, struct ip6q *q6,
struct label *q6label)
{
/* NOOP: we only accept matching labels, so no need to update */
}
static void
biba_ipq_create(struct mbuf *m, struct label *mlabel, struct ipq *q,
struct label *qlabel)
{
struct mac_biba *source, *dest;
source = SLOT(mlabel);
dest = SLOT(qlabel);
biba_copy_effective(source, dest);
}
static int
biba_ipq_match(struct mbuf *m, struct label *mlabel, struct ipq *q,
struct label *qlabel)
{
struct mac_biba *a, *b;
a = SLOT(qlabel);
b = SLOT(mlabel);
return (biba_equal_effective(a, b));
}
static void
biba_ipq_reassemble(struct ipq *q, struct label *qlabel, struct mbuf *m,
struct label *mlabel)
{
struct mac_biba *source, *dest;
source = SLOT(qlabel);
dest = SLOT(mlabel);
/* Just use the head, since we require them all to match. */
biba_copy_effective(source, dest);
}
static void
biba_ipq_update(struct mbuf *m, struct label *mlabel, struct ipq *q,
struct label *qlabel)
{
/* NOOP: we only accept matching labels, so no need to update */
}
static int
biba_kld_check_load(struct ucred *cred, struct vnode *vp,
struct label *vplabel)
{
struct mac_biba *subj, *obj;
int error;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
error = biba_subject_privileged(subj);
if (error)
return (error);
obj = SLOT(vplabel);
if (!biba_high_effective(obj))
return (EACCES);
return (0);
}
static int
biba_mount_check_stat(struct ucred *cred, struct mount *mp,
struct label *mplabel)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(mplabel);
if (!biba_dominate_effective(obj, subj))
return (EACCES);
return (0);
}
static void
biba_mount_create(struct ucred *cred, struct mount *mp,
struct label *mplabel)
{
struct mac_biba *source, *dest;
source = SLOT(cred->cr_label);
dest = SLOT(mplabel);
biba_copy_effective(source, dest);
}
static void
biba_netatalk_aarp_send(struct ifnet *ifp, struct label *ifplabel,
struct mbuf *m, struct label *mlabel)
{
struct mac_biba *dest;
dest = SLOT(mlabel);
biba_set_effective(dest, MAC_BIBA_TYPE_EQUAL, 0, NULL);
}
static void
biba_netinet_arp_send(struct ifnet *ifp, struct label *ifplabel,
struct mbuf *m, struct label *mlabel)
{
struct mac_biba *dest;
dest = SLOT(mlabel);
biba_set_effective(dest, MAC_BIBA_TYPE_EQUAL, 0, NULL);
}
static void
biba_netinet_firewall_reply(struct mbuf *mrecv, struct label *mrecvlabel,
struct mbuf *msend, struct label *msendlabel)
{
struct mac_biba *source, *dest;
source = SLOT(mrecvlabel);
dest = SLOT(msendlabel);
biba_copy_effective(source, dest);
}
static void
biba_netinet_firewall_send(struct mbuf *m, struct label *mlabel)
{
struct mac_biba *dest;
dest = SLOT(mlabel);
/* XXX: where is the label for the firewall really coming from? */
biba_set_effective(dest, MAC_BIBA_TYPE_EQUAL, 0, NULL);
}
static void
biba_netinet_fragment(struct mbuf *m, struct label *mlabel,
struct mbuf *frag, struct label *fraglabel)
{
struct mac_biba *source, *dest;
source = SLOT(mlabel);
dest = SLOT(fraglabel);
biba_copy_effective(source, dest);
}
static void
biba_netinet_icmp_reply(struct mbuf *mrecv, struct label *mrecvlabel,
struct mbuf *msend, struct label *msendlabel)
{
struct mac_biba *source, *dest;
source = SLOT(mrecvlabel);
dest = SLOT(msendlabel);
biba_copy_effective(source, dest);
}
static void
biba_netinet_igmp_send(struct ifnet *ifp, struct label *ifplabel,
struct mbuf *m, struct label *mlabel)
{
struct mac_biba *dest;
dest = SLOT(mlabel);
biba_set_effective(dest, MAC_BIBA_TYPE_EQUAL, 0, NULL);
}
static void
biba_netinet6_nd6_send(struct ifnet *ifp, struct label *ifplabel,
struct mbuf *m, struct label *mlabel)
{
struct mac_biba *dest;
dest = SLOT(mlabel);
biba_set_effective(dest, MAC_BIBA_TYPE_EQUAL, 0, NULL);
}
static int
biba_pipe_check_ioctl(struct ucred *cred, struct pipepair *pp,
struct label *pplabel, unsigned long cmd, void /* caddr_t */ *data)
{
if(!biba_enabled)
return (0);
/* XXX: This will be implemented soon... */
return (0);
}
static int
biba_pipe_check_poll(struct ucred *cred, struct pipepair *pp,
struct label *pplabel)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(pplabel);
if (!biba_dominate_effective(obj, subj))
return (EACCES);
return (0);
}
static int
biba_pipe_check_read(struct ucred *cred, struct pipepair *pp,
struct label *pplabel)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(pplabel);
if (!biba_dominate_effective(obj, subj))
return (EACCES);
return (0);
}
static int
biba_pipe_check_relabel(struct ucred *cred, struct pipepair *pp,
struct label *pplabel, struct label *newlabel)
{
struct mac_biba *subj, *obj, *new;
int error;
new = SLOT(newlabel);
subj = SLOT(cred->cr_label);
obj = SLOT(pplabel);
/*
* If there is a Biba label update for a pipe, it must be a effective
* update.
*/
error = biba_atmostflags(new, MAC_BIBA_FLAG_EFFECTIVE);
if (error)
return (error);
/*
* To perform a relabel of a pipe (Biba label or not), Biba must
* authorize the relabel.
*/
if (!biba_effective_in_range(obj, subj))
return (EPERM);
/*
* If the Biba label is to be changed, authorize as appropriate.
*/
if (new->mb_flags & MAC_BIBA_FLAG_EFFECTIVE) {
/*
* To change the Biba label on a pipe, the new pipe label
* must be in the subject range.
*/
if (!biba_effective_in_range(new, subj))
return (EPERM);
/*
* To change the Biba label on a pipe to be EQUAL, the
* subject must have appropriate privilege.
*/
if (biba_contains_equal(new)) {
error = biba_subject_privileged(subj);
if (error)
return (error);
}
}
return (0);
}
static int
biba_pipe_check_stat(struct ucred *cred, struct pipepair *pp,
struct label *pplabel)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(pplabel);
if (!biba_dominate_effective(obj, subj))
return (EACCES);
return (0);
}
static int
biba_pipe_check_write(struct ucred *cred, struct pipepair *pp,
struct label *pplabel)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(pplabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
return (0);
}
static void
biba_pipe_create(struct ucred *cred, struct pipepair *pp,
struct label *pplabel)
{
struct mac_biba *source, *dest;
source = SLOT(cred->cr_label);
dest = SLOT(pplabel);
biba_copy_effective(source, dest);
}
static void
biba_pipe_relabel(struct ucred *cred, struct pipepair *pp,
struct label *pplabel, struct label *newlabel)
{
struct mac_biba *source, *dest;
source = SLOT(newlabel);
dest = SLOT(pplabel);
biba_copy(source, dest);
}
static int
biba_posixsem_check_openunlink(struct ucred *cred, struct ksem *ks,
struct label *kslabel)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(kslabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
return (0);
}
static int
biba_posixsem_check_setmode(struct ucred *cred, struct ksem *ks,
struct label *kslabel, mode_t mode)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(kslabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
return (0);
}
static int
biba_posixsem_check_setowner(struct ucred *cred, struct ksem *ks,
struct label *kslabel, uid_t uid, gid_t gid)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(kslabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
return (0);
}
static int
biba_posixsem_check_write(struct ucred *active_cred, struct ucred *file_cred,
struct ksem *ks, struct label *kslabel)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(active_cred->cr_label);
obj = SLOT(kslabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
return (0);
}
static int
biba_posixsem_check_rdonly(struct ucred *active_cred, struct ucred *file_cred,
struct ksem *ks, struct label *kslabel)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(active_cred->cr_label);
obj = SLOT(kslabel);
if (!biba_dominate_effective(obj, subj))
return (EACCES);
return (0);
}
static void
biba_posixsem_create(struct ucred *cred, struct ksem *ks,
struct label *kslabel)
{
struct mac_biba *source, *dest;
source = SLOT(cred->cr_label);
dest = SLOT(kslabel);
biba_copy_effective(source, dest);
}
static int
biba_posixshm_check_mmap(struct ucred *cred, struct shmfd *shmfd,
struct label *shmlabel, int prot, int flags)
{
struct mac_biba *subj, *obj;
if (!biba_enabled || !revocation_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(shmlabel);
if (prot & (VM_PROT_READ | VM_PROT_EXECUTE)) {
if (!biba_dominate_effective(obj, subj))
return (EACCES);
}
if (((prot & VM_PROT_WRITE) != 0) && ((flags & MAP_SHARED) != 0)) {
if (!biba_dominate_effective(subj, obj))
return (EACCES);
}
return (0);
}
static int
biba_posixshm_check_open(struct ucred *cred, struct shmfd *shmfd,
struct label *shmlabel, accmode_t accmode)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(shmlabel);
if (accmode & (VREAD | VEXEC | VSTAT_PERMS)) {
if (!biba_dominate_effective(obj, subj))
return (EACCES);
}
if (accmode & VMODIFY_PERMS) {
if (!biba_dominate_effective(subj, obj))
return (EACCES);
}
return (0);
}
static int
biba_posixshm_check_setmode(struct ucred *cred, struct shmfd *shmfd,
struct label *shmlabel, mode_t mode)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(shmlabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
return (0);
}
static int
biba_posixshm_check_setowner(struct ucred *cred, struct shmfd *shmfd,
struct label *shmlabel, uid_t uid, gid_t gid)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(shmlabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
return (0);
}
static int
biba_posixshm_check_stat(struct ucred *active_cred, struct ucred *file_cred,
struct shmfd *shmfd, struct label *shmlabel)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(active_cred->cr_label);
obj = SLOT(shmlabel);
if (!biba_dominate_effective(obj, subj))
return (EACCES);
return (0);
}
static int
biba_posixshm_check_truncate(struct ucred *active_cred,
struct ucred *file_cred, struct shmfd *shmfd, struct label *shmlabel)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(active_cred->cr_label);
obj = SLOT(shmlabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
return (0);
}
static int
biba_posixshm_check_unlink(struct ucred *cred, struct shmfd *shmfd,
struct label *shmlabel)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(shmlabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
return (0);
}
static void
biba_posixshm_create(struct ucred *cred, struct shmfd *shmfd,
struct label *shmlabel)
{
struct mac_biba *source, *dest;
source = SLOT(cred->cr_label);
dest = SLOT(shmlabel);
biba_copy_effective(source, dest);
}
/*
* Some system privileges are allowed regardless of integrity grade; others
* are allowed only when running with privilege with respect to the Biba
* policy as they might otherwise allow bypassing of the integrity policy.
*/
static int
biba_priv_check(struct ucred *cred, int priv)
{
struct mac_biba *subj;
int error;
if (!biba_enabled)
return (0);
/*
* Exempt only specific privileges from the Biba integrity policy.
*/
switch (priv) {
case PRIV_KTRACE:
case PRIV_MSGBUF:
/*
* Allow processes to manipulate basic process audit properties, and
* to submit audit records.
*/
case PRIV_AUDIT_GETAUDIT:
case PRIV_AUDIT_SETAUDIT:
case PRIV_AUDIT_SUBMIT:
/*
* Allow processes to manipulate their regular UNIX credentials.
*/
case PRIV_CRED_SETUID:
case PRIV_CRED_SETEUID:
case PRIV_CRED_SETGID:
case PRIV_CRED_SETEGID:
case PRIV_CRED_SETGROUPS:
case PRIV_CRED_SETREUID:
case PRIV_CRED_SETREGID:
case PRIV_CRED_SETRESUID:
case PRIV_CRED_SETRESGID:
/*
* Allow processes to perform system monitoring.
*/
case PRIV_SEEOTHERGIDS:
case PRIV_SEEOTHERUIDS:
break;
/*
* Allow access to general process debugging facilities. We
* separately control debugging based on MAC label.
*/
case PRIV_DEBUG_DIFFCRED:
case PRIV_DEBUG_SUGID:
case PRIV_DEBUG_UNPRIV:
/*
* Allow manipulating jails.
*/
case PRIV_JAIL_ATTACH:
/*
* Allow privilege with respect to the Partition policy, but not the
* Privs policy.
*/
case PRIV_MAC_PARTITION:
/*
* Allow privilege with respect to process resource limits and login
* context.
*/
case PRIV_PROC_LIMIT:
case PRIV_PROC_SETLOGIN:
case PRIV_PROC_SETRLIMIT:
/*
* Allow System V and POSIX IPC privileges.
*/
case PRIV_IPC_READ:
case PRIV_IPC_WRITE:
case PRIV_IPC_ADMIN:
case PRIV_IPC_MSGSIZE:
case PRIV_MQ_ADMIN:
/*
* Allow certain scheduler manipulations -- possibly this should be
* controlled by more fine-grained policy, as potentially low
* integrity processes can deny CPU to higher integrity ones.
*/
case PRIV_SCHED_DIFFCRED:
case PRIV_SCHED_SETPRIORITY:
case PRIV_SCHED_RTPRIO:
case PRIV_SCHED_SETPOLICY:
case PRIV_SCHED_SET:
case PRIV_SCHED_SETPARAM:
/*
* More IPC privileges.
*/
case PRIV_SEM_WRITE:
/*
* Allow signaling privileges subject to integrity policy.
*/
case PRIV_SIGNAL_DIFFCRED:
case PRIV_SIGNAL_SUGID:
/*
* Allow access to only limited sysctls from lower integrity levels;
* piggy-back on the Jail definition.
*/
case PRIV_SYSCTL_WRITEJAIL:
/*
* Allow TTY-based privileges, subject to general device access using
* labels on TTY device nodes, but not console privilege.
*/
case PRIV_TTY_DRAINWAIT:
case PRIV_TTY_DTRWAIT:
case PRIV_TTY_EXCLUSIVE:
case PRIV_TTY_STI:
case PRIV_TTY_SETA:
/*
* Grant most VFS privileges, as almost all are in practice bounded
* by more specific checks using labels.
*/
case PRIV_VFS_READ:
case PRIV_VFS_WRITE:
case PRIV_VFS_ADMIN:
case PRIV_VFS_EXEC:
case PRIV_VFS_LOOKUP:
case PRIV_VFS_CHFLAGS_DEV:
case PRIV_VFS_CHOWN:
case PRIV_VFS_CHROOT:
case PRIV_VFS_RETAINSUGID:
case PRIV_VFS_EXCEEDQUOTA:
case PRIV_VFS_FCHROOT:
case PRIV_VFS_FHOPEN:
case PRIV_VFS_FHSTATFS:
case PRIV_VFS_GENERATION:
case PRIV_VFS_GETFH:
case PRIV_VFS_GETQUOTA:
case PRIV_VFS_LINK:
case PRIV_VFS_MOUNT:
case PRIV_VFS_MOUNT_OWNER:
case PRIV_VFS_MOUNT_PERM:
case PRIV_VFS_MOUNT_SUIDDIR:
case PRIV_VFS_MOUNT_NONUSER:
case PRIV_VFS_SETGID:
case PRIV_VFS_STICKYFILE:
case PRIV_VFS_SYSFLAGS:
case PRIV_VFS_UNMOUNT:
/*
* Allow VM privileges; it would be nice if these were subject to
* resource limits.
*/
case PRIV_VM_MADV_PROTECT:
case PRIV_VM_MLOCK:
case PRIV_VM_MUNLOCK:
case PRIV_VM_SWAP_NOQUOTA:
case PRIV_VM_SWAP_NORLIMIT:
/*
* Allow some but not all network privileges. In general, dont allow
* reconfiguring the network stack, just normal use.
*/
case PRIV_NETATALK_RESERVEDPORT:
case PRIV_NETINET_RESERVEDPORT:
case PRIV_NETINET_RAW:
case PRIV_NETINET_REUSEPORT:
case PRIV_NETIPX_RESERVEDPORT:
case PRIV_NETIPX_RAW:
break;
/*
* All remaining system privileges are allow only if the process
* holds privilege with respect to the Biba policy.
*/
default:
subj = SLOT(cred->cr_label);
error = biba_subject_privileged(subj);
if (error)
return (error);
}
return (0);
}
static int
biba_proc_check_debug(struct ucred *cred, struct proc *p)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(p->p_ucred->cr_label);
/* XXX: range checks */
if (!biba_dominate_effective(obj, subj))
return (ESRCH);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
return (0);
}
static int
biba_proc_check_sched(struct ucred *cred, struct proc *p)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(p->p_ucred->cr_label);
/* XXX: range checks */
if (!biba_dominate_effective(obj, subj))
return (ESRCH);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
return (0);
}
static int
biba_proc_check_signal(struct ucred *cred, struct proc *p, int signum)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(p->p_ucred->cr_label);
/* XXX: range checks */
if (!biba_dominate_effective(obj, subj))
return (ESRCH);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
return (0);
}
static int
biba_socket_check_deliver(struct socket *so, struct label *solabel,
struct mbuf *m, struct label *mlabel)
{
struct mac_biba *p, *s;
int error;
if (!biba_enabled)
return (0);
p = SLOT(mlabel);
s = SLOT(solabel);
SOCK_LOCK(so);
error = biba_equal_effective(p, s) ? 0 : EACCES;
SOCK_UNLOCK(so);
return (error);
}
static int
biba_socket_check_relabel(struct ucred *cred, struct socket *so,
struct label *solabel, struct label *newlabel)
{
struct mac_biba *subj, *obj, *new;
int error;
SOCK_LOCK_ASSERT(so);
new = SLOT(newlabel);
subj = SLOT(cred->cr_label);
obj = SLOT(solabel);
/*
* If there is a Biba label update for the socket, it may be an
* update of effective.
*/
error = biba_atmostflags(new, MAC_BIBA_FLAG_EFFECTIVE);
if (error)
return (error);
/*
* To relabel a socket, the old socket effective must be in the
* subject range.
*/
if (!biba_effective_in_range(obj, subj))
return (EPERM);
/*
* If the Biba label is to be changed, authorize as appropriate.
*/
if (new->mb_flags & MAC_BIBA_FLAG_EFFECTIVE) {
/*
* To relabel a socket, the new socket effective must be in
* the subject range.
*/
if (!biba_effective_in_range(new, subj))
return (EPERM);
/*
* To change the Biba label on the socket to contain EQUAL,
* the subject must have appropriate privilege.
*/
if (biba_contains_equal(new)) {
error = biba_subject_privileged(subj);
if (error)
return (error);
}
}
return (0);
}
static int
biba_socket_check_visible(struct ucred *cred, struct socket *so,
struct label *solabel)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(solabel);
SOCK_LOCK(so);
if (!biba_dominate_effective(obj, subj)) {
SOCK_UNLOCK(so);
return (ENOENT);
}
SOCK_UNLOCK(so);
return (0);
}
static void
biba_socket_create(struct ucred *cred, struct socket *so,
struct label *solabel)
{
struct mac_biba *source, *dest;
source = SLOT(cred->cr_label);
dest = SLOT(solabel);
biba_copy_effective(source, dest);
}
static void
biba_socket_create_mbuf(struct socket *so, struct label *solabel,
struct mbuf *m, struct label *mlabel)
{
struct mac_biba *source, *dest;
source = SLOT(solabel);
dest = SLOT(mlabel);
SOCK_LOCK(so);
biba_copy_effective(source, dest);
SOCK_UNLOCK(so);
}
static void
biba_socket_newconn(struct socket *oldso, struct label *oldsolabel,
struct socket *newso, struct label *newsolabel)
{
struct mac_biba source, *dest;
SOCK_LOCK(oldso);
source = *SLOT(oldsolabel);
SOCK_UNLOCK(oldso);
dest = SLOT(newsolabel);
SOCK_LOCK(newso);
biba_copy_effective(&source, dest);
SOCK_UNLOCK(newso);
}
static void
biba_socket_relabel(struct ucred *cred, struct socket *so,
struct label *solabel, struct label *newlabel)
{
struct mac_biba *source, *dest;
SOCK_LOCK_ASSERT(so);
source = SLOT(newlabel);
dest = SLOT(solabel);
biba_copy(source, dest);
}
static void
biba_socketpeer_set_from_mbuf(struct mbuf *m, struct label *mlabel,
struct socket *so, struct label *sopeerlabel)
{
struct mac_biba *source, *dest;
source = SLOT(mlabel);
dest = SLOT(sopeerlabel);
SOCK_LOCK(so);
biba_copy_effective(source, dest);
SOCK_UNLOCK(so);
}
static void
biba_socketpeer_set_from_socket(struct socket *oldso,
struct label *oldsolabel, struct socket *newso,
struct label *newsopeerlabel)
{
struct mac_biba source, *dest;
SOCK_LOCK(oldso);
source = *SLOT(oldsolabel);
SOCK_UNLOCK(oldso);
dest = SLOT(newsopeerlabel);
SOCK_LOCK(newso);
biba_copy_effective(&source, dest);
SOCK_UNLOCK(newso);
}
static void
biba_syncache_create(struct label *label, struct inpcb *inp)
{
struct mac_biba *source, *dest;
source = SLOT(inp->inp_label);
dest = SLOT(label);
biba_copy_effective(source, dest);
}
static void
biba_syncache_create_mbuf(struct label *sc_label, struct mbuf *m,
struct label *mlabel)
{
struct mac_biba *source, *dest;
source = SLOT(sc_label);
dest = SLOT(mlabel);
biba_copy_effective(source, dest);
}
static int
biba_system_check_acct(struct ucred *cred, struct vnode *vp,
struct label *vplabel)
{
struct mac_biba *subj, *obj;
int error;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
error = biba_subject_privileged(subj);
if (error)
return (error);
if (vplabel == NULL)
return (0);
obj = SLOT(vplabel);
if (!biba_high_effective(obj))
return (EACCES);
return (0);
}
static int
biba_system_check_auditctl(struct ucred *cred, struct vnode *vp,
struct label *vplabel)
{
struct mac_biba *subj, *obj;
int error;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
error = biba_subject_privileged(subj);
if (error)
return (error);
if (vplabel == NULL)
return (0);
obj = SLOT(vplabel);
if (!biba_high_effective(obj))
return (EACCES);
return (0);
}
static int
biba_system_check_auditon(struct ucred *cred, int cmd)
{
struct mac_biba *subj;
int error;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
error = biba_subject_privileged(subj);
if (error)
return (error);
return (0);
}
static int
biba_system_check_swapoff(struct ucred *cred, struct vnode *vp,
struct label *label)
{
struct mac_biba *subj;
int error;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
error = biba_subject_privileged(subj);
if (error)
return (error);
return (0);
}
static int
biba_system_check_swapon(struct ucred *cred, struct vnode *vp,
struct label *vplabel)
{
struct mac_biba *subj, *obj;
int error;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(vplabel);
error = biba_subject_privileged(subj);
if (error)
return (error);
if (!biba_high_effective(obj))
return (EACCES);
return (0);
}
static int
biba_system_check_sysctl(struct ucred *cred, struct sysctl_oid *oidp,
void *arg1, int arg2, struct sysctl_req *req)
{
struct mac_biba *subj;
int error;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
/*
* Treat sysctl variables without CTLFLAG_ANYBODY flag as biba/high,
* but also require privilege to change them.
*/
if (req->newptr != NULL && (oidp->oid_kind & CTLFLAG_ANYBODY) == 0) {
if (!biba_subject_dominate_high(subj))
return (EACCES);
error = biba_subject_privileged(subj);
if (error)
return (error);
}
return (0);
}
static void
biba_sysvmsg_cleanup(struct label *msglabel)
{
bzero(SLOT(msglabel), sizeof(struct mac_biba));
}
static void
biba_sysvmsg_create(struct ucred *cred, struct msqid_kernel *msqkptr,
struct label *msqlabel, struct msg *msgptr, struct label *msglabel)
{
struct mac_biba *source, *dest;
/* Ignore the msgq label */
source = SLOT(cred->cr_label);
dest = SLOT(msglabel);
biba_copy_effective(source, dest);
}
static int
biba_sysvmsq_check_msgrcv(struct ucred *cred, struct msg *msgptr,
struct label *msglabel)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(msglabel);
if (!biba_dominate_effective(obj, subj))
return (EACCES);
return (0);
}
static int
biba_sysvmsq_check_msgrmid(struct ucred *cred, struct msg *msgptr,
struct label *msglabel)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(msglabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
return (0);
}
static int
biba_sysvmsq_check_msqget(struct ucred *cred, struct msqid_kernel *msqkptr,
struct label *msqklabel)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(msqklabel);
if (!biba_dominate_effective(obj, subj))
return (EACCES);
return (0);
}
static int
biba_sysvmsq_check_msqsnd(struct ucred *cred, struct msqid_kernel *msqkptr,
struct label *msqklabel)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(msqklabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
return (0);
}
static int
biba_sysvmsq_check_msqrcv(struct ucred *cred, struct msqid_kernel *msqkptr,
struct label *msqklabel)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(msqklabel);
if (!biba_dominate_effective(obj, subj))
return (EACCES);
return (0);
}
static int
biba_sysvmsq_check_msqctl(struct ucred *cred, struct msqid_kernel *msqkptr,
struct label *msqklabel, int cmd)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(msqklabel);
switch(cmd) {
case IPC_RMID:
case IPC_SET:
if (!biba_dominate_effective(subj, obj))
return (EACCES);
break;
case IPC_STAT:
if (!biba_dominate_effective(obj, subj))
return (EACCES);
break;
default:
return (EACCES);
}
return (0);
}
static void
biba_sysvmsq_cleanup(struct label *msqlabel)
{
bzero(SLOT(msqlabel), sizeof(struct mac_biba));
}
static void
biba_sysvmsq_create(struct ucred *cred, struct msqid_kernel *msqkptr,
struct label *msqlabel)
{
struct mac_biba *source, *dest;
source = SLOT(cred->cr_label);
dest = SLOT(msqlabel);
biba_copy_effective(source, dest);
}
static int
biba_sysvsem_check_semctl(struct ucred *cred, struct semid_kernel *semakptr,
struct label *semaklabel, int cmd)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(semaklabel);
switch(cmd) {
case IPC_RMID:
case IPC_SET:
case SETVAL:
case SETALL:
if (!biba_dominate_effective(subj, obj))
return (EACCES);
break;
case IPC_STAT:
case GETVAL:
case GETPID:
case GETNCNT:
case GETZCNT:
case GETALL:
if (!biba_dominate_effective(obj, subj))
return (EACCES);
break;
default:
return (EACCES);
}
return (0);
}
static int
biba_sysvsem_check_semget(struct ucred *cred, struct semid_kernel *semakptr,
struct label *semaklabel)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(semaklabel);
if (!biba_dominate_effective(obj, subj))
return (EACCES);
return (0);
}
static int
biba_sysvsem_check_semop(struct ucred *cred, struct semid_kernel *semakptr,
struct label *semaklabel, size_t accesstype)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(semaklabel);
if (accesstype & SEM_R)
if (!biba_dominate_effective(obj, subj))
return (EACCES);
if (accesstype & SEM_A)
if (!biba_dominate_effective(subj, obj))
return (EACCES);
return (0);
}
static void
biba_sysvsem_cleanup(struct label *semalabel)
{
bzero(SLOT(semalabel), sizeof(struct mac_biba));
}
static void
biba_sysvsem_create(struct ucred *cred, struct semid_kernel *semakptr,
struct label *semalabel)
{
struct mac_biba *source, *dest;
source = SLOT(cred->cr_label);
dest = SLOT(semalabel);
biba_copy_effective(source, dest);
}
static int
biba_sysvshm_check_shmat(struct ucred *cred, struct shmid_kernel *shmsegptr,
struct label *shmseglabel, int shmflg)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(shmseglabel);
if (!biba_dominate_effective(obj, subj))
return (EACCES);
if ((shmflg & SHM_RDONLY) == 0) {
if (!biba_dominate_effective(subj, obj))
return (EACCES);
}
return (0);
}
static int
biba_sysvshm_check_shmctl(struct ucred *cred, struct shmid_kernel *shmsegptr,
struct label *shmseglabel, int cmd)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(shmseglabel);
switch(cmd) {
case IPC_RMID:
case IPC_SET:
if (!biba_dominate_effective(subj, obj))
return (EACCES);
break;
case IPC_STAT:
case SHM_STAT:
if (!biba_dominate_effective(obj, subj))
return (EACCES);
break;
default:
return (EACCES);
}
return (0);
}
static int
biba_sysvshm_check_shmget(struct ucred *cred, struct shmid_kernel *shmsegptr,
struct label *shmseglabel, int shmflg)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(shmseglabel);
if (!biba_dominate_effective(obj, subj))
return (EACCES);
return (0);
}
static void
biba_sysvshm_cleanup(struct label *shmlabel)
{
bzero(SLOT(shmlabel), sizeof(struct mac_biba));
}
static void
biba_sysvshm_create(struct ucred *cred, struct shmid_kernel *shmsegptr,
struct label *shmlabel)
{
struct mac_biba *source, *dest;
source = SLOT(cred->cr_label);
dest = SLOT(shmlabel);
biba_copy_effective(source, dest);
}
static int
biba_vnode_associate_extattr(struct mount *mp, struct label *mplabel,
struct vnode *vp, struct label *vplabel)
{
struct mac_biba mb_temp, *source, *dest;
int buflen, error;
source = SLOT(mplabel);
dest = SLOT(vplabel);
buflen = sizeof(mb_temp);
bzero(&mb_temp, buflen);
error = vn_extattr_get(vp, IO_NODELOCKED, MAC_BIBA_EXTATTR_NAMESPACE,
MAC_BIBA_EXTATTR_NAME, &buflen, (char *) &mb_temp, curthread);
if (error == ENOATTR || error == EOPNOTSUPP) {
/* Fall back to the mntlabel. */
biba_copy_effective(source, dest);
return (0);
} else if (error)
return (error);
if (buflen != sizeof(mb_temp)) {
printf("biba_vnode_associate_extattr: bad size %d\n",
buflen);
return (EPERM);
}
if (biba_valid(&mb_temp) != 0) {
printf("biba_vnode_associate_extattr: invalid\n");
return (EPERM);
}
if ((mb_temp.mb_flags & MAC_BIBA_FLAGS_BOTH) !=
MAC_BIBA_FLAG_EFFECTIVE) {
printf("biba_vnode_associate_extattr: not effective\n");
return (EPERM);
}
biba_copy_effective(&mb_temp, dest);
return (0);
}
static void
biba_vnode_associate_singlelabel(struct mount *mp, struct label *mplabel,
struct vnode *vp, struct label *vplabel)
{
struct mac_biba *source, *dest;
source = SLOT(mplabel);
dest = SLOT(vplabel);
biba_copy_effective(source, dest);
}
static int
biba_vnode_check_chdir(struct ucred *cred, struct vnode *dvp,
struct label *dvplabel)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(dvplabel);
if (!biba_dominate_effective(obj, subj))
return (EACCES);
return (0);
}
static int
biba_vnode_check_chroot(struct ucred *cred, struct vnode *dvp,
struct label *dvplabel)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(dvplabel);
if (!biba_dominate_effective(obj, subj))
return (EACCES);
return (0);
}
static int
biba_vnode_check_create(struct ucred *cred, struct vnode *dvp,
struct label *dvplabel, struct componentname *cnp, struct vattr *vap)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(dvplabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
return (0);
}
static int
biba_vnode_check_deleteacl(struct ucred *cred, struct vnode *vp,
struct label *vplabel, acl_type_t type)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(vplabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
return (0);
}
static int
biba_vnode_check_deleteextattr(struct ucred *cred, struct vnode *vp,
struct label *vplabel, int attrnamespace, const char *name)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(vplabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
return (0);
}
static int
biba_vnode_check_exec(struct ucred *cred, struct vnode *vp,
struct label *vplabel, struct image_params *imgp,
struct label *execlabel)
{
struct mac_biba *subj, *obj, *exec;
int error;
if (execlabel != NULL) {
/*
* We currently don't permit labels to be changed at
* exec-time as part of Biba, so disallow non-NULL Biba label
* elements in the execlabel.
*/
exec = SLOT(execlabel);
error = biba_atmostflags(exec, 0);
if (error)
return (error);
}
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(vplabel);
if (!biba_dominate_effective(obj, subj))
return (EACCES);
return (0);
}
static int
biba_vnode_check_getacl(struct ucred *cred, struct vnode *vp,
struct label *vplabel, acl_type_t type)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(vplabel);
if (!biba_dominate_effective(obj, subj))
return (EACCES);
return (0);
}
static int
biba_vnode_check_getextattr(struct ucred *cred, struct vnode *vp,
struct label *vplabel, int attrnamespace, const char *name)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(vplabel);
if (!biba_dominate_effective(obj, subj))
return (EACCES);
return (0);
}
static int
biba_vnode_check_link(struct ucred *cred, struct vnode *dvp,
struct label *dvplabel, struct vnode *vp, struct label *vplabel,
struct componentname *cnp)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(dvplabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
obj = SLOT(vplabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
return (0);
}
static int
biba_vnode_check_listextattr(struct ucred *cred, struct vnode *vp,
struct label *vplabel, int attrnamespace)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(vplabel);
if (!biba_dominate_effective(obj, subj))
return (EACCES);
return (0);
}
static int
biba_vnode_check_lookup(struct ucred *cred, struct vnode *dvp,
struct label *dvplabel, struct componentname *cnp)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(dvplabel);
if (!biba_dominate_effective(obj, subj))
return (EACCES);
return (0);
}
static int
biba_vnode_check_mmap(struct ucred *cred, struct vnode *vp,
struct label *vplabel, int prot, int flags)
{
struct mac_biba *subj, *obj;
/*
* Rely on the use of open()-time protections to handle
* non-revocation cases.
*/
if (!biba_enabled || !revocation_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(vplabel);
if (prot & (VM_PROT_READ | VM_PROT_EXECUTE)) {
if (!biba_dominate_effective(obj, subj))
return (EACCES);
}
if (((prot & VM_PROT_WRITE) != 0) && ((flags & MAP_SHARED) != 0)) {
if (!biba_dominate_effective(subj, obj))
return (EACCES);
}
return (0);
}
static int
biba_vnode_check_open(struct ucred *cred, struct vnode *vp,
struct label *vplabel, accmode_t accmode)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(vplabel);
/* XXX privilege override for admin? */
if (accmode & (VREAD | VEXEC | VSTAT_PERMS)) {
if (!biba_dominate_effective(obj, subj))
return (EACCES);
}
if (accmode & VMODIFY_PERMS) {
if (!biba_dominate_effective(subj, obj))
return (EACCES);
}
return (0);
}
static int
biba_vnode_check_poll(struct ucred *active_cred, struct ucred *file_cred,
struct vnode *vp, struct label *vplabel)
{
struct mac_biba *subj, *obj;
if (!biba_enabled || !revocation_enabled)
return (0);
subj = SLOT(active_cred->cr_label);
obj = SLOT(vplabel);
if (!biba_dominate_effective(obj, subj))
return (EACCES);
return (0);
}
static int
biba_vnode_check_read(struct ucred *active_cred, struct ucred *file_cred,
struct vnode *vp, struct label *vplabel)
{
struct mac_biba *subj, *obj;
if (!biba_enabled || !revocation_enabled)
return (0);
subj = SLOT(active_cred->cr_label);
obj = SLOT(vplabel);
if (!biba_dominate_effective(obj, subj))
return (EACCES);
return (0);
}
static int
biba_vnode_check_readdir(struct ucred *cred, struct vnode *dvp,
struct label *dvplabel)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(dvplabel);
if (!biba_dominate_effective(obj, subj))
return (EACCES);
return (0);
}
static int
biba_vnode_check_readlink(struct ucred *cred, struct vnode *vp,
struct label *vplabel)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(vplabel);
if (!biba_dominate_effective(obj, subj))
return (EACCES);
return (0);
}
static int
biba_vnode_check_relabel(struct ucred *cred, struct vnode *vp,
struct label *vplabel, struct label *newlabel)
{
struct mac_biba *old, *new, *subj;
int error;
old = SLOT(vplabel);
new = SLOT(newlabel);
subj = SLOT(cred->cr_label);
/*
* If there is a Biba label update for the vnode, it must be a
* effective label.
*/
error = biba_atmostflags(new, MAC_BIBA_FLAG_EFFECTIVE);
if (error)
return (error);
/*
* To perform a relabel of the vnode (Biba label or not), Biba must
* authorize the relabel.
*/
if (!biba_effective_in_range(old, subj))
return (EPERM);
/*
* If the Biba label is to be changed, authorize as appropriate.
*/
if (new->mb_flags & MAC_BIBA_FLAG_EFFECTIVE) {
/*
* To change the Biba label on a vnode, the new vnode label
* must be in the subject range.
*/
if (!biba_effective_in_range(new, subj))
return (EPERM);
/*
* To change the Biba label on the vnode to be EQUAL, the
* subject must have appropriate privilege.
*/
if (biba_contains_equal(new)) {
error = biba_subject_privileged(subj);
if (error)
return (error);
}
}
return (0);
}
static int
biba_vnode_check_rename_from(struct ucred *cred, struct vnode *dvp,
struct label *dvplabel, struct vnode *vp, struct label *vplabel,
struct componentname *cnp)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(dvplabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
obj = SLOT(vplabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
return (0);
}
static int
biba_vnode_check_rename_to(struct ucred *cred, struct vnode *dvp,
struct label *dvplabel, struct vnode *vp, struct label *vplabel,
int samedir, struct componentname *cnp)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(dvplabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
if (vp != NULL) {
obj = SLOT(vplabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
}
return (0);
}
static int
biba_vnode_check_revoke(struct ucred *cred, struct vnode *vp,
struct label *vplabel)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(vplabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
return (0);
}
static int
biba_vnode_check_setacl(struct ucred *cred, struct vnode *vp,
struct label *vplabel, acl_type_t type, struct acl *acl)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(vplabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
return (0);
}
static int
biba_vnode_check_setextattr(struct ucred *cred, struct vnode *vp,
struct label *vplabel, int attrnamespace, const char *name)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(vplabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
/* XXX: protect the MAC EA in a special way? */
return (0);
}
static int
biba_vnode_check_setflags(struct ucred *cred, struct vnode *vp,
struct label *vplabel, u_long flags)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(vplabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
return (0);
}
static int
biba_vnode_check_setmode(struct ucred *cred, struct vnode *vp,
struct label *vplabel, mode_t mode)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(vplabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
return (0);
}
static int
biba_vnode_check_setowner(struct ucred *cred, struct vnode *vp,
struct label *vplabel, uid_t uid, gid_t gid)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(vplabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
return (0);
}
static int
biba_vnode_check_setutimes(struct ucred *cred, struct vnode *vp,
struct label *vplabel, struct timespec atime, struct timespec mtime)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(vplabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
return (0);
}
static int
biba_vnode_check_stat(struct ucred *active_cred, struct ucred *file_cred,
struct vnode *vp, struct label *vplabel)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(active_cred->cr_label);
obj = SLOT(vplabel);
if (!biba_dominate_effective(obj, subj))
return (EACCES);
return (0);
}
static int
biba_vnode_check_unlink(struct ucred *cred, struct vnode *dvp,
struct label *dvplabel, struct vnode *vp, struct label *vplabel,
struct componentname *cnp)
{
struct mac_biba *subj, *obj;
if (!biba_enabled)
return (0);
subj = SLOT(cred->cr_label);
obj = SLOT(dvplabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
obj = SLOT(vplabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
return (0);
}
static int
biba_vnode_check_write(struct ucred *active_cred,
struct ucred *file_cred, struct vnode *vp, struct label *vplabel)
{
struct mac_biba *subj, *obj;
if (!biba_enabled || !revocation_enabled)
return (0);
subj = SLOT(active_cred->cr_label);
obj = SLOT(vplabel);
if (!biba_dominate_effective(subj, obj))
return (EACCES);
return (0);
}
static int
biba_vnode_create_extattr(struct ucred *cred, struct mount *mp,
struct label *mplabel, struct vnode *dvp, struct label *dvplabel,
struct vnode *vp, struct label *vplabel, struct componentname *cnp)
{
struct mac_biba *source, *dest, mb_temp;
size_t buflen;
int error;
buflen = sizeof(mb_temp);
bzero(&mb_temp, buflen);
source = SLOT(cred->cr_label);
dest = SLOT(vplabel);
biba_copy_effective(source, &mb_temp);
error = vn_extattr_set(vp, IO_NODELOCKED, MAC_BIBA_EXTATTR_NAMESPACE,
MAC_BIBA_EXTATTR_NAME, buflen, (char *) &mb_temp, curthread);
if (error == 0)
biba_copy_effective(source, dest);
return (error);
}
static void
biba_vnode_relabel(struct ucred *cred, struct vnode *vp,
struct label *vplabel, struct label *newlabel)
{
struct mac_biba *source, *dest;
source = SLOT(newlabel);
dest = SLOT(vplabel);
biba_copy(source, dest);
}
static int
biba_vnode_setlabel_extattr(struct ucred *cred, struct vnode *vp,
struct label *vplabel, struct label *intlabel)
{
struct mac_biba *source, mb_temp;
size_t buflen;
int error;
buflen = sizeof(mb_temp);
bzero(&mb_temp, buflen);
source = SLOT(intlabel);
if ((source->mb_flags & MAC_BIBA_FLAG_EFFECTIVE) == 0)
return (0);
biba_copy_effective(source, &mb_temp);
error = vn_extattr_set(vp, IO_NODELOCKED, MAC_BIBA_EXTATTR_NAMESPACE,
MAC_BIBA_EXTATTR_NAME, buflen, (char *) &mb_temp, curthread);
return (error);
}
static struct mac_policy_ops mac_biba_ops =
{
.mpo_init = biba_init,
.mpo_bpfdesc_check_receive = biba_bpfdesc_check_receive,
.mpo_bpfdesc_create = biba_bpfdesc_create,
.mpo_bpfdesc_create_mbuf = biba_bpfdesc_create_mbuf,
.mpo_bpfdesc_destroy_label = biba_destroy_label,
.mpo_bpfdesc_init_label = biba_init_label,
.mpo_cred_associate_nfsd = biba_cred_associate_nfsd,
.mpo_cred_check_relabel = biba_cred_check_relabel,
.mpo_cred_check_visible = biba_cred_check_visible,
.mpo_cred_copy_label = biba_copy_label,
.mpo_cred_create_init = biba_cred_create_init,
.mpo_cred_create_swapper = biba_cred_create_swapper,
.mpo_cred_destroy_label = biba_destroy_label,
.mpo_cred_externalize_label = biba_externalize_label,
.mpo_cred_init_label = biba_init_label,
.mpo_cred_internalize_label = biba_internalize_label,
.mpo_cred_relabel = biba_cred_relabel,
.mpo_devfs_create_device = biba_devfs_create_device,
.mpo_devfs_create_directory = biba_devfs_create_directory,
.mpo_devfs_create_symlink = biba_devfs_create_symlink,
.mpo_devfs_destroy_label = biba_destroy_label,
.mpo_devfs_init_label = biba_init_label,
.mpo_devfs_update = biba_devfs_update,
.mpo_devfs_vnode_associate = biba_devfs_vnode_associate,
.mpo_ifnet_check_relabel = biba_ifnet_check_relabel,
.mpo_ifnet_check_transmit = biba_ifnet_check_transmit,
.mpo_ifnet_copy_label = biba_copy_label,
.mpo_ifnet_create = biba_ifnet_create,
.mpo_ifnet_create_mbuf = biba_ifnet_create_mbuf,
.mpo_ifnet_destroy_label = biba_destroy_label,
.mpo_ifnet_externalize_label = biba_externalize_label,
.mpo_ifnet_init_label = biba_init_label,
.mpo_ifnet_internalize_label = biba_internalize_label,
.mpo_ifnet_relabel = biba_ifnet_relabel,
.mpo_inpcb_check_deliver = biba_inpcb_check_deliver,
.mpo_inpcb_check_visible = biba_inpcb_check_visible,
.mpo_inpcb_create = biba_inpcb_create,
.mpo_inpcb_create_mbuf = biba_inpcb_create_mbuf,
.mpo_inpcb_destroy_label = biba_destroy_label,
.mpo_inpcb_init_label = biba_init_label_waitcheck,
.mpo_inpcb_sosetlabel = biba_inpcb_sosetlabel,
.mpo_ip6q_create = biba_ip6q_create,
.mpo_ip6q_destroy_label = biba_destroy_label,
.mpo_ip6q_init_label = biba_init_label_waitcheck,
.mpo_ip6q_match = biba_ip6q_match,
.mpo_ip6q_reassemble = biba_ip6q_reassemble,
.mpo_ip6q_update = biba_ip6q_update,
.mpo_ipq_create = biba_ipq_create,
.mpo_ipq_destroy_label = biba_destroy_label,
.mpo_ipq_init_label = biba_init_label_waitcheck,
.mpo_ipq_match = biba_ipq_match,
.mpo_ipq_reassemble = biba_ipq_reassemble,
.mpo_ipq_update = biba_ipq_update,
.mpo_kld_check_load = biba_kld_check_load,
.mpo_mbuf_copy_label = biba_copy_label,
.mpo_mbuf_destroy_label = biba_destroy_label,
.mpo_mbuf_init_label = biba_init_label_waitcheck,
.mpo_mount_check_stat = biba_mount_check_stat,
.mpo_mount_create = biba_mount_create,
.mpo_mount_destroy_label = biba_destroy_label,
.mpo_mount_init_label = biba_init_label,
.mpo_netatalk_aarp_send = biba_netatalk_aarp_send,
.mpo_netinet_arp_send = biba_netinet_arp_send,
.mpo_netinet_firewall_reply = biba_netinet_firewall_reply,
.mpo_netinet_firewall_send = biba_netinet_firewall_send,
.mpo_netinet_fragment = biba_netinet_fragment,
.mpo_netinet_icmp_reply = biba_netinet_icmp_reply,
.mpo_netinet_igmp_send = biba_netinet_igmp_send,
.mpo_netinet6_nd6_send = biba_netinet6_nd6_send,
.mpo_pipe_check_ioctl = biba_pipe_check_ioctl,
.mpo_pipe_check_poll = biba_pipe_check_poll,
.mpo_pipe_check_read = biba_pipe_check_read,
.mpo_pipe_check_relabel = biba_pipe_check_relabel,
.mpo_pipe_check_stat = biba_pipe_check_stat,
.mpo_pipe_check_write = biba_pipe_check_write,
.mpo_pipe_copy_label = biba_copy_label,
.mpo_pipe_create = biba_pipe_create,
.mpo_pipe_destroy_label = biba_destroy_label,
.mpo_pipe_externalize_label = biba_externalize_label,
.mpo_pipe_init_label = biba_init_label,
.mpo_pipe_internalize_label = biba_internalize_label,
.mpo_pipe_relabel = biba_pipe_relabel,
.mpo_posixsem_check_getvalue = biba_posixsem_check_rdonly,
.mpo_posixsem_check_open = biba_posixsem_check_openunlink,
.mpo_posixsem_check_post = biba_posixsem_check_write,
.mpo_posixsem_check_setmode = biba_posixsem_check_setmode,
.mpo_posixsem_check_setowner = biba_posixsem_check_setowner,
.mpo_posixsem_check_stat = biba_posixsem_check_rdonly,
.mpo_posixsem_check_unlink = biba_posixsem_check_openunlink,
.mpo_posixsem_check_wait = biba_posixsem_check_write,
.mpo_posixsem_create = biba_posixsem_create,
.mpo_posixsem_destroy_label = biba_destroy_label,
.mpo_posixsem_init_label = biba_init_label,
.mpo_posixshm_check_mmap = biba_posixshm_check_mmap,
.mpo_posixshm_check_open = biba_posixshm_check_open,
.mpo_posixshm_check_setmode = biba_posixshm_check_setmode,
.mpo_posixshm_check_setowner = biba_posixshm_check_setowner,
.mpo_posixshm_check_stat = biba_posixshm_check_stat,
.mpo_posixshm_check_truncate = biba_posixshm_check_truncate,
.mpo_posixshm_check_unlink = biba_posixshm_check_unlink,
.mpo_posixshm_create = biba_posixshm_create,
.mpo_posixshm_destroy_label = biba_destroy_label,
.mpo_posixshm_init_label = biba_init_label,
.mpo_priv_check = biba_priv_check,
.mpo_proc_check_debug = biba_proc_check_debug,
.mpo_proc_check_sched = biba_proc_check_sched,
.mpo_proc_check_signal = biba_proc_check_signal,
.mpo_socket_check_deliver = biba_socket_check_deliver,
.mpo_socket_check_relabel = biba_socket_check_relabel,
.mpo_socket_check_visible = biba_socket_check_visible,
.mpo_socket_copy_label = biba_copy_label,
.mpo_socket_create = biba_socket_create,
.mpo_socket_create_mbuf = biba_socket_create_mbuf,
.mpo_socket_destroy_label = biba_destroy_label,
.mpo_socket_externalize_label = biba_externalize_label,
.mpo_socket_init_label = biba_init_label_waitcheck,
.mpo_socket_internalize_label = biba_internalize_label,
.mpo_socket_newconn = biba_socket_newconn,
.mpo_socket_relabel = biba_socket_relabel,
.mpo_socketpeer_destroy_label = biba_destroy_label,
.mpo_socketpeer_externalize_label = biba_externalize_label,
.mpo_socketpeer_init_label = biba_init_label_waitcheck,
.mpo_socketpeer_set_from_mbuf = biba_socketpeer_set_from_mbuf,
.mpo_socketpeer_set_from_socket = biba_socketpeer_set_from_socket,
.mpo_syncache_create = biba_syncache_create,
.mpo_syncache_create_mbuf = biba_syncache_create_mbuf,
.mpo_syncache_destroy_label = biba_destroy_label,
.mpo_syncache_init_label = biba_init_label_waitcheck,
.mpo_system_check_acct = biba_system_check_acct,
.mpo_system_check_auditctl = biba_system_check_auditctl,
.mpo_system_check_auditon = biba_system_check_auditon,
.mpo_system_check_swapoff = biba_system_check_swapoff,
.mpo_system_check_swapon = biba_system_check_swapon,
.mpo_system_check_sysctl = biba_system_check_sysctl,
.mpo_sysvmsg_cleanup = biba_sysvmsg_cleanup,
.mpo_sysvmsg_create = biba_sysvmsg_create,
.mpo_sysvmsg_destroy_label = biba_destroy_label,
.mpo_sysvmsg_init_label = biba_init_label,
.mpo_sysvmsq_check_msgrcv = biba_sysvmsq_check_msgrcv,
.mpo_sysvmsq_check_msgrmid = biba_sysvmsq_check_msgrmid,
.mpo_sysvmsq_check_msqget = biba_sysvmsq_check_msqget,
.mpo_sysvmsq_check_msqsnd = biba_sysvmsq_check_msqsnd,
.mpo_sysvmsq_check_msqrcv = biba_sysvmsq_check_msqrcv,
.mpo_sysvmsq_check_msqctl = biba_sysvmsq_check_msqctl,
.mpo_sysvmsq_cleanup = biba_sysvmsq_cleanup,
.mpo_sysvmsq_create = biba_sysvmsq_create,
.mpo_sysvmsq_destroy_label = biba_destroy_label,
.mpo_sysvmsq_init_label = biba_init_label,
.mpo_sysvsem_check_semctl = biba_sysvsem_check_semctl,
.mpo_sysvsem_check_semget = biba_sysvsem_check_semget,
.mpo_sysvsem_check_semop = biba_sysvsem_check_semop,
.mpo_sysvsem_cleanup = biba_sysvsem_cleanup,
.mpo_sysvsem_create = biba_sysvsem_create,
.mpo_sysvsem_destroy_label = biba_destroy_label,
.mpo_sysvsem_init_label = biba_init_label,
.mpo_sysvshm_check_shmat = biba_sysvshm_check_shmat,
.mpo_sysvshm_check_shmctl = biba_sysvshm_check_shmctl,
.mpo_sysvshm_check_shmget = biba_sysvshm_check_shmget,
.mpo_sysvshm_cleanup = biba_sysvshm_cleanup,
.mpo_sysvshm_create = biba_sysvshm_create,
.mpo_sysvshm_destroy_label = biba_destroy_label,
.mpo_sysvshm_init_label = biba_init_label,
.mpo_vnode_associate_extattr = biba_vnode_associate_extattr,
.mpo_vnode_associate_singlelabel = biba_vnode_associate_singlelabel,
.mpo_vnode_check_access = biba_vnode_check_open,
.mpo_vnode_check_chdir = biba_vnode_check_chdir,
.mpo_vnode_check_chroot = biba_vnode_check_chroot,
.mpo_vnode_check_create = biba_vnode_check_create,
.mpo_vnode_check_deleteacl = biba_vnode_check_deleteacl,
.mpo_vnode_check_deleteextattr = biba_vnode_check_deleteextattr,
.mpo_vnode_check_exec = biba_vnode_check_exec,
.mpo_vnode_check_getacl = biba_vnode_check_getacl,
.mpo_vnode_check_getextattr = biba_vnode_check_getextattr,
.mpo_vnode_check_link = biba_vnode_check_link,
.mpo_vnode_check_listextattr = biba_vnode_check_listextattr,
.mpo_vnode_check_lookup = biba_vnode_check_lookup,
.mpo_vnode_check_mmap = biba_vnode_check_mmap,
.mpo_vnode_check_open = biba_vnode_check_open,
.mpo_vnode_check_poll = biba_vnode_check_poll,
.mpo_vnode_check_read = biba_vnode_check_read,
.mpo_vnode_check_readdir = biba_vnode_check_readdir,
.mpo_vnode_check_readlink = biba_vnode_check_readlink,
.mpo_vnode_check_relabel = biba_vnode_check_relabel,
.mpo_vnode_check_rename_from = biba_vnode_check_rename_from,
.mpo_vnode_check_rename_to = biba_vnode_check_rename_to,
.mpo_vnode_check_revoke = biba_vnode_check_revoke,
.mpo_vnode_check_setacl = biba_vnode_check_setacl,
.mpo_vnode_check_setextattr = biba_vnode_check_setextattr,
.mpo_vnode_check_setflags = biba_vnode_check_setflags,
.mpo_vnode_check_setmode = biba_vnode_check_setmode,
.mpo_vnode_check_setowner = biba_vnode_check_setowner,
.mpo_vnode_check_setutimes = biba_vnode_check_setutimes,
.mpo_vnode_check_stat = biba_vnode_check_stat,
.mpo_vnode_check_unlink = biba_vnode_check_unlink,
.mpo_vnode_check_write = biba_vnode_check_write,
.mpo_vnode_create_extattr = biba_vnode_create_extattr,
.mpo_vnode_copy_label = biba_copy_label,
.mpo_vnode_destroy_label = biba_destroy_label,
.mpo_vnode_externalize_label = biba_externalize_label,
.mpo_vnode_init_label = biba_init_label,
.mpo_vnode_internalize_label = biba_internalize_label,
.mpo_vnode_relabel = biba_vnode_relabel,
.mpo_vnode_setlabel_extattr = biba_vnode_setlabel_extattr,
};
MAC_POLICY_SET(&mac_biba_ops, mac_biba, "TrustedBSD MAC/Biba",
MPC_LOADTIME_FLAG_NOTLATE, &biba_slot);
|
312023.c | #include <assert.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "mjsonlib.h"
int main(void)
{
mjson_t p;
bool b = json_init_in_str(&p, stdin);
if (!b) exit(1);
printf("JSON= ");
json_out_str(stdout, p);
printf("\n");
double d = json_get_real(p, "c", "[2]", "d", NULL);
d = json_get_real(p, "b", NULL);
int i = json_get_boolean (p, "c", "[0]", NULL);
const char *str = json_get_string(p, "c", "[3]", NULL);
json_clear(p);
exit(0);
}
|
988350.c | /*
** $Id: liolib.c,v 2.73.1.4 2010/05/14 15:33:51 roberto Exp $
** Standard I/O (and system) library
** See Copyright Notice in lua.h
** IO库
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define liolib_c
#define LUA_LIB
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
#define IO_INPUT 1
#define IO_OUTPUT 2
static const char *const fnames[] = {"input", "output"};
static int pushresult (lua_State *L, int i, const char *filename) {
int en = errno; /* calls to Lua API may change this value */
if (i) {
lua_pushboolean(L, 1);
return 1;
}
else {
lua_pushnil(L);
if (filename)
lua_pushfstring(L, "%s: %s", filename, strerror(en));
else
lua_pushfstring(L, "%s", strerror(en));
lua_pushinteger(L, en);
return 3;
}
}
static void fileerror (lua_State *L, int arg, const char *filename) {
lua_pushfstring(L, "%s: %s", filename, strerror(errno));
luaL_argerror(L, arg, lua_tostring(L, -1));
}
#define tofilep(L) ((FILE **)luaL_checkudata(L, 1, LUA_FILEHANDLE))
static int io_type (lua_State *L) {
void *ud;
luaL_checkany(L, 1);
ud = lua_touserdata(L, 1);
lua_getfield(L, LUA_REGISTRYINDEX, LUA_FILEHANDLE);
if (ud == NULL || !lua_getmetatable(L, 1) || !lua_rawequal(L, -2, -1))
lua_pushnil(L); /* not a file */
else if (*((FILE **)ud) == NULL)
lua_pushliteral(L, "closed file");
else
lua_pushliteral(L, "file");
return 1;
}
static FILE *tofile (lua_State *L) {
FILE **f = tofilep(L);
if (*f == NULL)
luaL_error(L, "attempt to use a closed file");
return *f;
}
/*
** When creating file handles, always creates a `closed' file handle
** before opening the actual file; so, if there is a memory error, the
** file is not left opened.
*/
static FILE **newfile (lua_State *L) {
FILE **pf = (FILE **)lua_newuserdata(L, sizeof(FILE *));
*pf = NULL; /* file handle is currently `closed' */
luaL_getmetatable(L, LUA_FILEHANDLE);
lua_setmetatable(L, -2);
return pf;
}
/*
** function to (not) close the standard files stdin, stdout, and stderr
*/
static int io_noclose (lua_State *L) {
lua_pushnil(L);
lua_pushliteral(L, "cannot close standard file");
return 2;
}
/*
** function to close 'popen' files
*/
static int io_pclose (lua_State *L) {
FILE **p = tofilep(L);
int ok = lua_pclose(L, *p);
*p = NULL;
return pushresult(L, ok, NULL);
}
/*
** function to close regular files
*/
static int io_fclose (lua_State *L) {
FILE **p = tofilep(L);
int ok = (fclose(*p) == 0);
*p = NULL;
return pushresult(L, ok, NULL);
}
static int aux_close (lua_State *L) {
lua_getfenv(L, 1);
lua_getfield(L, -1, "__close");
return (lua_tocfunction(L, -1))(L);
}
static int io_close (lua_State *L) {
if (lua_isnone(L, 1))
lua_rawgeti(L, LUA_ENVIRONINDEX, IO_OUTPUT);
tofile(L); /* make sure argument is a file */
return aux_close(L);
}
static int io_gc (lua_State *L) {
FILE *f = *tofilep(L);
/* ignore closed files */
if (f != NULL)
aux_close(L);
return 0;
}
static int io_tostring (lua_State *L) {
FILE *f = *tofilep(L);
if (f == NULL)
lua_pushliteral(L, "file (closed)");
else
lua_pushfstring(L, "file (%p)", f);
return 1;
}
static int io_open (lua_State *L) {
const char *filename = luaL_checkstring(L, 1);
const char *mode = luaL_optstring(L, 2, "r");
FILE **pf = newfile(L);
*pf = fopen(filename, mode);
return (*pf == NULL) ? pushresult(L, 0, filename) : 1;
}
/*
** this function has a separated environment, which defines the
** correct __close for 'popen' files
*/
static int io_popen (lua_State *L) {
const char *filename = luaL_checkstring(L, 1);
const char *mode = luaL_optstring(L, 2, "r");
FILE **pf = newfile(L);
*pf = lua_popen(L, filename, mode);
return (*pf == NULL) ? pushresult(L, 0, filename) : 1;
}
static int io_tmpfile (lua_State *L) {
FILE **pf = newfile(L);
*pf = tmpfile();
return (*pf == NULL) ? pushresult(L, 0, NULL) : 1;
}
static FILE *getiofile (lua_State *L, int findex) {
FILE *f;
lua_rawgeti(L, LUA_ENVIRONINDEX, findex);
f = *(FILE **)lua_touserdata(L, -1);
if (f == NULL)
luaL_error(L, "standard %s file is closed", fnames[findex - 1]);
return f;
}
static int g_iofile (lua_State *L, int f, const char *mode) {
if (!lua_isnoneornil(L, 1)) {
const char *filename = lua_tostring(L, 1);
if (filename) {
FILE **pf = newfile(L);
*pf = fopen(filename, mode);
if (*pf == NULL)
fileerror(L, 1, filename);
}
else {
tofile(L); /* check that it's a valid file handle */
lua_pushvalue(L, 1);
}
lua_rawseti(L, LUA_ENVIRONINDEX, f);
}
/* return current value */
lua_rawgeti(L, LUA_ENVIRONINDEX, f);
return 1;
}
static int io_input (lua_State *L) {
return g_iofile(L, IO_INPUT, "r");
}
static int io_output (lua_State *L) {
return g_iofile(L, IO_OUTPUT, "w");
}
static int io_readline (lua_State *L);
static void aux_lines (lua_State *L, int idx, int toclose) {
lua_pushvalue(L, idx);
lua_pushboolean(L, toclose); /* close/not close file when finished */
lua_pushcclosure(L, io_readline, 2);
}
static int f_lines (lua_State *L) {
tofile(L); /* check that it's a valid file handle */
aux_lines(L, 1, 0);
return 1;
}
static int io_lines (lua_State *L) {
if (lua_isnoneornil(L, 1)) { /* no arguments? */
/* will iterate over default input */
lua_rawgeti(L, LUA_ENVIRONINDEX, IO_INPUT);
return f_lines(L);
}
else {
const char *filename = luaL_checkstring(L, 1);
FILE **pf = newfile(L);
*pf = fopen(filename, "r");
if (*pf == NULL)
fileerror(L, 1, filename);
aux_lines(L, lua_gettop(L), 1);
return 1;
}
}
/*
** {======================================================
** READ
** =======================================================
*/
static int read_number (lua_State *L, FILE *f) {
lua_Number d;
if (fscanf(f, LUA_NUMBER_SCAN, &d) == 1) {
lua_pushnumber(L, d);
return 1;
}
else {
lua_pushnil(L); /* "result" to be removed */
return 0; /* read fails */
}
}
static int test_eof (lua_State *L, FILE *f) {
int c = getc(f);
ungetc(c, f);
lua_pushlstring(L, NULL, 0);
return (c != EOF);
}
static int read_line (lua_State *L, FILE *f) {
luaL_Buffer b;
luaL_buffinit(L, &b);
for (;;) {
size_t l;
char *p = luaL_prepbuffer(&b);
if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) { /* eof? */
luaL_pushresult(&b); /* close buffer */
return (lua_objlen(L, -1) > 0); /* check whether read something */
}
l = strlen(p);
if (l == 0 || p[l-1] != '\n')
luaL_addsize(&b, l);
else {
luaL_addsize(&b, l - 1); /* do not include `eol' */
luaL_pushresult(&b); /* close buffer */
return 1; /* read at least an `eol' */
}
}
}
static int read_chars (lua_State *L, FILE *f, size_t n) {
size_t rlen; /* how much to read */
size_t nr; /* number of chars actually read */
luaL_Buffer b;
luaL_buffinit(L, &b);
rlen = LUAL_BUFFERSIZE; /* try to read that much each time */
do {
char *p = luaL_prepbuffer(&b);
if (rlen > n) rlen = n; /* cannot read more than asked */
nr = fread(p, sizeof(char), rlen, f);
luaL_addsize(&b, nr);
n -= nr; /* still have to read `n' chars */
} while (n > 0 && nr == rlen); /* until end of count or eof */
luaL_pushresult(&b); /* close buffer */
return (n == 0 || lua_objlen(L, -1) > 0);
}
static int g_read (lua_State *L, FILE *f, int first) {
int nargs = lua_gettop(L) - 1;
int success;
int n;
clearerr(f);
if (nargs == 0) { /* no arguments? */
success = read_line(L, f);
n = first+1; /* to return 1 result */
}
else { /* ensure stack space for all results and for auxlib's buffer */
luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
success = 1;
for (n = first; nargs-- && success; n++) {
if (lua_type(L, n) == LUA_TNUMBER) {
size_t l = (size_t)lua_tointeger(L, n);
success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
}
else {
const char *p = lua_tostring(L, n);
luaL_argcheck(L, p && p[0] == '*', n, "invalid option");
switch (p[1]) {
case 'n': /* number */
success = read_number(L, f);
break;
case 'l': /* line */
success = read_line(L, f);
break;
case 'a': /* file */
read_chars(L, f, ~((size_t)0)); /* read MAX_SIZE_T chars */
success = 1; /* always success */
break;
default:
return luaL_argerror(L, n, "invalid format");
}
}
}
}
if (ferror(f))
return pushresult(L, 0, NULL);
if (!success) {
lua_pop(L, 1); /* remove last result */
lua_pushnil(L); /* push nil instead */
}
return n - first;
}
static int io_read (lua_State *L) {
return g_read(L, getiofile(L, IO_INPUT), 1);
}
static int f_read (lua_State *L) {
return g_read(L, tofile(L), 2);
}
static int io_readline (lua_State *L) {
FILE *f = *(FILE **)lua_touserdata(L, lua_upvalueindex(1));
int sucess;
if (f == NULL) /* file is already closed? */
luaL_error(L, "file is already closed");
sucess = read_line(L, f);
if (ferror(f))
return luaL_error(L, "%s", strerror(errno));
if (sucess) return 1;
else { /* EOF */
if (lua_toboolean(L, lua_upvalueindex(2))) { /* generator created file? */
lua_settop(L, 0);
lua_pushvalue(L, lua_upvalueindex(1));
aux_close(L); /* close it */
}
return 0;
}
}
/* }====================================================== */
static int g_write (lua_State *L, FILE *f, int arg) {
int nargs = lua_gettop(L) - 1;
int status = 1;
for (; nargs--; arg++) {
if (lua_type(L, arg) == LUA_TNUMBER) {
/* optimization: could be done exactly as for strings */
status = status &&
fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0;
}
else {
size_t l;
const char *s = luaL_checklstring(L, arg, &l);
status = status && (fwrite(s, sizeof(char), l, f) == l);
}
}
return pushresult(L, status, NULL);
}
static int io_write (lua_State *L) {
return g_write(L, getiofile(L, IO_OUTPUT), 1);
}
static int f_write (lua_State *L) {
return g_write(L, tofile(L), 2);
}
static int f_seek (lua_State *L) {
static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
static const char *const modenames[] = {"set", "cur", "end", NULL};
FILE *f = tofile(L);
int op = luaL_checkoption(L, 2, "cur", modenames);
long offset = luaL_optlong(L, 3, 0);
op = fseek(f, offset, mode[op]);
if (op)
return pushresult(L, 0, NULL); /* error */
else {
lua_pushinteger(L, ftell(f));
return 1;
}
}
static int f_setvbuf (lua_State *L) {
static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
static const char *const modenames[] = {"no", "full", "line", NULL};
FILE *f = tofile(L);
int op = luaL_checkoption(L, 2, NULL, modenames);
lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
int res = setvbuf(f, NULL, mode[op], sz);
return pushresult(L, res == 0, NULL);
}
static int io_flush (lua_State *L) {
return pushresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
}
static int f_flush (lua_State *L) {
return pushresult(L, fflush(tofile(L)) == 0, NULL);
}
static const luaL_Reg iolib[] = {
{"close", io_close},
{"flush", io_flush},
{"input", io_input},
{"lines", io_lines},
{"open", io_open},
{"output", io_output},
{"popen", io_popen},
{"read", io_read},
{"tmpfile", io_tmpfile},
{"type", io_type},
{"write", io_write},
{NULL, NULL}
};
static const luaL_Reg flib[] = {
{"close", io_close},
{"flush", f_flush},
{"lines", f_lines},
{"read", f_read},
{"seek", f_seek},
{"setvbuf", f_setvbuf},
{"write", f_write},
{"__gc", io_gc},
{"__tostring", io_tostring},
{NULL, NULL}
};
static void createmeta (lua_State *L) {
luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */
lua_pushvalue(L, -1); /* push metatable */
lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */
luaL_register(L, NULL, flib); /* file methods */
}
static void createstdfile (lua_State *L, FILE *f, int k, const char *fname) {
*newfile(L) = f;
if (k > 0) {
lua_pushvalue(L, -1);
lua_rawseti(L, LUA_ENVIRONINDEX, k);
}
lua_pushvalue(L, -2); /* copy environment */
lua_setfenv(L, -2); /* set it */
lua_setfield(L, -3, fname);
}
static void newfenv (lua_State *L, lua_CFunction cls) {
lua_createtable(L, 0, 1);
lua_pushcfunction(L, cls);
lua_setfield(L, -2, "__close");
}
LUALIB_API int luaopen_io (lua_State *L) {
createmeta(L);
/* create (private) environment (with fields IO_INPUT, IO_OUTPUT, __close) */
newfenv(L, io_fclose);
lua_replace(L, LUA_ENVIRONINDEX);
/* open library */
luaL_register(L, LUA_IOLIBNAME, iolib);
/* create (and set) default files */
newfenv(L, io_noclose); /* close function for default files */
createstdfile(L, stdin, IO_INPUT, "stdin");
createstdfile(L, stdout, IO_OUTPUT, "stdout");
createstdfile(L, stderr, 0, "stderr");
lua_pop(L, 1); /* pop environment for default files */
lua_getfield(L, -1, "popen");
newfenv(L, io_pclose); /* create environment for 'popen' */
lua_setfenv(L, -2); /* set fenv for 'popen' */
lua_pop(L, 1); /* pop 'popen' */
return 1;
}
|
335765.c | #include "test/jemalloc_test.h"
#define NTHREADS 10
static bool have_dss =
#ifdef JEMALLOC_DSS
true
#else
false
#endif
;
void *thd_start(void *arg)
{
unsigned thread_ind = (unsigned)(uintptr_t)arg;
unsigned arena_ind;
void *p;
size_t sz;
sz = sizeof(arena_ind);
assert_d_eq(mallctl("arenas.create", (void *)&arena_ind, &sz, NULL, 0), 0,
"Error in arenas.create");
if (thread_ind % 4 != 3) {
size_t mib[3];
size_t miblen = sizeof(mib) / sizeof(size_t);
const char *dss_precs[] = { "disabled", "primary", "secondary" };
unsigned prec_ind = thread_ind % (sizeof(dss_precs) / sizeof(char *));
const char *dss = dss_precs[prec_ind];
int expected_err = (have_dss || prec_ind == 0) ? 0 : EFAULT;
assert_d_eq(mallctlnametomib("arena.0.dss", mib, &miblen), 0,
"Error in mallctlnametomib()");
mib[1] = arena_ind;
assert_d_eq(mallctlbymib(mib, miblen, NULL, NULL, (void *)&dss,
sizeof(const char *)),
expected_err, "Error in mallctlbymib()");
}
p = mallocx(1, MALLOCX_ARENA(arena_ind));
assert_ptr_not_null(p, "Unexpected mallocx() error");
dallocx(p, 0);
return NULL;
}
TEST_BEGIN(test_MALLOCX_ARENA)
{
thd_t thds[NTHREADS];
unsigned i;
for (i = 0; i < NTHREADS; i++) {
thd_create(&thds[i], thd_start, (void *)(uintptr_t)i);
}
for (i = 0; i < NTHREADS; i++) {
thd_join(thds[i], NULL);
}
}
TEST_END
int main(void)
{
return test(test_MALLOCX_ARENA);
}
|
175537.c | // kernel panic: stack is corrupted in get_kernel_gp_address
// https://syzkaller.appspot.com/bug?id=d6459d8f8984c0929e54
// status:6 arch:386
// autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <dirent.h>
#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <netinet/in.h>
#include <pthread.h>
#include <sched.h>
#include <setjmp.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/ioctl.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <linux/capability.h>
#include <linux/futex.h>
#include <linux/genetlink.h>
#include <linux/if_addr.h>
#include <linux/if_ether.h>
#include <linux/if_link.h>
#include <linux/if_tun.h>
#include <linux/in6.h>
#include <linux/ip.h>
#include <linux/neighbour.h>
#include <linux/net.h>
#include <linux/netlink.h>
#include <linux/rfkill.h>
#include <linux/rtnetlink.h>
#include <linux/tcp.h>
#include <linux/veth.h>
static unsigned long long procid;
static __thread int skip_segv;
static __thread jmp_buf segv_env;
static void segv_handler(int sig, siginfo_t* info, void* ctx)
{
uintptr_t addr = (uintptr_t)info->si_addr;
const uintptr_t prog_start = 1 << 20;
const uintptr_t prog_end = 100 << 20;
int skip = __atomic_load_n(&skip_segv, __ATOMIC_RELAXED) != 0;
int valid = addr < prog_start || addr > prog_end;
if (skip && valid) {
_longjmp(segv_env, 1);
}
exit(sig);
}
static void install_segv_handler(void)
{
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_IGN;
syscall(SYS_rt_sigaction, 0x20, &sa, NULL, 8);
syscall(SYS_rt_sigaction, 0x21, &sa, NULL, 8);
memset(&sa, 0, sizeof(sa));
sa.sa_sigaction = segv_handler;
sa.sa_flags = SA_NODEFER | SA_SIGINFO;
sigaction(SIGSEGV, &sa, NULL);
sigaction(SIGBUS, &sa, NULL);
}
#define NONFAILING(...) \
{ \
__atomic_fetch_add(&skip_segv, 1, __ATOMIC_SEQ_CST); \
if (_setjmp(segv_env) == 0) { \
__VA_ARGS__; \
} \
__atomic_fetch_sub(&skip_segv, 1, __ATOMIC_SEQ_CST); \
}
static void sleep_ms(uint64_t ms)
{
usleep(ms * 1000);
}
static uint64_t current_time_ms(void)
{
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts))
exit(1);
return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000;
}
static void use_temporary_dir(void)
{
char tmpdir_template[] = "./syzkaller.XXXXXX";
char* tmpdir = mkdtemp(tmpdir_template);
if (!tmpdir)
exit(1);
if (chmod(tmpdir, 0777))
exit(1);
if (chdir(tmpdir))
exit(1);
}
static void thread_start(void* (*fn)(void*), void* arg)
{
pthread_t th;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, 128 << 10);
int i = 0;
for (; i < 100; i++) {
if (pthread_create(&th, &attr, fn, arg) == 0) {
pthread_attr_destroy(&attr);
return;
}
if (errno == EAGAIN) {
usleep(50);
continue;
}
break;
}
exit(1);
}
typedef struct {
int state;
} event_t;
static void event_init(event_t* ev)
{
ev->state = 0;
}
static void event_reset(event_t* ev)
{
ev->state = 0;
}
static void event_set(event_t* ev)
{
if (ev->state)
exit(1);
__atomic_store_n(&ev->state, 1, __ATOMIC_RELEASE);
syscall(SYS_futex, &ev->state, FUTEX_WAKE | FUTEX_PRIVATE_FLAG, 1000000);
}
static void event_wait(event_t* ev)
{
while (!__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE))
syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, 0);
}
static int event_isset(event_t* ev)
{
return __atomic_load_n(&ev->state, __ATOMIC_ACQUIRE);
}
static int event_timedwait(event_t* ev, uint64_t timeout)
{
uint64_t start = current_time_ms();
uint64_t now = start;
for (;;) {
uint64_t remain = timeout - (now - start);
struct timespec ts;
ts.tv_sec = remain / 1000;
ts.tv_nsec = (remain % 1000) * 1000 * 1000;
syscall(SYS_futex, &ev->state, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0, &ts);
if (__atomic_load_n(&ev->state, __ATOMIC_ACQUIRE))
return 1;
now = current_time_ms();
if (now - start > timeout)
return 0;
}
}
static bool write_file(const char* file, const char* what, ...)
{
char buf[1024];
va_list args;
va_start(args, what);
vsnprintf(buf, sizeof(buf), what, args);
va_end(args);
buf[sizeof(buf) - 1] = 0;
int len = strlen(buf);
int fd = open(file, O_WRONLY | O_CLOEXEC);
if (fd == -1)
return false;
if (write(fd, buf, len) != len) {
int err = errno;
close(fd);
errno = err;
return false;
}
close(fd);
return true;
}
struct nlmsg {
char* pos;
int nesting;
struct nlattr* nested[8];
char buf[1024];
};
static struct nlmsg nlmsg;
static void netlink_init(struct nlmsg* nlmsg, int typ, int flags,
const void* data, int size)
{
memset(nlmsg, 0, sizeof(*nlmsg));
struct nlmsghdr* hdr = (struct nlmsghdr*)nlmsg->buf;
hdr->nlmsg_type = typ;
hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags;
memcpy(hdr + 1, data, size);
nlmsg->pos = (char*)(hdr + 1) + NLMSG_ALIGN(size);
}
static void netlink_attr(struct nlmsg* nlmsg, int typ, const void* data,
int size)
{
struct nlattr* attr = (struct nlattr*)nlmsg->pos;
attr->nla_len = sizeof(*attr) + size;
attr->nla_type = typ;
memcpy(attr + 1, data, size);
nlmsg->pos += NLMSG_ALIGN(attr->nla_len);
}
static void netlink_nest(struct nlmsg* nlmsg, int typ)
{
struct nlattr* attr = (struct nlattr*)nlmsg->pos;
attr->nla_type = typ;
nlmsg->pos += sizeof(*attr);
nlmsg->nested[nlmsg->nesting++] = attr;
}
static void netlink_done(struct nlmsg* nlmsg)
{
struct nlattr* attr = nlmsg->nested[--nlmsg->nesting];
attr->nla_len = nlmsg->pos - (char*)attr;
}
static int netlink_send_ext(struct nlmsg* nlmsg, int sock, uint16_t reply_type,
int* reply_len)
{
if (nlmsg->pos > nlmsg->buf + sizeof(nlmsg->buf) || nlmsg->nesting)
exit(1);
struct nlmsghdr* hdr = (struct nlmsghdr*)nlmsg->buf;
hdr->nlmsg_len = nlmsg->pos - nlmsg->buf;
struct sockaddr_nl addr;
memset(&addr, 0, sizeof(addr));
addr.nl_family = AF_NETLINK;
unsigned n = sendto(sock, nlmsg->buf, hdr->nlmsg_len, 0,
(struct sockaddr*)&addr, sizeof(addr));
if (n != hdr->nlmsg_len)
exit(1);
n = recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0);
if (reply_len)
*reply_len = 0;
if (hdr->nlmsg_type == NLMSG_DONE)
return 0;
if (n < sizeof(struct nlmsghdr))
exit(1);
if (reply_len && hdr->nlmsg_type == reply_type) {
*reply_len = n;
return 0;
}
if (n < sizeof(struct nlmsghdr) + sizeof(struct nlmsgerr))
exit(1);
if (hdr->nlmsg_type != NLMSG_ERROR)
exit(1);
return -((struct nlmsgerr*)(hdr + 1))->error;
}
static int netlink_send(struct nlmsg* nlmsg, int sock)
{
return netlink_send_ext(nlmsg, sock, 0, NULL);
}
static int netlink_next_msg(struct nlmsg* nlmsg, unsigned int offset,
unsigned int total_len)
{
struct nlmsghdr* hdr = (struct nlmsghdr*)(nlmsg->buf + offset);
if (offset == total_len || offset + hdr->nlmsg_len > total_len)
return -1;
return hdr->nlmsg_len;
}
static void netlink_add_device_impl(struct nlmsg* nlmsg, const char* type,
const char* name)
{
struct ifinfomsg hdr;
memset(&hdr, 0, sizeof(hdr));
netlink_init(nlmsg, RTM_NEWLINK, NLM_F_EXCL | NLM_F_CREATE, &hdr,
sizeof(hdr));
if (name)
netlink_attr(nlmsg, IFLA_IFNAME, name, strlen(name));
netlink_nest(nlmsg, IFLA_LINKINFO);
netlink_attr(nlmsg, IFLA_INFO_KIND, type, strlen(type));
}
static void netlink_add_device(struct nlmsg* nlmsg, int sock, const char* type,
const char* name)
{
netlink_add_device_impl(nlmsg, type, name);
netlink_done(nlmsg);
int err = netlink_send(nlmsg, sock);
(void)err;
}
static void netlink_add_veth(struct nlmsg* nlmsg, int sock, const char* name,
const char* peer)
{
netlink_add_device_impl(nlmsg, "veth", name);
netlink_nest(nlmsg, IFLA_INFO_DATA);
netlink_nest(nlmsg, VETH_INFO_PEER);
nlmsg->pos += sizeof(struct ifinfomsg);
netlink_attr(nlmsg, IFLA_IFNAME, peer, strlen(peer));
netlink_done(nlmsg);
netlink_done(nlmsg);
netlink_done(nlmsg);
int err = netlink_send(nlmsg, sock);
(void)err;
}
static void netlink_add_hsr(struct nlmsg* nlmsg, int sock, const char* name,
const char* slave1, const char* slave2)
{
netlink_add_device_impl(nlmsg, "hsr", name);
netlink_nest(nlmsg, IFLA_INFO_DATA);
int ifindex1 = if_nametoindex(slave1);
netlink_attr(nlmsg, IFLA_HSR_SLAVE1, &ifindex1, sizeof(ifindex1));
int ifindex2 = if_nametoindex(slave2);
netlink_attr(nlmsg, IFLA_HSR_SLAVE2, &ifindex2, sizeof(ifindex2));
netlink_done(nlmsg);
netlink_done(nlmsg);
int err = netlink_send(nlmsg, sock);
(void)err;
}
static void netlink_add_linked(struct nlmsg* nlmsg, int sock, const char* type,
const char* name, const char* link)
{
netlink_add_device_impl(nlmsg, type, name);
netlink_done(nlmsg);
int ifindex = if_nametoindex(link);
netlink_attr(nlmsg, IFLA_LINK, &ifindex, sizeof(ifindex));
int err = netlink_send(nlmsg, sock);
(void)err;
}
static void netlink_add_vlan(struct nlmsg* nlmsg, int sock, const char* name,
const char* link, uint16_t id, uint16_t proto)
{
netlink_add_device_impl(nlmsg, "vlan", name);
netlink_nest(nlmsg, IFLA_INFO_DATA);
netlink_attr(nlmsg, IFLA_VLAN_ID, &id, sizeof(id));
netlink_attr(nlmsg, IFLA_VLAN_PROTOCOL, &proto, sizeof(proto));
netlink_done(nlmsg);
netlink_done(nlmsg);
int ifindex = if_nametoindex(link);
netlink_attr(nlmsg, IFLA_LINK, &ifindex, sizeof(ifindex));
int err = netlink_send(nlmsg, sock);
(void)err;
}
static void netlink_add_macvlan(struct nlmsg* nlmsg, int sock, const char* name,
const char* link)
{
netlink_add_device_impl(nlmsg, "macvlan", name);
netlink_nest(nlmsg, IFLA_INFO_DATA);
uint32_t mode = MACVLAN_MODE_BRIDGE;
netlink_attr(nlmsg, IFLA_MACVLAN_MODE, &mode, sizeof(mode));
netlink_done(nlmsg);
netlink_done(nlmsg);
int ifindex = if_nametoindex(link);
netlink_attr(nlmsg, IFLA_LINK, &ifindex, sizeof(ifindex));
int err = netlink_send(nlmsg, sock);
(void)err;
}
static void netlink_add_geneve(struct nlmsg* nlmsg, int sock, const char* name,
uint32_t vni, struct in_addr* addr4,
struct in6_addr* addr6)
{
netlink_add_device_impl(nlmsg, "geneve", name);
netlink_nest(nlmsg, IFLA_INFO_DATA);
netlink_attr(nlmsg, IFLA_GENEVE_ID, &vni, sizeof(vni));
if (addr4)
netlink_attr(nlmsg, IFLA_GENEVE_REMOTE, addr4, sizeof(*addr4));
if (addr6)
netlink_attr(nlmsg, IFLA_GENEVE_REMOTE6, addr6, sizeof(*addr6));
netlink_done(nlmsg);
netlink_done(nlmsg);
int err = netlink_send(nlmsg, sock);
(void)err;
}
#define IFLA_IPVLAN_FLAGS 2
#define IPVLAN_MODE_L3S 2
#undef IPVLAN_F_VEPA
#define IPVLAN_F_VEPA 2
static void netlink_add_ipvlan(struct nlmsg* nlmsg, int sock, const char* name,
const char* link, uint16_t mode, uint16_t flags)
{
netlink_add_device_impl(nlmsg, "ipvlan", name);
netlink_nest(nlmsg, IFLA_INFO_DATA);
netlink_attr(nlmsg, IFLA_IPVLAN_MODE, &mode, sizeof(mode));
netlink_attr(nlmsg, IFLA_IPVLAN_FLAGS, &flags, sizeof(flags));
netlink_done(nlmsg);
netlink_done(nlmsg);
int ifindex = if_nametoindex(link);
netlink_attr(nlmsg, IFLA_LINK, &ifindex, sizeof(ifindex));
int err = netlink_send(nlmsg, sock);
(void)err;
}
static void netlink_device_change(struct nlmsg* nlmsg, int sock,
const char* name, bool up, const char* master,
const void* mac, int macsize,
const char* new_name)
{
struct ifinfomsg hdr;
memset(&hdr, 0, sizeof(hdr));
if (up)
hdr.ifi_flags = hdr.ifi_change = IFF_UP;
hdr.ifi_index = if_nametoindex(name);
netlink_init(nlmsg, RTM_NEWLINK, 0, &hdr, sizeof(hdr));
if (new_name)
netlink_attr(nlmsg, IFLA_IFNAME, new_name, strlen(new_name));
if (master) {
int ifindex = if_nametoindex(master);
netlink_attr(nlmsg, IFLA_MASTER, &ifindex, sizeof(ifindex));
}
if (macsize)
netlink_attr(nlmsg, IFLA_ADDRESS, mac, macsize);
int err = netlink_send(nlmsg, sock);
(void)err;
}
static int netlink_add_addr(struct nlmsg* nlmsg, int sock, const char* dev,
const void* addr, int addrsize)
{
struct ifaddrmsg hdr;
memset(&hdr, 0, sizeof(hdr));
hdr.ifa_family = addrsize == 4 ? AF_INET : AF_INET6;
hdr.ifa_prefixlen = addrsize == 4 ? 24 : 120;
hdr.ifa_scope = RT_SCOPE_UNIVERSE;
hdr.ifa_index = if_nametoindex(dev);
netlink_init(nlmsg, RTM_NEWADDR, NLM_F_CREATE | NLM_F_REPLACE, &hdr,
sizeof(hdr));
netlink_attr(nlmsg, IFA_LOCAL, addr, addrsize);
netlink_attr(nlmsg, IFA_ADDRESS, addr, addrsize);
return netlink_send(nlmsg, sock);
}
static void netlink_add_addr4(struct nlmsg* nlmsg, int sock, const char* dev,
const char* addr)
{
struct in_addr in_addr;
inet_pton(AF_INET, addr, &in_addr);
int err = netlink_add_addr(nlmsg, sock, dev, &in_addr, sizeof(in_addr));
(void)err;
}
static void netlink_add_addr6(struct nlmsg* nlmsg, int sock, const char* dev,
const char* addr)
{
struct in6_addr in6_addr;
inet_pton(AF_INET6, addr, &in6_addr);
int err = netlink_add_addr(nlmsg, sock, dev, &in6_addr, sizeof(in6_addr));
(void)err;
}
static void netlink_add_neigh(struct nlmsg* nlmsg, int sock, const char* name,
const void* addr, int addrsize, const void* mac,
int macsize)
{
struct ndmsg hdr;
memset(&hdr, 0, sizeof(hdr));
hdr.ndm_family = addrsize == 4 ? AF_INET : AF_INET6;
hdr.ndm_ifindex = if_nametoindex(name);
hdr.ndm_state = NUD_PERMANENT;
netlink_init(nlmsg, RTM_NEWNEIGH, NLM_F_EXCL | NLM_F_CREATE, &hdr,
sizeof(hdr));
netlink_attr(nlmsg, NDA_DST, addr, addrsize);
netlink_attr(nlmsg, NDA_LLADDR, mac, macsize);
int err = netlink_send(nlmsg, sock);
(void)err;
}
static int tunfd = -1;
#define TUN_IFACE "syz_tun"
#define LOCAL_MAC 0xaaaaaaaaaaaa
#define REMOTE_MAC 0xaaaaaaaaaabb
#define LOCAL_IPV4 "172.20.20.170"
#define REMOTE_IPV4 "172.20.20.187"
#define LOCAL_IPV6 "fe80::aa"
#define REMOTE_IPV6 "fe80::bb"
#define IFF_NAPI 0x0010
static void initialize_tun(void)
{
tunfd = open("/dev/net/tun", O_RDWR | O_NONBLOCK);
if (tunfd == -1) {
printf("tun: can't open /dev/net/tun: please enable CONFIG_TUN=y\n");
printf("otherwise fuzzing or reproducing might not work as intended\n");
return;
}
const int kTunFd = 240;
if (dup2(tunfd, kTunFd) < 0)
exit(1);
close(tunfd);
tunfd = kTunFd;
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, TUN_IFACE, IFNAMSIZ);
ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
if (ioctl(tunfd, TUNSETIFF, (void*)&ifr) < 0) {
exit(1);
}
char sysctl[64];
sprintf(sysctl, "/proc/sys/net/ipv6/conf/%s/accept_dad", TUN_IFACE);
write_file(sysctl, "0");
sprintf(sysctl, "/proc/sys/net/ipv6/conf/%s/router_solicitations", TUN_IFACE);
write_file(sysctl, "0");
int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (sock == -1)
exit(1);
netlink_add_addr4(&nlmsg, sock, TUN_IFACE, LOCAL_IPV4);
netlink_add_addr6(&nlmsg, sock, TUN_IFACE, LOCAL_IPV6);
uint64_t macaddr = REMOTE_MAC;
struct in_addr in_addr;
inet_pton(AF_INET, REMOTE_IPV4, &in_addr);
netlink_add_neigh(&nlmsg, sock, TUN_IFACE, &in_addr, sizeof(in_addr),
&macaddr, ETH_ALEN);
struct in6_addr in6_addr;
inet_pton(AF_INET6, REMOTE_IPV6, &in6_addr);
netlink_add_neigh(&nlmsg, sock, TUN_IFACE, &in6_addr, sizeof(in6_addr),
&macaddr, ETH_ALEN);
macaddr = LOCAL_MAC;
netlink_device_change(&nlmsg, sock, TUN_IFACE, true, 0, &macaddr, ETH_ALEN,
NULL);
close(sock);
}
#define DEVLINK_FAMILY_NAME "devlink"
#define DEVLINK_CMD_PORT_GET 5
#define DEVLINK_ATTR_BUS_NAME 1
#define DEVLINK_ATTR_DEV_NAME 2
#define DEVLINK_ATTR_NETDEV_NAME 7
static int netlink_devlink_id_get(struct nlmsg* nlmsg, int sock)
{
struct genlmsghdr genlhdr;
memset(&genlhdr, 0, sizeof(genlhdr));
genlhdr.cmd = CTRL_CMD_GETFAMILY;
netlink_init(nlmsg, GENL_ID_CTRL, 0, &genlhdr, sizeof(genlhdr));
netlink_attr(nlmsg, CTRL_ATTR_FAMILY_NAME, DEVLINK_FAMILY_NAME,
strlen(DEVLINK_FAMILY_NAME) + 1);
int n = 0;
int err = netlink_send_ext(nlmsg, sock, GENL_ID_CTRL, &n);
if (err) {
return -1;
}
uint16_t id = 0;
struct nlattr* attr = (struct nlattr*)(nlmsg->buf + NLMSG_HDRLEN +
NLMSG_ALIGN(sizeof(genlhdr)));
for (; (char*)attr < nlmsg->buf + n;
attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) {
if (attr->nla_type == CTRL_ATTR_FAMILY_ID) {
id = *(uint16_t*)(attr + 1);
break;
}
}
if (!id) {
return -1;
}
recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0);
return id;
}
static struct nlmsg nlmsg2;
static void initialize_devlink_ports(const char* bus_name, const char* dev_name,
const char* netdev_prefix)
{
struct genlmsghdr genlhdr;
int len, total_len, id, err, offset;
uint16_t netdev_index;
int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC);
if (sock == -1)
exit(1);
int rtsock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (rtsock == -1)
exit(1);
id = netlink_devlink_id_get(&nlmsg, sock);
if (id == -1)
goto error;
memset(&genlhdr, 0, sizeof(genlhdr));
genlhdr.cmd = DEVLINK_CMD_PORT_GET;
netlink_init(&nlmsg, id, NLM_F_DUMP, &genlhdr, sizeof(genlhdr));
netlink_attr(&nlmsg, DEVLINK_ATTR_BUS_NAME, bus_name, strlen(bus_name) + 1);
netlink_attr(&nlmsg, DEVLINK_ATTR_DEV_NAME, dev_name, strlen(dev_name) + 1);
err = netlink_send_ext(&nlmsg, sock, id, &total_len);
if (err) {
goto error;
}
offset = 0;
netdev_index = 0;
while ((len = netlink_next_msg(&nlmsg, offset, total_len)) != -1) {
struct nlattr* attr = (struct nlattr*)(nlmsg.buf + offset + NLMSG_HDRLEN +
NLMSG_ALIGN(sizeof(genlhdr)));
for (; (char*)attr < nlmsg.buf + offset + len;
attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) {
if (attr->nla_type == DEVLINK_ATTR_NETDEV_NAME) {
char* port_name;
char netdev_name[IFNAMSIZ];
port_name = (char*)(attr + 1);
snprintf(netdev_name, sizeof(netdev_name), "%s%d", netdev_prefix,
netdev_index);
netlink_device_change(&nlmsg2, rtsock, port_name, true, 0, 0, 0,
netdev_name);
break;
}
}
offset += len;
netdev_index++;
}
error:
close(rtsock);
close(sock);
}
#define DEV_IPV4 "172.20.20.%d"
#define DEV_IPV6 "fe80::%02x"
#define DEV_MAC 0x00aaaaaaaaaa
static void netdevsim_add(unsigned int addr, unsigned int port_count)
{
char buf[16];
sprintf(buf, "%u %u", addr, port_count);
if (write_file("/sys/bus/netdevsim/new_device", buf)) {
snprintf(buf, sizeof(buf), "netdevsim%d", addr);
initialize_devlink_ports("netdevsim", buf, "netdevsim");
}
}
#define WG_GENL_NAME "wireguard"
enum wg_cmd {
WG_CMD_GET_DEVICE,
WG_CMD_SET_DEVICE,
};
enum wgdevice_attribute {
WGDEVICE_A_UNSPEC,
WGDEVICE_A_IFINDEX,
WGDEVICE_A_IFNAME,
WGDEVICE_A_PRIVATE_KEY,
WGDEVICE_A_PUBLIC_KEY,
WGDEVICE_A_FLAGS,
WGDEVICE_A_LISTEN_PORT,
WGDEVICE_A_FWMARK,
WGDEVICE_A_PEERS,
};
enum wgpeer_attribute {
WGPEER_A_UNSPEC,
WGPEER_A_PUBLIC_KEY,
WGPEER_A_PRESHARED_KEY,
WGPEER_A_FLAGS,
WGPEER_A_ENDPOINT,
WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL,
WGPEER_A_LAST_HANDSHAKE_TIME,
WGPEER_A_RX_BYTES,
WGPEER_A_TX_BYTES,
WGPEER_A_ALLOWEDIPS,
WGPEER_A_PROTOCOL_VERSION,
};
enum wgallowedip_attribute {
WGALLOWEDIP_A_UNSPEC,
WGALLOWEDIP_A_FAMILY,
WGALLOWEDIP_A_IPADDR,
WGALLOWEDIP_A_CIDR_MASK,
};
static int netlink_wireguard_id_get(struct nlmsg* nlmsg, int sock)
{
struct genlmsghdr genlhdr;
memset(&genlhdr, 0, sizeof(genlhdr));
genlhdr.cmd = CTRL_CMD_GETFAMILY;
netlink_init(nlmsg, GENL_ID_CTRL, 0, &genlhdr, sizeof(genlhdr));
netlink_attr(nlmsg, CTRL_ATTR_FAMILY_NAME, WG_GENL_NAME,
strlen(WG_GENL_NAME) + 1);
int n = 0;
int err = netlink_send_ext(nlmsg, sock, GENL_ID_CTRL, &n);
if (err) {
return -1;
}
uint16_t id = 0;
struct nlattr* attr = (struct nlattr*)(nlmsg->buf + NLMSG_HDRLEN +
NLMSG_ALIGN(sizeof(genlhdr)));
for (; (char*)attr < nlmsg->buf + n;
attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) {
if (attr->nla_type == CTRL_ATTR_FAMILY_ID) {
id = *(uint16_t*)(attr + 1);
break;
}
}
if (!id) {
return -1;
}
recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0);
return id;
}
static void netlink_wireguard_setup(void)
{
const char ifname_a[] = "wg0";
const char ifname_b[] = "wg1";
const char ifname_c[] = "wg2";
const char private_a[] =
"\xa0\x5c\xa8\x4f\x6c\x9c\x8e\x38\x53\xe2\xfd\x7a\x70\xae\x0f\xb2\x0f\xa1"
"\x52\x60\x0c\xb0\x08\x45\x17\x4f\x08\x07\x6f\x8d\x78\x43";
const char private_b[] =
"\xb0\x80\x73\xe8\xd4\x4e\x91\xe3\xda\x92\x2c\x22\x43\x82\x44\xbb\x88\x5c"
"\x69\xe2\x69\xc8\xe9\xd8\x35\xb1\x14\x29\x3a\x4d\xdc\x6e";
const char private_c[] =
"\xa0\xcb\x87\x9a\x47\xf5\xbc\x64\x4c\x0e\x69\x3f\xa6\xd0\x31\xc7\x4a\x15"
"\x53\xb6\xe9\x01\xb9\xff\x2f\x51\x8c\x78\x04\x2f\xb5\x42";
const char public_a[] =
"\x97\x5c\x9d\x81\xc9\x83\xc8\x20\x9e\xe7\x81\x25\x4b\x89\x9f\x8e\xd9\x25"
"\xae\x9f\x09\x23\xc2\x3c\x62\xf5\x3c\x57\xcd\xbf\x69\x1c";
const char public_b[] =
"\xd1\x73\x28\x99\xf6\x11\xcd\x89\x94\x03\x4d\x7f\x41\x3d\xc9\x57\x63\x0e"
"\x54\x93\xc2\x85\xac\xa4\x00\x65\xcb\x63\x11\xbe\x69\x6b";
const char public_c[] =
"\xf4\x4d\xa3\x67\xa8\x8e\xe6\x56\x4f\x02\x02\x11\x45\x67\x27\x08\x2f\x5c"
"\xeb\xee\x8b\x1b\xf5\xeb\x73\x37\x34\x1b\x45\x9b\x39\x22";
const uint16_t listen_a = 20001;
const uint16_t listen_b = 20002;
const uint16_t listen_c = 20003;
const uint16_t af_inet = AF_INET;
const uint16_t af_inet6 = AF_INET6;
const struct sockaddr_in endpoint_b_v4 = {
.sin_family = AF_INET,
.sin_port = htons(listen_b),
.sin_addr = {htonl(INADDR_LOOPBACK)}};
const struct sockaddr_in endpoint_c_v4 = {
.sin_family = AF_INET,
.sin_port = htons(listen_c),
.sin_addr = {htonl(INADDR_LOOPBACK)}};
struct sockaddr_in6 endpoint_a_v6 = {.sin6_family = AF_INET6,
.sin6_port = htons(listen_a)};
endpoint_a_v6.sin6_addr = in6addr_loopback;
struct sockaddr_in6 endpoint_c_v6 = {.sin6_family = AF_INET6,
.sin6_port = htons(listen_c)};
endpoint_c_v6.sin6_addr = in6addr_loopback;
const struct in_addr first_half_v4 = {0};
const struct in_addr second_half_v4 = {(uint32_t)htonl(128 << 24)};
const struct in6_addr first_half_v6 = {{{0}}};
const struct in6_addr second_half_v6 = {{{0x80}}};
const uint8_t half_cidr = 1;
const uint16_t persistent_keepalives[] = {1, 3, 7, 9, 14, 19};
struct genlmsghdr genlhdr = {.cmd = WG_CMD_SET_DEVICE, .version = 1};
int sock;
int id, err;
sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC);
if (sock == -1) {
return;
}
id = netlink_wireguard_id_get(&nlmsg, sock);
if (id == -1)
goto error;
netlink_init(&nlmsg, id, 0, &genlhdr, sizeof(genlhdr));
netlink_attr(&nlmsg, WGDEVICE_A_IFNAME, ifname_a, strlen(ifname_a) + 1);
netlink_attr(&nlmsg, WGDEVICE_A_PRIVATE_KEY, private_a, 32);
netlink_attr(&nlmsg, WGDEVICE_A_LISTEN_PORT, &listen_a, 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGDEVICE_A_PEERS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_b, 32);
netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_b_v4,
sizeof(endpoint_b_v4));
netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL,
&persistent_keepalives[0], 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v4,
sizeof(first_half_v4));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v6,
sizeof(first_half_v6));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_c, 32);
netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_c_v6,
sizeof(endpoint_c_v6));
netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL,
&persistent_keepalives[1], 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v4,
sizeof(second_half_v4));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v6,
sizeof(second_half_v6));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
err = netlink_send(&nlmsg, sock);
if (err) {
}
netlink_init(&nlmsg, id, 0, &genlhdr, sizeof(genlhdr));
netlink_attr(&nlmsg, WGDEVICE_A_IFNAME, ifname_b, strlen(ifname_b) + 1);
netlink_attr(&nlmsg, WGDEVICE_A_PRIVATE_KEY, private_b, 32);
netlink_attr(&nlmsg, WGDEVICE_A_LISTEN_PORT, &listen_b, 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGDEVICE_A_PEERS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_a, 32);
netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_a_v6,
sizeof(endpoint_a_v6));
netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL,
&persistent_keepalives[2], 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v4,
sizeof(first_half_v4));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v6,
sizeof(first_half_v6));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_c, 32);
netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_c_v4,
sizeof(endpoint_c_v4));
netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL,
&persistent_keepalives[3], 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v4,
sizeof(second_half_v4));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v6,
sizeof(second_half_v6));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
err = netlink_send(&nlmsg, sock);
if (err) {
}
netlink_init(&nlmsg, id, 0, &genlhdr, sizeof(genlhdr));
netlink_attr(&nlmsg, WGDEVICE_A_IFNAME, ifname_c, strlen(ifname_c) + 1);
netlink_attr(&nlmsg, WGDEVICE_A_PRIVATE_KEY, private_c, 32);
netlink_attr(&nlmsg, WGDEVICE_A_LISTEN_PORT, &listen_c, 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGDEVICE_A_PEERS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_a, 32);
netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_a_v6,
sizeof(endpoint_a_v6));
netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL,
&persistent_keepalives[4], 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v4,
sizeof(first_half_v4));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &first_half_v6,
sizeof(first_half_v6));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGPEER_A_PUBLIC_KEY, public_b, 32);
netlink_attr(&nlmsg, WGPEER_A_ENDPOINT, &endpoint_b_v4,
sizeof(endpoint_b_v4));
netlink_attr(&nlmsg, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL,
&persistent_keepalives[5], 2);
netlink_nest(&nlmsg, NLA_F_NESTED | WGPEER_A_ALLOWEDIPS);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v4,
sizeof(second_half_v4));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_nest(&nlmsg, NLA_F_NESTED | 0);
netlink_attr(&nlmsg, WGALLOWEDIP_A_FAMILY, &af_inet6, 2);
netlink_attr(&nlmsg, WGALLOWEDIP_A_IPADDR, &second_half_v6,
sizeof(second_half_v6));
netlink_attr(&nlmsg, WGALLOWEDIP_A_CIDR_MASK, &half_cidr, 1);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
netlink_done(&nlmsg);
err = netlink_send(&nlmsg, sock);
if (err) {
}
error:
close(sock);
}
static void initialize_netdevices(void)
{
char netdevsim[16];
sprintf(netdevsim, "netdevsim%d", (int)procid);
struct {
const char* type;
const char* dev;
} devtypes[] = {
{"ip6gretap", "ip6gretap0"}, {"bridge", "bridge0"},
{"vcan", "vcan0"}, {"bond", "bond0"},
{"team", "team0"}, {"dummy", "dummy0"},
{"nlmon", "nlmon0"}, {"caif", "caif0"},
{"batadv", "batadv0"}, {"vxcan", "vxcan1"},
{"netdevsim", netdevsim}, {"veth", 0},
{"xfrm", "xfrm0"}, {"wireguard", "wg0"},
{"wireguard", "wg1"}, {"wireguard", "wg2"},
};
const char* devmasters[] = {"bridge", "bond", "team", "batadv"};
struct {
const char* name;
int macsize;
bool noipv6;
} devices[] = {
{"lo", ETH_ALEN},
{"sit0", 0},
{"bridge0", ETH_ALEN},
{"vcan0", 0, true},
{"tunl0", 0},
{"gre0", 0},
{"gretap0", ETH_ALEN},
{"ip_vti0", 0},
{"ip6_vti0", 0},
{"ip6tnl0", 0},
{"ip6gre0", 0},
{"ip6gretap0", ETH_ALEN},
{"erspan0", ETH_ALEN},
{"bond0", ETH_ALEN},
{"veth0", ETH_ALEN},
{"veth1", ETH_ALEN},
{"team0", ETH_ALEN},
{"veth0_to_bridge", ETH_ALEN},
{"veth1_to_bridge", ETH_ALEN},
{"veth0_to_bond", ETH_ALEN},
{"veth1_to_bond", ETH_ALEN},
{"veth0_to_team", ETH_ALEN},
{"veth1_to_team", ETH_ALEN},
{"veth0_to_hsr", ETH_ALEN},
{"veth1_to_hsr", ETH_ALEN},
{"hsr0", 0},
{"dummy0", ETH_ALEN},
{"nlmon0", 0},
{"vxcan0", 0, true},
{"vxcan1", 0, true},
{"caif0", ETH_ALEN},
{"batadv0", ETH_ALEN},
{netdevsim, ETH_ALEN},
{"xfrm0", ETH_ALEN},
{"veth0_virt_wifi", ETH_ALEN},
{"veth1_virt_wifi", ETH_ALEN},
{"virt_wifi0", ETH_ALEN},
{"veth0_vlan", ETH_ALEN},
{"veth1_vlan", ETH_ALEN},
{"vlan0", ETH_ALEN},
{"vlan1", ETH_ALEN},
{"macvlan0", ETH_ALEN},
{"macvlan1", ETH_ALEN},
{"ipvlan0", ETH_ALEN},
{"ipvlan1", ETH_ALEN},
{"veth0_macvtap", ETH_ALEN},
{"veth1_macvtap", ETH_ALEN},
{"macvtap0", ETH_ALEN},
{"macsec0", ETH_ALEN},
{"veth0_to_batadv", ETH_ALEN},
{"veth1_to_batadv", ETH_ALEN},
{"batadv_slave_0", ETH_ALEN},
{"batadv_slave_1", ETH_ALEN},
{"geneve0", ETH_ALEN},
{"geneve1", ETH_ALEN},
{"wg0", 0},
{"wg1", 0},
{"wg2", 0},
};
int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (sock == -1)
exit(1);
unsigned i;
for (i = 0; i < sizeof(devtypes) / sizeof(devtypes[0]); i++)
netlink_add_device(&nlmsg, sock, devtypes[i].type, devtypes[i].dev);
for (i = 0; i < sizeof(devmasters) / (sizeof(devmasters[0])); i++) {
char master[32], slave0[32], veth0[32], slave1[32], veth1[32];
sprintf(slave0, "%s_slave_0", devmasters[i]);
sprintf(veth0, "veth0_to_%s", devmasters[i]);
netlink_add_veth(&nlmsg, sock, slave0, veth0);
sprintf(slave1, "%s_slave_1", devmasters[i]);
sprintf(veth1, "veth1_to_%s", devmasters[i]);
netlink_add_veth(&nlmsg, sock, slave1, veth1);
sprintf(master, "%s0", devmasters[i]);
netlink_device_change(&nlmsg, sock, slave0, false, master, 0, 0, NULL);
netlink_device_change(&nlmsg, sock, slave1, false, master, 0, 0, NULL);
}
netlink_device_change(&nlmsg, sock, "bridge_slave_0", true, 0, 0, 0, NULL);
netlink_device_change(&nlmsg, sock, "bridge_slave_1", true, 0, 0, 0, NULL);
netlink_add_veth(&nlmsg, sock, "hsr_slave_0", "veth0_to_hsr");
netlink_add_veth(&nlmsg, sock, "hsr_slave_1", "veth1_to_hsr");
netlink_add_hsr(&nlmsg, sock, "hsr0", "hsr_slave_0", "hsr_slave_1");
netlink_device_change(&nlmsg, sock, "hsr_slave_0", true, 0, 0, 0, NULL);
netlink_device_change(&nlmsg, sock, "hsr_slave_1", true, 0, 0, 0, NULL);
netlink_add_veth(&nlmsg, sock, "veth0_virt_wifi", "veth1_virt_wifi");
netlink_add_linked(&nlmsg, sock, "virt_wifi", "virt_wifi0",
"veth1_virt_wifi");
netlink_add_veth(&nlmsg, sock, "veth0_vlan", "veth1_vlan");
netlink_add_vlan(&nlmsg, sock, "vlan0", "veth0_vlan", 0, htons(ETH_P_8021Q));
netlink_add_vlan(&nlmsg, sock, "vlan1", "veth0_vlan", 1, htons(ETH_P_8021AD));
netlink_add_macvlan(&nlmsg, sock, "macvlan0", "veth1_vlan");
netlink_add_macvlan(&nlmsg, sock, "macvlan1", "veth1_vlan");
netlink_add_ipvlan(&nlmsg, sock, "ipvlan0", "veth0_vlan", IPVLAN_MODE_L2, 0);
netlink_add_ipvlan(&nlmsg, sock, "ipvlan1", "veth0_vlan", IPVLAN_MODE_L3S,
IPVLAN_F_VEPA);
netlink_add_veth(&nlmsg, sock, "veth0_macvtap", "veth1_macvtap");
netlink_add_linked(&nlmsg, sock, "macvtap", "macvtap0", "veth0_macvtap");
netlink_add_linked(&nlmsg, sock, "macsec", "macsec0", "veth1_macvtap");
char addr[32];
sprintf(addr, DEV_IPV4, 14 + 10);
struct in_addr geneve_addr4;
if (inet_pton(AF_INET, addr, &geneve_addr4) <= 0)
exit(1);
struct in6_addr geneve_addr6;
if (inet_pton(AF_INET6, "fc00::01", &geneve_addr6) <= 0)
exit(1);
netlink_add_geneve(&nlmsg, sock, "geneve0", 0, &geneve_addr4, 0);
netlink_add_geneve(&nlmsg, sock, "geneve1", 1, 0, &geneve_addr6);
netdevsim_add((int)procid, 4);
netlink_wireguard_setup();
for (i = 0; i < sizeof(devices) / (sizeof(devices[0])); i++) {
char addr[32];
sprintf(addr, DEV_IPV4, i + 10);
netlink_add_addr4(&nlmsg, sock, devices[i].name, addr);
if (!devices[i].noipv6) {
sprintf(addr, DEV_IPV6, i + 10);
netlink_add_addr6(&nlmsg, sock, devices[i].name, addr);
}
uint64_t macaddr = DEV_MAC + ((i + 10ull) << 40);
netlink_device_change(&nlmsg, sock, devices[i].name, true, 0, &macaddr,
devices[i].macsize, NULL);
}
close(sock);
}
static void initialize_netdevices_init(void)
{
int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (sock == -1)
exit(1);
struct {
const char* type;
int macsize;
bool noipv6;
bool noup;
} devtypes[] = {
{"nr", 7, true},
{"rose", 5, true, true},
};
unsigned i;
for (i = 0; i < sizeof(devtypes) / sizeof(devtypes[0]); i++) {
char dev[32], addr[32];
sprintf(dev, "%s%d", devtypes[i].type, (int)procid);
sprintf(addr, "172.30.%d.%d", i, (int)procid + 1);
netlink_add_addr4(&nlmsg, sock, dev, addr);
if (!devtypes[i].noipv6) {
sprintf(addr, "fe88::%02x:%02x", i, (int)procid + 1);
netlink_add_addr6(&nlmsg, sock, dev, addr);
}
int macsize = devtypes[i].macsize;
uint64_t macaddr = 0xbbbbbb +
((unsigned long long)i << (8 * (macsize - 2))) +
(procid << (8 * (macsize - 1)));
netlink_device_change(&nlmsg, sock, dev, !devtypes[i].noup, 0, &macaddr,
macsize, NULL);
}
close(sock);
}
static int read_tun(char* data, int size)
{
if (tunfd < 0)
return -1;
int rv = read(tunfd, data, size);
if (rv < 0) {
if (errno == EAGAIN || errno == EBADFD)
return -1;
exit(1);
}
return rv;
}
static void flush_tun()
{
char data[1000];
while (read_tun(&data[0], sizeof(data)) != -1) {
}
}
#define MAX_FDS 30
static long syz_open_dev(volatile long a0, volatile long a1, volatile long a2)
{
if (a0 == 0xc || a0 == 0xb) {
char buf[128];
sprintf(buf, "/dev/%s/%d:%d", a0 == 0xc ? "char" : "block", (uint8_t)a1,
(uint8_t)a2);
return open(buf, O_RDWR, 0);
} else {
char buf[1024];
char* hash;
strncpy(buf, (char*)a0, sizeof(buf) - 1);
buf[sizeof(buf) - 1] = 0;
while ((hash = strchr(buf, '#'))) {
*hash = '0' + (char)(a1 % 10);
a1 /= 10;
}
return open(buf, a2, 0);
}
}
#define BTPROTO_HCI 1
#define ACL_LINK 1
#define SCAN_PAGE 2
typedef struct {
uint8_t b[6];
} __attribute__((packed)) bdaddr_t;
#define HCI_COMMAND_PKT 1
#define HCI_EVENT_PKT 4
#define HCI_VENDOR_PKT 0xff
struct hci_command_hdr {
uint16_t opcode;
uint8_t plen;
} __attribute__((packed));
struct hci_event_hdr {
uint8_t evt;
uint8_t plen;
} __attribute__((packed));
#define HCI_EV_CONN_COMPLETE 0x03
struct hci_ev_conn_complete {
uint8_t status;
uint16_t handle;
bdaddr_t bdaddr;
uint8_t link_type;
uint8_t encr_mode;
} __attribute__((packed));
#define HCI_EV_CONN_REQUEST 0x04
struct hci_ev_conn_request {
bdaddr_t bdaddr;
uint8_t dev_class[3];
uint8_t link_type;
} __attribute__((packed));
#define HCI_EV_REMOTE_FEATURES 0x0b
struct hci_ev_remote_features {
uint8_t status;
uint16_t handle;
uint8_t features[8];
} __attribute__((packed));
#define HCI_EV_CMD_COMPLETE 0x0e
struct hci_ev_cmd_complete {
uint8_t ncmd;
uint16_t opcode;
} __attribute__((packed));
#define HCI_OP_WRITE_SCAN_ENABLE 0x0c1a
#define HCI_OP_READ_BUFFER_SIZE 0x1005
struct hci_rp_read_buffer_size {
uint8_t status;
uint16_t acl_mtu;
uint8_t sco_mtu;
uint16_t acl_max_pkt;
uint16_t sco_max_pkt;
} __attribute__((packed));
#define HCI_OP_READ_BD_ADDR 0x1009
struct hci_rp_read_bd_addr {
uint8_t status;
bdaddr_t bdaddr;
} __attribute__((packed));
#define HCI_EV_LE_META 0x3e
struct hci_ev_le_meta {
uint8_t subevent;
} __attribute__((packed));
#define HCI_EV_LE_CONN_COMPLETE 0x01
struct hci_ev_le_conn_complete {
uint8_t status;
uint16_t handle;
uint8_t role;
uint8_t bdaddr_type;
bdaddr_t bdaddr;
uint16_t interval;
uint16_t latency;
uint16_t supervision_timeout;
uint8_t clk_accurancy;
} __attribute__((packed));
struct hci_dev_req {
uint16_t dev_id;
uint32_t dev_opt;
};
struct vhci_vendor_pkt {
uint8_t type;
uint8_t opcode;
uint16_t id;
};
#define HCIDEVUP _IOW('H', 201, int)
#define HCISETSCAN _IOW('H', 221, int)
static int vhci_fd = -1;
static void rfkill_unblock_all()
{
int fd = open("/dev/rfkill", O_WRONLY);
if (fd < 0)
exit(1);
struct rfkill_event event = {0};
event.idx = 0;
event.type = RFKILL_TYPE_ALL;
event.op = RFKILL_OP_CHANGE_ALL;
event.soft = 0;
event.hard = 0;
if (write(fd, &event, sizeof(event)) < 0)
exit(1);
close(fd);
}
static void hci_send_event_packet(int fd, uint8_t evt, void* data,
size_t data_len)
{
struct iovec iv[3];
struct hci_event_hdr hdr;
hdr.evt = evt;
hdr.plen = data_len;
uint8_t type = HCI_EVENT_PKT;
iv[0].iov_base = &type;
iv[0].iov_len = sizeof(type);
iv[1].iov_base = &hdr;
iv[1].iov_len = sizeof(hdr);
iv[2].iov_base = data;
iv[2].iov_len = data_len;
if (writev(fd, iv, sizeof(iv) / sizeof(struct iovec)) < 0)
exit(1);
}
static void hci_send_event_cmd_complete(int fd, uint16_t opcode, void* data,
size_t data_len)
{
struct iovec iv[4];
struct hci_event_hdr hdr;
hdr.evt = HCI_EV_CMD_COMPLETE;
hdr.plen = sizeof(struct hci_ev_cmd_complete) + data_len;
struct hci_ev_cmd_complete evt_hdr;
evt_hdr.ncmd = 1;
evt_hdr.opcode = opcode;
uint8_t type = HCI_EVENT_PKT;
iv[0].iov_base = &type;
iv[0].iov_len = sizeof(type);
iv[1].iov_base = &hdr;
iv[1].iov_len = sizeof(hdr);
iv[2].iov_base = &evt_hdr;
iv[2].iov_len = sizeof(evt_hdr);
iv[3].iov_base = data;
iv[3].iov_len = data_len;
if (writev(fd, iv, sizeof(iv) / sizeof(struct iovec)) < 0)
exit(1);
}
static bool process_command_pkt(int fd, char* buf, ssize_t buf_size)
{
struct hci_command_hdr* hdr = (struct hci_command_hdr*)buf;
if (buf_size < (ssize_t)sizeof(struct hci_command_hdr) ||
hdr->plen != buf_size - sizeof(struct hci_command_hdr)) {
exit(1);
}
switch (hdr->opcode) {
case HCI_OP_WRITE_SCAN_ENABLE: {
uint8_t status = 0;
hci_send_event_cmd_complete(fd, hdr->opcode, &status, sizeof(status));
return true;
}
case HCI_OP_READ_BD_ADDR: {
struct hci_rp_read_bd_addr rp = {0};
rp.status = 0;
memset(&rp.bdaddr, 0xaa, 6);
hci_send_event_cmd_complete(fd, hdr->opcode, &rp, sizeof(rp));
return false;
}
case HCI_OP_READ_BUFFER_SIZE: {
struct hci_rp_read_buffer_size rp = {0};
rp.status = 0;
rp.acl_mtu = 1021;
rp.sco_mtu = 96;
rp.acl_max_pkt = 4;
rp.sco_max_pkt = 6;
hci_send_event_cmd_complete(fd, hdr->opcode, &rp, sizeof(rp));
return false;
}
}
char dummy[0xf9] = {0};
hci_send_event_cmd_complete(fd, hdr->opcode, dummy, sizeof(dummy));
return false;
}
static void* event_thread(void* arg)
{
while (1) {
char buf[1024] = {0};
ssize_t buf_size = read(vhci_fd, buf, sizeof(buf));
if (buf_size < 0)
exit(1);
if (buf_size > 0 && buf[0] == HCI_COMMAND_PKT) {
if (process_command_pkt(vhci_fd, buf + 1, buf_size - 1))
break;
}
}
return NULL;
}
#define HCI_HANDLE_1 200
#define HCI_HANDLE_2 201
static void initialize_vhci()
{
int hci_sock = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI);
if (hci_sock < 0)
exit(1);
vhci_fd = open("/dev/vhci", O_RDWR);
if (vhci_fd == -1)
exit(1);
const int kVhciFd = 241;
if (dup2(vhci_fd, kVhciFd) < 0)
exit(1);
close(vhci_fd);
vhci_fd = kVhciFd;
struct vhci_vendor_pkt vendor_pkt;
if (read(vhci_fd, &vendor_pkt, sizeof(vendor_pkt)) != sizeof(vendor_pkt))
exit(1);
if (vendor_pkt.type != HCI_VENDOR_PKT)
exit(1);
pthread_t th;
if (pthread_create(&th, NULL, event_thread, NULL))
exit(1);
int ret = ioctl(hci_sock, HCIDEVUP, vendor_pkt.id);
if (ret) {
if (errno == ERFKILL) {
rfkill_unblock_all();
ret = ioctl(hci_sock, HCIDEVUP, vendor_pkt.id);
}
if (ret && errno != EALREADY)
exit(1);
}
struct hci_dev_req dr = {0};
dr.dev_id = vendor_pkt.id;
dr.dev_opt = SCAN_PAGE;
if (ioctl(hci_sock, HCISETSCAN, &dr))
exit(1);
struct hci_ev_conn_request request;
memset(&request, 0, sizeof(request));
memset(&request.bdaddr, 0xaa, 6);
*(uint8_t*)&request.bdaddr.b[5] = 0x10;
request.link_type = ACL_LINK;
hci_send_event_packet(vhci_fd, HCI_EV_CONN_REQUEST, &request,
sizeof(request));
struct hci_ev_conn_complete complete;
memset(&complete, 0, sizeof(complete));
complete.status = 0;
complete.handle = HCI_HANDLE_1;
memset(&complete.bdaddr, 0xaa, 6);
*(uint8_t*)&complete.bdaddr.b[5] = 0x10;
complete.link_type = ACL_LINK;
complete.encr_mode = 0;
hci_send_event_packet(vhci_fd, HCI_EV_CONN_COMPLETE, &complete,
sizeof(complete));
struct hci_ev_remote_features features;
memset(&features, 0, sizeof(features));
features.status = 0;
features.handle = HCI_HANDLE_1;
hci_send_event_packet(vhci_fd, HCI_EV_REMOTE_FEATURES, &features,
sizeof(features));
struct {
struct hci_ev_le_meta le_meta;
struct hci_ev_le_conn_complete le_conn;
} le_conn;
memset(&le_conn, 0, sizeof(le_conn));
le_conn.le_meta.subevent = HCI_EV_LE_CONN_COMPLETE;
memset(&le_conn.le_conn.bdaddr, 0xaa, 6);
*(uint8_t*)&le_conn.le_conn.bdaddr.b[5] = 0x11;
le_conn.le_conn.role = 1;
le_conn.le_conn.handle = HCI_HANDLE_2;
hci_send_event_packet(vhci_fd, HCI_EV_LE_META, &le_conn, sizeof(le_conn));
pthread_join(th, NULL);
close(hci_sock);
}
#define XT_TABLE_SIZE 1536
#define XT_MAX_ENTRIES 10
struct xt_counters {
uint64_t pcnt, bcnt;
};
struct ipt_getinfo {
char name[32];
unsigned int valid_hooks;
unsigned int hook_entry[5];
unsigned int underflow[5];
unsigned int num_entries;
unsigned int size;
};
struct ipt_get_entries {
char name[32];
unsigned int size;
void* entrytable[XT_TABLE_SIZE / sizeof(void*)];
};
struct ipt_replace {
char name[32];
unsigned int valid_hooks;
unsigned int num_entries;
unsigned int size;
unsigned int hook_entry[5];
unsigned int underflow[5];
unsigned int num_counters;
struct xt_counters* counters;
char entrytable[XT_TABLE_SIZE];
};
struct ipt_table_desc {
const char* name;
struct ipt_getinfo info;
struct ipt_replace replace;
};
static struct ipt_table_desc ipv4_tables[] = {
{.name = "filter"}, {.name = "nat"}, {.name = "mangle"},
{.name = "raw"}, {.name = "security"},
};
static struct ipt_table_desc ipv6_tables[] = {
{.name = "filter"}, {.name = "nat"}, {.name = "mangle"},
{.name = "raw"}, {.name = "security"},
};
#define IPT_BASE_CTL 64
#define IPT_SO_SET_REPLACE (IPT_BASE_CTL)
#define IPT_SO_GET_INFO (IPT_BASE_CTL)
#define IPT_SO_GET_ENTRIES (IPT_BASE_CTL + 1)
struct arpt_getinfo {
char name[32];
unsigned int valid_hooks;
unsigned int hook_entry[3];
unsigned int underflow[3];
unsigned int num_entries;
unsigned int size;
};
struct arpt_get_entries {
char name[32];
unsigned int size;
void* entrytable[XT_TABLE_SIZE / sizeof(void*)];
};
struct arpt_replace {
char name[32];
unsigned int valid_hooks;
unsigned int num_entries;
unsigned int size;
unsigned int hook_entry[3];
unsigned int underflow[3];
unsigned int num_counters;
struct xt_counters* counters;
char entrytable[XT_TABLE_SIZE];
};
struct arpt_table_desc {
const char* name;
struct arpt_getinfo info;
struct arpt_replace replace;
};
static struct arpt_table_desc arpt_tables[] = {
{.name = "filter"},
};
#define ARPT_BASE_CTL 96
#define ARPT_SO_SET_REPLACE (ARPT_BASE_CTL)
#define ARPT_SO_GET_INFO (ARPT_BASE_CTL)
#define ARPT_SO_GET_ENTRIES (ARPT_BASE_CTL + 1)
static void checkpoint_iptables(struct ipt_table_desc* tables, int num_tables,
int family, int level)
{
int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
if (fd == -1) {
switch (errno) {
case EAFNOSUPPORT:
case ENOPROTOOPT:
return;
}
exit(1);
}
for (int i = 0; i < num_tables; i++) {
struct ipt_table_desc* table = &tables[i];
strcpy(table->info.name, table->name);
strcpy(table->replace.name, table->name);
socklen_t optlen = sizeof(table->info);
if (getsockopt(fd, level, IPT_SO_GET_INFO, &table->info, &optlen)) {
switch (errno) {
case EPERM:
case ENOENT:
case ENOPROTOOPT:
continue;
}
exit(1);
}
if (table->info.size > sizeof(table->replace.entrytable))
exit(1);
if (table->info.num_entries > XT_MAX_ENTRIES)
exit(1);
struct ipt_get_entries entries;
memset(&entries, 0, sizeof(entries));
strcpy(entries.name, table->name);
entries.size = table->info.size;
optlen = sizeof(entries) - sizeof(entries.entrytable) + table->info.size;
if (getsockopt(fd, level, IPT_SO_GET_ENTRIES, &entries, &optlen))
exit(1);
table->replace.valid_hooks = table->info.valid_hooks;
table->replace.num_entries = table->info.num_entries;
table->replace.size = table->info.size;
memcpy(table->replace.hook_entry, table->info.hook_entry,
sizeof(table->replace.hook_entry));
memcpy(table->replace.underflow, table->info.underflow,
sizeof(table->replace.underflow));
memcpy(table->replace.entrytable, entries.entrytable, table->info.size);
}
close(fd);
}
static void reset_iptables(struct ipt_table_desc* tables, int num_tables,
int family, int level)
{
int fd = socket(family, SOCK_STREAM, IPPROTO_TCP);
if (fd == -1) {
switch (errno) {
case EAFNOSUPPORT:
case ENOPROTOOPT:
return;
}
exit(1);
}
for (int i = 0; i < num_tables; i++) {
struct ipt_table_desc* table = &tables[i];
if (table->info.valid_hooks == 0)
continue;
struct ipt_getinfo info;
memset(&info, 0, sizeof(info));
strcpy(info.name, table->name);
socklen_t optlen = sizeof(info);
if (getsockopt(fd, level, IPT_SO_GET_INFO, &info, &optlen))
exit(1);
if (memcmp(&table->info, &info, sizeof(table->info)) == 0) {
struct ipt_get_entries entries;
memset(&entries, 0, sizeof(entries));
strcpy(entries.name, table->name);
entries.size = table->info.size;
optlen = sizeof(entries) - sizeof(entries.entrytable) + entries.size;
if (getsockopt(fd, level, IPT_SO_GET_ENTRIES, &entries, &optlen))
exit(1);
if (memcmp(table->replace.entrytable, entries.entrytable,
table->info.size) == 0)
continue;
}
struct xt_counters counters[XT_MAX_ENTRIES];
table->replace.num_counters = info.num_entries;
table->replace.counters = counters;
optlen = sizeof(table->replace) - sizeof(table->replace.entrytable) +
table->replace.size;
if (setsockopt(fd, level, IPT_SO_SET_REPLACE, &table->replace, optlen))
exit(1);
}
close(fd);
}
static void checkpoint_arptables(void)
{
int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (fd == -1) {
switch (errno) {
case EAFNOSUPPORT:
case ENOPROTOOPT:
return;
}
exit(1);
}
for (unsigned i = 0; i < sizeof(arpt_tables) / sizeof(arpt_tables[0]); i++) {
struct arpt_table_desc* table = &arpt_tables[i];
strcpy(table->info.name, table->name);
strcpy(table->replace.name, table->name);
socklen_t optlen = sizeof(table->info);
if (getsockopt(fd, SOL_IP, ARPT_SO_GET_INFO, &table->info, &optlen)) {
switch (errno) {
case EPERM:
case ENOENT:
case ENOPROTOOPT:
continue;
}
exit(1);
}
if (table->info.size > sizeof(table->replace.entrytable))
exit(1);
if (table->info.num_entries > XT_MAX_ENTRIES)
exit(1);
struct arpt_get_entries entries;
memset(&entries, 0, sizeof(entries));
strcpy(entries.name, table->name);
entries.size = table->info.size;
optlen = sizeof(entries) - sizeof(entries.entrytable) + table->info.size;
if (getsockopt(fd, SOL_IP, ARPT_SO_GET_ENTRIES, &entries, &optlen))
exit(1);
table->replace.valid_hooks = table->info.valid_hooks;
table->replace.num_entries = table->info.num_entries;
table->replace.size = table->info.size;
memcpy(table->replace.hook_entry, table->info.hook_entry,
sizeof(table->replace.hook_entry));
memcpy(table->replace.underflow, table->info.underflow,
sizeof(table->replace.underflow));
memcpy(table->replace.entrytable, entries.entrytable, table->info.size);
}
close(fd);
}
static void reset_arptables()
{
int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (fd == -1) {
switch (errno) {
case EAFNOSUPPORT:
case ENOPROTOOPT:
return;
}
exit(1);
}
for (unsigned i = 0; i < sizeof(arpt_tables) / sizeof(arpt_tables[0]); i++) {
struct arpt_table_desc* table = &arpt_tables[i];
if (table->info.valid_hooks == 0)
continue;
struct arpt_getinfo info;
memset(&info, 0, sizeof(info));
strcpy(info.name, table->name);
socklen_t optlen = sizeof(info);
if (getsockopt(fd, SOL_IP, ARPT_SO_GET_INFO, &info, &optlen))
exit(1);
if (memcmp(&table->info, &info, sizeof(table->info)) == 0) {
struct arpt_get_entries entries;
memset(&entries, 0, sizeof(entries));
strcpy(entries.name, table->name);
entries.size = table->info.size;
optlen = sizeof(entries) - sizeof(entries.entrytable) + entries.size;
if (getsockopt(fd, SOL_IP, ARPT_SO_GET_ENTRIES, &entries, &optlen))
exit(1);
if (memcmp(table->replace.entrytable, entries.entrytable,
table->info.size) == 0)
continue;
} else {
}
struct xt_counters counters[XT_MAX_ENTRIES];
table->replace.num_counters = info.num_entries;
table->replace.counters = counters;
optlen = sizeof(table->replace) - sizeof(table->replace.entrytable) +
table->replace.size;
if (setsockopt(fd, SOL_IP, ARPT_SO_SET_REPLACE, &table->replace, optlen))
exit(1);
}
close(fd);
}
#define NF_BR_NUMHOOKS 6
#define EBT_TABLE_MAXNAMELEN 32
#define EBT_CHAIN_MAXNAMELEN 32
#define EBT_BASE_CTL 128
#define EBT_SO_SET_ENTRIES (EBT_BASE_CTL)
#define EBT_SO_GET_INFO (EBT_BASE_CTL)
#define EBT_SO_GET_ENTRIES (EBT_SO_GET_INFO + 1)
#define EBT_SO_GET_INIT_INFO (EBT_SO_GET_ENTRIES + 1)
#define EBT_SO_GET_INIT_ENTRIES (EBT_SO_GET_INIT_INFO + 1)
struct ebt_replace {
char name[EBT_TABLE_MAXNAMELEN];
unsigned int valid_hooks;
unsigned int nentries;
unsigned int entries_size;
struct ebt_entries* hook_entry[NF_BR_NUMHOOKS];
unsigned int num_counters;
struct ebt_counter* counters;
char* entries;
};
struct ebt_entries {
unsigned int distinguisher;
char name[EBT_CHAIN_MAXNAMELEN];
unsigned int counter_offset;
int policy;
unsigned int nentries;
char data[0] __attribute__((aligned(__alignof__(struct ebt_replace))));
};
struct ebt_table_desc {
const char* name;
struct ebt_replace replace;
char entrytable[XT_TABLE_SIZE];
};
static struct ebt_table_desc ebt_tables[] = {
{.name = "filter"},
{.name = "nat"},
{.name = "broute"},
};
static void checkpoint_ebtables(void)
{
int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (fd == -1) {
switch (errno) {
case EAFNOSUPPORT:
case ENOPROTOOPT:
return;
}
exit(1);
}
for (size_t i = 0; i < sizeof(ebt_tables) / sizeof(ebt_tables[0]); i++) {
struct ebt_table_desc* table = &ebt_tables[i];
strcpy(table->replace.name, table->name);
socklen_t optlen = sizeof(table->replace);
if (getsockopt(fd, SOL_IP, EBT_SO_GET_INIT_INFO, &table->replace,
&optlen)) {
switch (errno) {
case EPERM:
case ENOENT:
case ENOPROTOOPT:
continue;
}
exit(1);
}
if (table->replace.entries_size > sizeof(table->entrytable))
exit(1);
table->replace.num_counters = 0;
table->replace.entries = table->entrytable;
optlen = sizeof(table->replace) + table->replace.entries_size;
if (getsockopt(fd, SOL_IP, EBT_SO_GET_INIT_ENTRIES, &table->replace,
&optlen))
exit(1);
}
close(fd);
}
static void reset_ebtables()
{
int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (fd == -1) {
switch (errno) {
case EAFNOSUPPORT:
case ENOPROTOOPT:
return;
}
exit(1);
}
for (unsigned i = 0; i < sizeof(ebt_tables) / sizeof(ebt_tables[0]); i++) {
struct ebt_table_desc* table = &ebt_tables[i];
if (table->replace.valid_hooks == 0)
continue;
struct ebt_replace replace;
memset(&replace, 0, sizeof(replace));
strcpy(replace.name, table->name);
socklen_t optlen = sizeof(replace);
if (getsockopt(fd, SOL_IP, EBT_SO_GET_INFO, &replace, &optlen))
exit(1);
replace.num_counters = 0;
table->replace.entries = 0;
for (unsigned h = 0; h < NF_BR_NUMHOOKS; h++)
table->replace.hook_entry[h] = 0;
if (memcmp(&table->replace, &replace, sizeof(table->replace)) == 0) {
char entrytable[XT_TABLE_SIZE];
memset(&entrytable, 0, sizeof(entrytable));
replace.entries = entrytable;
optlen = sizeof(replace) + replace.entries_size;
if (getsockopt(fd, SOL_IP, EBT_SO_GET_ENTRIES, &replace, &optlen))
exit(1);
if (memcmp(table->entrytable, entrytable, replace.entries_size) == 0)
continue;
}
for (unsigned j = 0, h = 0; h < NF_BR_NUMHOOKS; h++) {
if (table->replace.valid_hooks & (1 << h)) {
table->replace.hook_entry[h] =
(struct ebt_entries*)table->entrytable + j;
j++;
}
}
table->replace.entries = table->entrytable;
optlen = sizeof(table->replace) + table->replace.entries_size;
if (setsockopt(fd, SOL_IP, EBT_SO_SET_ENTRIES, &table->replace, optlen))
exit(1);
}
close(fd);
}
static void checkpoint_net_namespace(void)
{
checkpoint_ebtables();
checkpoint_arptables();
checkpoint_iptables(ipv4_tables, sizeof(ipv4_tables) / sizeof(ipv4_tables[0]),
AF_INET, SOL_IP);
checkpoint_iptables(ipv6_tables, sizeof(ipv6_tables) / sizeof(ipv6_tables[0]),
AF_INET6, SOL_IPV6);
}
static void reset_net_namespace(void)
{
reset_ebtables();
reset_arptables();
reset_iptables(ipv4_tables, sizeof(ipv4_tables) / sizeof(ipv4_tables[0]),
AF_INET, SOL_IP);
reset_iptables(ipv6_tables, sizeof(ipv6_tables) / sizeof(ipv6_tables[0]),
AF_INET6, SOL_IPV6);
}
static void setup_cgroups()
{
if (mkdir("/syzcgroup", 0777)) {
}
if (mkdir("/syzcgroup/unified", 0777)) {
}
if (mount("none", "/syzcgroup/unified", "cgroup2", 0, NULL)) {
}
if (chmod("/syzcgroup/unified", 0777)) {
}
write_file("/syzcgroup/unified/cgroup.subtree_control",
"+cpu +memory +io +pids +rdma");
if (mkdir("/syzcgroup/cpu", 0777)) {
}
if (mount("none", "/syzcgroup/cpu", "cgroup", 0,
"cpuset,cpuacct,perf_event,hugetlb")) {
}
write_file("/syzcgroup/cpu/cgroup.clone_children", "1");
write_file("/syzcgroup/cpu/cpuset.memory_pressure_enabled", "1");
if (chmod("/syzcgroup/cpu", 0777)) {
}
if (mkdir("/syzcgroup/net", 0777)) {
}
if (mount("none", "/syzcgroup/net", "cgroup", 0,
"net_cls,net_prio,devices,freezer")) {
}
if (chmod("/syzcgroup/net", 0777)) {
}
}
static void setup_cgroups_loop()
{
int pid = getpid();
char file[128];
char cgroupdir[64];
snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/unified/syz%llu", procid);
if (mkdir(cgroupdir, 0777)) {
}
snprintf(file, sizeof(file), "%s/pids.max", cgroupdir);
write_file(file, "32");
snprintf(file, sizeof(file), "%s/memory.low", cgroupdir);
write_file(file, "%d", 298 << 20);
snprintf(file, sizeof(file), "%s/memory.high", cgroupdir);
write_file(file, "%d", 299 << 20);
snprintf(file, sizeof(file), "%s/memory.max", cgroupdir);
write_file(file, "%d", 300 << 20);
snprintf(file, sizeof(file), "%s/cgroup.procs", cgroupdir);
write_file(file, "%d", pid);
snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/cpu/syz%llu", procid);
if (mkdir(cgroupdir, 0777)) {
}
snprintf(file, sizeof(file), "%s/cgroup.procs", cgroupdir);
write_file(file, "%d", pid);
snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/net/syz%llu", procid);
if (mkdir(cgroupdir, 0777)) {
}
snprintf(file, sizeof(file), "%s/cgroup.procs", cgroupdir);
write_file(file, "%d", pid);
}
static void setup_cgroups_test()
{
char cgroupdir[64];
snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/unified/syz%llu", procid);
if (symlink(cgroupdir, "./cgroup")) {
}
snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/cpu/syz%llu", procid);
if (symlink(cgroupdir, "./cgroup.cpu")) {
}
snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/net/syz%llu", procid);
if (symlink(cgroupdir, "./cgroup.net")) {
}
}
static void setup_common()
{
if (mount(0, "/sys/fs/fuse/connections", "fusectl", 0, 0)) {
}
setup_cgroups();
}
static void loop();
static void sandbox_common()
{
prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0);
setpgrp();
setsid();
struct rlimit rlim;
rlim.rlim_cur = rlim.rlim_max = (200 << 20);
setrlimit(RLIMIT_AS, &rlim);
rlim.rlim_cur = rlim.rlim_max = 32 << 20;
setrlimit(RLIMIT_MEMLOCK, &rlim);
rlim.rlim_cur = rlim.rlim_max = 136 << 20;
setrlimit(RLIMIT_FSIZE, &rlim);
rlim.rlim_cur = rlim.rlim_max = 1 << 20;
setrlimit(RLIMIT_STACK, &rlim);
rlim.rlim_cur = rlim.rlim_max = 0;
setrlimit(RLIMIT_CORE, &rlim);
rlim.rlim_cur = rlim.rlim_max = 256;
setrlimit(RLIMIT_NOFILE, &rlim);
if (unshare(CLONE_NEWNS)) {
}
if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL)) {
}
if (unshare(CLONE_NEWIPC)) {
}
if (unshare(0x02000000)) {
}
if (unshare(CLONE_NEWUTS)) {
}
if (unshare(CLONE_SYSVSEM)) {
}
typedef struct {
const char* name;
const char* value;
} sysctl_t;
static const sysctl_t sysctls[] = {
{"/proc/sys/kernel/shmmax", "16777216"},
{"/proc/sys/kernel/shmall", "536870912"},
{"/proc/sys/kernel/shmmni", "1024"},
{"/proc/sys/kernel/msgmax", "8192"},
{"/proc/sys/kernel/msgmni", "1024"},
{"/proc/sys/kernel/msgmnb", "1024"},
{"/proc/sys/kernel/sem", "1024 1048576 500 1024"},
};
unsigned i;
for (i = 0; i < sizeof(sysctls) / sizeof(sysctls[0]); i++)
write_file(sysctls[i].name, sysctls[i].value);
}
static int wait_for_loop(int pid)
{
if (pid < 0)
exit(1);
int status = 0;
while (waitpid(-1, &status, __WALL) != pid) {
}
return WEXITSTATUS(status);
}
static void drop_caps(void)
{
struct __user_cap_header_struct cap_hdr = {};
struct __user_cap_data_struct cap_data[2] = {};
cap_hdr.version = _LINUX_CAPABILITY_VERSION_3;
cap_hdr.pid = getpid();
if (syscall(SYS_capget, &cap_hdr, &cap_data))
exit(1);
const int drop = (1 << CAP_SYS_PTRACE) | (1 << CAP_SYS_NICE);
cap_data[0].effective &= ~drop;
cap_data[0].permitted &= ~drop;
cap_data[0].inheritable &= ~drop;
if (syscall(SYS_capset, &cap_hdr, &cap_data))
exit(1);
}
static int do_sandbox_none(void)
{
if (unshare(CLONE_NEWPID)) {
}
int pid = fork();
if (pid != 0)
return wait_for_loop(pid);
setup_common();
initialize_vhci();
sandbox_common();
drop_caps();
initialize_netdevices_init();
if (unshare(CLONE_NEWNET)) {
}
initialize_tun();
initialize_netdevices();
loop();
exit(1);
}
#define FS_IOC_SETFLAGS _IOW('f', 2, long)
static void remove_dir(const char* dir)
{
int iter = 0;
DIR* dp = 0;
retry:
while (umount2(dir, MNT_DETACH) == 0) {
}
dp = opendir(dir);
if (dp == NULL) {
if (errno == EMFILE) {
exit(1);
}
exit(1);
}
struct dirent* ep = 0;
while ((ep = readdir(dp))) {
if (strcmp(ep->d_name, ".") == 0 || strcmp(ep->d_name, "..") == 0)
continue;
char filename[FILENAME_MAX];
snprintf(filename, sizeof(filename), "%s/%s", dir, ep->d_name);
while (umount2(filename, MNT_DETACH) == 0) {
}
struct stat st;
if (lstat(filename, &st))
exit(1);
if (S_ISDIR(st.st_mode)) {
remove_dir(filename);
continue;
}
int i;
for (i = 0;; i++) {
if (unlink(filename) == 0)
break;
if (errno == EPERM) {
int fd = open(filename, O_RDONLY);
if (fd != -1) {
long flags = 0;
if (ioctl(fd, FS_IOC_SETFLAGS, &flags) == 0) {
}
close(fd);
continue;
}
}
if (errno == EROFS) {
break;
}
if (errno != EBUSY || i > 100)
exit(1);
if (umount2(filename, MNT_DETACH))
exit(1);
}
}
closedir(dp);
for (int i = 0;; i++) {
if (rmdir(dir) == 0)
break;
if (i < 100) {
if (errno == EPERM) {
int fd = open(dir, O_RDONLY);
if (fd != -1) {
long flags = 0;
if (ioctl(fd, FS_IOC_SETFLAGS, &flags) == 0) {
}
close(fd);
continue;
}
}
if (errno == EROFS) {
break;
}
if (errno == EBUSY) {
if (umount2(dir, MNT_DETACH))
exit(1);
continue;
}
if (errno == ENOTEMPTY) {
if (iter < 100) {
iter++;
goto retry;
}
}
}
exit(1);
}
}
static void kill_and_wait(int pid, int* status)
{
kill(-pid, SIGKILL);
kill(pid, SIGKILL);
for (int i = 0; i < 100; i++) {
if (waitpid(-1, status, WNOHANG | __WALL) == pid)
return;
usleep(1000);
}
DIR* dir = opendir("/sys/fs/fuse/connections");
if (dir) {
for (;;) {
struct dirent* ent = readdir(dir);
if (!ent)
break;
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
continue;
char abort[300];
snprintf(abort, sizeof(abort), "/sys/fs/fuse/connections/%s/abort",
ent->d_name);
int fd = open(abort, O_WRONLY);
if (fd == -1) {
continue;
}
if (write(fd, abort, 1) < 0) {
}
close(fd);
}
closedir(dir);
} else {
}
while (waitpid(-1, status, __WALL) != pid) {
}
}
static void setup_loop()
{
setup_cgroups_loop();
checkpoint_net_namespace();
}
static void reset_loop()
{
reset_net_namespace();
}
static void setup_test()
{
prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0);
setpgrp();
setup_cgroups_test();
write_file("/proc/self/oom_score_adj", "1000");
flush_tun();
}
static void close_fds()
{
for (int fd = 3; fd < MAX_FDS; fd++)
close(fd);
}
static void setup_binfmt_misc()
{
if (mount(0, "/proc/sys/fs/binfmt_misc", "binfmt_misc", 0, 0)) {
}
write_file("/proc/sys/fs/binfmt_misc/register", ":syz0:M:0:\x01::./file0:");
write_file("/proc/sys/fs/binfmt_misc/register",
":syz1:M:1:\x02::./file0:POC");
}
struct thread_t {
int created, call;
event_t ready, done;
};
static struct thread_t threads[16];
static void execute_call(int call);
static int running;
static void* thr(void* arg)
{
struct thread_t* th = (struct thread_t*)arg;
for (;;) {
event_wait(&th->ready);
event_reset(&th->ready);
execute_call(th->call);
__atomic_fetch_sub(&running, 1, __ATOMIC_RELAXED);
event_set(&th->done);
}
return 0;
}
static void execute_one(void)
{
int i, call, thread;
int collide = 0;
again:
for (call = 0; call < 6; call++) {
for (thread = 0; thread < (int)(sizeof(threads) / sizeof(threads[0]));
thread++) {
struct thread_t* th = &threads[thread];
if (!th->created) {
th->created = 1;
event_init(&th->ready);
event_init(&th->done);
event_set(&th->done);
thread_start(thr, th);
}
if (!event_isset(&th->done))
continue;
event_reset(&th->done);
th->call = call;
__atomic_fetch_add(&running, 1, __ATOMIC_RELAXED);
event_set(&th->ready);
if (collide && (call % 2) == 0)
break;
event_timedwait(&th->done, 45);
break;
}
}
for (i = 0; i < 100 && __atomic_load_n(&running, __ATOMIC_RELAXED); i++)
sleep_ms(1);
close_fds();
if (!collide) {
collide = 1;
goto again;
}
}
static void execute_one(void);
#define WAIT_FLAGS __WALL
static void loop(void)
{
setup_loop();
int iter = 0;
for (;; iter++) {
char cwdbuf[32];
sprintf(cwdbuf, "./%d", iter);
if (mkdir(cwdbuf, 0777))
exit(1);
reset_loop();
int pid = fork();
if (pid < 0)
exit(1);
if (pid == 0) {
if (chdir(cwdbuf))
exit(1);
setup_test();
execute_one();
exit(0);
}
int status = 0;
uint64_t start = current_time_ms();
for (;;) {
if (waitpid(-1, &status, WNOHANG | WAIT_FLAGS) == pid)
break;
sleep_ms(1);
if (current_time_ms() - start < 5 * 1000)
continue;
kill_and_wait(pid, &status);
break;
}
remove_dir(cwdbuf);
}
}
#ifndef __NR_dup
#define __NR_dup 41
#endif
#ifndef __NR_ioctl
#define __NR_ioctl 54
#endif
#ifndef __NR_mmap
#define __NR_mmap 192
#endif
#ifndef __NR_openat
#define __NR_openat 295
#endif
#ifndef __NR_socketpair
#define __NR_socketpair 360
#endif
#ifndef __NR_write
#define __NR_write 4
#endif
#undef __NR_mmap
#define __NR_mmap __NR_mmap2
uint64_t r[3] = {0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff};
void execute_call(int call)
{
intptr_t res = 0;
switch (call) {
case 0:
NONFAILING(memcpy((void*)0x20000180, "/dev/fb0\000", 9));
res = syscall(__NR_openat, 0xffffff9c, 0x20000180, 0, 0);
if (res != -1)
r[0] = res;
break;
case 1:
NONFAILING(*(uint32_t*)0x20000000 = 0x400);
NONFAILING(*(uint32_t*)0x20000004 = 0);
NONFAILING(*(uint32_t*)0x20000008 = 0);
NONFAILING(*(uint32_t*)0x2000000c = 0xf0);
NONFAILING(*(uint32_t*)0x20000010 = 0);
NONFAILING(*(uint32_t*)0x20000014 = 0);
NONFAILING(*(uint32_t*)0x20000018 = 4);
NONFAILING(*(uint32_t*)0x2000001c = 0);
NONFAILING(*(uint32_t*)0x20000020 = 0);
NONFAILING(*(uint32_t*)0x20000024 = 0);
NONFAILING(*(uint32_t*)0x20000028 = 0);
NONFAILING(*(uint32_t*)0x2000002c = 0);
NONFAILING(*(uint32_t*)0x20000030 = 0);
NONFAILING(*(uint32_t*)0x20000034 = 0);
NONFAILING(*(uint32_t*)0x20000038 = 0);
NONFAILING(*(uint32_t*)0x2000003c = 0);
NONFAILING(*(uint32_t*)0x20000040 = 0);
NONFAILING(*(uint32_t*)0x20000044 = 0);
NONFAILING(*(uint32_t*)0x20000048 = 0);
NONFAILING(*(uint32_t*)0x2000004c = 0);
NONFAILING(*(uint32_t*)0x20000050 = 3);
NONFAILING(*(uint32_t*)0x20000054 = 0);
NONFAILING(*(uint32_t*)0x20000058 = 0);
NONFAILING(*(uint32_t*)0x2000005c = 0);
NONFAILING(*(uint32_t*)0x20000060 = 0);
NONFAILING(*(uint32_t*)0x20000064 = 0);
NONFAILING(*(uint32_t*)0x20000068 = 0);
NONFAILING(*(uint32_t*)0x2000006c = 0);
NONFAILING(*(uint32_t*)0x20000070 = 0);
NONFAILING(*(uint32_t*)0x20000074 = 0);
NONFAILING(*(uint32_t*)0x20000078 = 0);
NONFAILING(*(uint32_t*)0x2000007c = 0);
NONFAILING(*(uint32_t*)0x20000080 = 0);
NONFAILING(*(uint32_t*)0x20000084 = 6);
NONFAILING(*(uint32_t*)0x20000088 = 0);
NONFAILING(*(uint32_t*)0x2000008c = 0);
NONFAILING(*(uint32_t*)0x20000090 = 0);
NONFAILING(*(uint32_t*)0x20000094 = 0);
NONFAILING(*(uint32_t*)0x20000098 = 0);
NONFAILING(*(uint32_t*)0x2000009c = 0);
syscall(__NR_ioctl, (intptr_t)r[0], 0x4601, 0x20000000);
break;
case 2:
syscall(__NR_socketpair, 1, 5, 0, 0x20000000);
break;
case 3:
res = -1;
NONFAILING(res = syz_open_dev(0xc, 4, 1));
if (res != -1)
r[1] = res;
break;
case 4:
res = syscall(__NR_dup, (intptr_t)r[1]);
if (res != -1)
r[2] = res;
break;
case 5:
NONFAILING(*(uint32_t*)0x20001440 = 8);
NONFAILING(memcpy(
(void*)0x20001444,
"\xa2\xe3\xad\x21\xed\x6b\x52\xf9\x9c\xfb\xf4\xc0\x87\xf7\x19\xb4\xd0"
"\x4f\xe7\xff\x7f\xc6\xe5\x53\x9b\x63\x6e\x0e\x8b\x54\x6a\x9b\x37\x60"
"\x94\x37\x08\x90\xe0\x87\x8f\xdb\x1a\xc6\xe7\x04\x9b\x61\xb4\x95\x6c"
"\x40\x9a\x47\x2a\x5b\x67\xf3\x98\x8f\x7e\xf3\x19\x52\xa9\x81\xff\xe8"
"\xd1\x78\x70\x8c\x52\x3c\x92\x1b\x1b\x4d\x4b\x0a\x16\x9b\x58\xd3\x36"
"\xcd\x3b\x78\x13\x0d\xaa\x61\xd8\xe8\x09\xea\x88\x2f\x58\x02\xb7\x7f"
"\x07\x22\x72\x27\xb7\xba\x67\xe0\xe7\x86\x57\xa6\xf5\xc2\xa8\x74\xe6"
"\x2a\x9c\xcd\xc0\xd3\x1a\x0c\x9f\x31\x8c\x0d\xa1\x99\x3b\xd1\x60\xe2"
"\x33\xdf\x4a\x62\x17\x9c\x6f\x30\x9f\x4c\xff\x77\x38\x59\x6e\xca\xe8"
"\x70\x7c\xe0\x65\xcd\x5b\x91\xcd\x0a\xe1\x93\x97\x37\x35\xb3\x6d\x5b"
"\x1b\x63\xe9\x1c\x00\x30\x5d\x3f\x46\x63\x5e\xb0\x16\xd5\xb1\xdd\xa9"
"\x8e\x2d\x74\x9b\xe7\xbd\x1d\xf1\xfb\x3b\x23\x1f\xdc\xdb\x50\x75\xa9"
"\xaa\xa1\xb4\x69\xc3\x09\x00\x00\x00\x00\x00\x00\x00\x75\x27\x1b\x28"
"\x63\x29\xd1\x69\x93\x42\x88\xfd\x78\x9a\xa3\x7d\x6e\x98\xb2\x24\xfd"
"\x44\xb6\x5b\x31\x33\x4f\xfc\x55\xcc\x82\xcd\x3a\xc3\x2e\xcd\x03\xad"
"\xed\x6f\x90\x81\xb4\xdd\x0d\x8b\x38\xf3\xcd\x44\x98\xbe\xe8\x00\x49"
"\x08\x41\xbd\xb1\x14\xf6\xb7\x63\x83\x70\x9d\x8f\x5c\x55\x43\x2a\x90"
"\x9f\xda\x03\x9a\xec\x54\xa1\x23\x6e\x80\xf6\xa8\xab\xad\xea\x76\x62"
"\x49\x6b\xdd\xbb\x42\xbe\x6b\xfb\x2f\x17\x95\x9d\x1f\x41\x6e\x56\xc7"
"\x1b\x19\x31\x87\x02\x62\xf5\xe8\x01\x11\x92\x42\xca\x5b\x6b\xfc\x82"
"\x1e\x7e\x7d\xaf\x24\x51\x13\x8e\x64\x5b\xb8\x0c\x61\x76\x69\x31\x4e"
"\x2f\xbe\x70\xde\x98\xec\x76\xa9\xe4\x0d\xad\x47\xf3\x6f\xd9\xf7\xd0"
"\xd4\x2a\x4b\x5f\x11\x85\xcc\xdc\xf1\x6f\xf4\x62\x95\xd8\xa0\xfa\x17"
"\x71\x3c\x58\x02\x63\x09\x33\xa9\xa3\x4a\xf6\x74\xf3\xf3\x9f\xe2\x34"
"\x91\x23\x7c\x08\x82\x2d\xec\x11\x09\x11\xe8\x93\xd0\xa8\xc4\xf6\x77"
"\x74\x7a\xbc\x36\x09\x34\xb8\x29\x10\xff\x85\xbf\xd9\x95\x08\x3b\xba"
"\x29\x87\xa6\x73\x99\xea\xc4\x27\xd1\x45\xd5\x46\xa4\x0b\x9f\x6f\xf1"
"\x4a\xc4\x88\xec\x13\x0f\xb3\x85\x0a\x27\xaf\xc9\x53\x85\x4a\x64\x2c"
"\x57\x51\x95\x44\xae\x15\xa7\xe4\x54\xde\xa0\x59\x18\xb4\x12\x43\x51"
"\x60\x16\x11\xc8\xf1\x1b\xaa\x50\x0a\x36\x21\xc5\x6c\xea\x8d\x20\xff"
"\x91\x1a\x0c\x41\xdb\x6e\xbe\x8c\xac\x64\xf1\x76\x79\x14\x1d\x54\xb3"
"\x4b\xbc\x99\x63\xac\x4f\x4b\xb3\x30\x96\x03\xf1\xd4\xab\x96\x62\x03"
"\x86\x1b\x5b\x15\xa8\x41\xf2\xb5\x75\xa8\xbd\x0d\x78\x24\x8e\xbe\x4d"
"\x9a\x80\x00\x26\x95\x10\x4f\x67\x4c\x24\x31\xdc\xa1\x41\xfa\xe2\x69"
"\xca\xb7\x0e\x9a\x66\xf3\xc3\xa9\xa6\x3e\x96\x39\xe1\xf5\x9c\x0e\xde"
"\x26\xc6\xb5\xd7\x4b\x07\x8a\x5e\x15\xc3\x16\x34\xe5\xae\x09\x8c\xe9"
"\xee\x70\x77\x1a\xaa\x18\x11\x9a\x86\x7e\x10\x88\x33\x49\x75\xe9\xf7"
"\x34\x83\xb6\xa6\x2f\xa6\x78\xca\x14\xff\xd9\xf9\xdb\x2a\x78\x69\xd8"
"\x58\x64\x05\x65\x26\xf8\x89\xaf\x43\xa6\x05\x60\xa2\x2f\x1f\xca\x56"
"\x7e\x65\xd5\xe8\x80\x57\x22\x86\x52\x24\x49\xdf\x46\x6c\x63\x2b\x35"
"\x70\x24\x3f\x98\x9c\xce\x38\x03\xf4\x65\xe4\x1e\x61\x0c\x20\xd8\x04"
"\x21\xd6\x53\xa5\x12\x00\x00\x00\x82\x13\xb7\x04\xc7\xfb\x08\x2f\xf2"
"\x75\x90\x67\x8e\xf9\xf1\x90\xba\xe9\x79\xba\xbc\x70\x41\xd8\x60\x42"
"\x0c\x56\x64\xba\x79\x21\xb1\x4d\xc1\xdb\x88\x92\xfd\x32\xd0\xad\x7b"
"\xc9\x46\x81\x35\x91\xad\x8d\xef\xf4\xb0\x5f\x60\xce\xa0\xda\x77\x10"
"\xac\x00\x00\x00\x00\x00\x00\x80\x00\xbe\xa3\x7c\xe0\xd0\xd4\xaa\x20"
"\x2f\xef\x59\x52\xa5\x39\x1f\xd5\x61\x5d\x42\x9a\x04\xa6\x89\xb8\x3c"
"\x70\x68\xae\x94\x9e\xd0\x6e\x28\x8e\x81\x0b\xac\x9c\x76\x60\x00\x25"
"\xe1\x9c\x90\x7f\x8e\xa2\xe2\xf0\x5d\xd3\x31\x82\x71\xa1\xf5\xf8\x52"
"\x8f\x22\x7e\x79\xc1\x38\x8d\xbd\xff\xfe\x49\x2f\x21\x57\x9d\x2c\x15"
"\xb8\xc7\x0c\xdb\x1c\x33\x2d\x86\xd8\x73\x41\x43\x27\x50\x86\x1e\xc2"
"\xbc\x34\x51\xed\xca\x19\x4b\x22\x1c\xfe\xc4\x60\x3d\x27\x6b\xba\xa1"
"\xdf\xa6\xd4\xfb\x8a\x48\xa7\x6e\xef\xc9\xa9\xa0\x27\x0e\x4c\x10\xd6"
"\x4c\xd5\xa6\x24\x27\x26\x4f\x23\x77\xfe\x76\x3c\x43\x47\x08\x33\xac"
"\x96\xc4\x5f\x35\x7c\xbb\xab\xa8\xf1\xb1\xfd\xcc\x7c\xbb\x61\xa7\xcd"
"\xb9\x74\x4e\xd7\xf9\x12\x9a\xed\xe2\xbe\x21\xcc\xfd\xc4\xe9\x13\x4f"
"\x86\x84\xb3\xa4\xf3\x54\xda\x9a\x79\x5e\x96\x33\x4e\x20\x7d\xff\x70"
"\xf1\x98\x80\x37\xb2\xed\x3a\xaf\x57\x5c\x0b\x88\xd8\xf1\x46\x68\x40"
"\x78\x41\x6d\x59\xfd\xee\x53\x25\x92\x89\x74\xd1\x2d\xad\x99\xda\xc4"
"\x4c\x3f\x00\x08\x04\x70\x96\xa4\x40\x60\xbe\xbc\x24\x20\xae\xd9\x2f"
"\xa9\xb6\x57\x8b\x47\x79\x41\x5d\x97\xb9\xa6\xd6\xd5\x49\x5c\x11\x80"
"\x45\x65\x1c\xf4\x1c\x2f\xc4\x8b\x77\x8e\xfa\x5e\xa5\x67\x77\x47\x43"
"\x0a\xf4\x16\x2b\x98\x7b\x80\xc3\xe0\x01\xcd\x34\xe5\xc9\x2f\x76\xcc"
"\x4c\x24\xee\xb8\xbc\x4e\x9a\xc2\xae\xd9\xe5\x38\x03\xed\x0c\xa4\xae"
"\x3a\x97\x37\xd2\x14\x06\x00\x05\xea\x6f\x17\x83\xe2\x87\xb3\xbe\xe9"
"\x6e\x3a\x72\x88\xaf\xe2\xfd\xfa\xa7\x8d\x1f\x48\xc1\x3b\x64\xdf\x07"
"\x84\x77\x54\xb8\x40\x0d\xaa\xa6\x9b\xf5\xc8\xf4\x8f\xe4\xea\xe9\xca"
"\x12\x07\xe7\x82\x83\xcd\x0b\x20\xce\xb3\x60\xc7\xe6\x58\x82\x81\x63"
"\xe2\xd2\x5c\x4a\xa3\x48\x56\x1f\x92\x7e\x88\xf6\x3a\xa7\x0e\x73\xa5"
"\xe6\x9b\x3d\xf3\x49\x59\x03\xf0\x65\x72\xe1\xe0\x07\xfa\x55\xa2\x99"
"\x9f\x59\x6d\x06\x73\x12\xf5\x77\x9e\x8d\xbf\xdc\xf3\x42\x71\x38\xf3"
"\xd4\x44\xd2\x63\x9a\x10\x47\x7f\x9b\xec\x4b\x0b\xbb\x6e\x3c\x04\xbe"
"\x68\x98\x1f\x39\x22\x03\xdd\x0e\xe3\xef\x47\x8e\x67\xd1\xd7\x23\x2f"
"\x17\x69\x62\x94\x37\x8c\xe7\x16\xda\xcf\xc5\xe3\xe0\x3c\xf7\xab\x8e"
"\x39\x02\xf1\xb0\xff\x03\x4e\xf6\x55\xb2\x53\xca\x50\x93\x83\x81\x5b"
"\x1b\x6f\xc6\x52\x2d\x4e\x4f\xdc\x11\xa4\x8c\xf4\x2d\x48\x60\x46\x75"
"\xfd\xe2\xb9\x4c\xf0\x2b\x98\xa2\x69\xb8\x91\xab\xf8\xab\x9c\x01\x50"
"\x73\x01\x4d\x9e\x08\xd4\x33\x8b\x87\x80\xbd\xec\xd4\x36\xcf\x05\x41"
"\x35\x9b\xaf\xff\xa4\x52\x37\xf1\x04\xb9\x62\x10\x40\x3b\x2d\xe9\xef"
"\xed\xfd\x71\xaf\x94\x44\xe1\x97\xf4\x7e\x86\x61\x01\x49\x6f\x42\x35"
"\x5b\xc7\x87\x2c\x82\x74\x67\xcf\xa5\xc4\xe7\x27\x30\xd5\x6b\xd0\x68"
"\xed\x21\x1c\xf8\x47\x53\x5e\xde\xcb\x7b\x37\x3f\x78\xb0\x95\xb6\x84"
"\x41\xa3\x4c\xb5\x16\x82\xa8\xae\x4d\x24\xad\x04\x65\xf7\x92\x7f\x88"
"\x9b\x81\x30\x76\x03\x8e\x79\xa7\x96\x2f\xb3\x85\xa8\x82\xe8\x02\x0f"
"\x06\xc4\xc2\xba\x1d\xd5\xca\xc7\xc1\x88\x76\xda\x86\x5d\x25\x87\x34"
"\xdd\x73\x58\x3d\xf2\x92\x89\x24\x48\x03\x9e\xf7\x99\xcf\x06\x30\xbe"
"\xcd\xcc\xe0\x45\x79\xb5\x56\x1d\xc8\x25\xab\x82\x98\x27\x94\x5e\x02"
"\x0c\x1f\x67\xee\x61\x5f\x70\x84\xa6\x07\xa7\xec\xeb\x62\x43\x37\x8e"
"\x06\x10\x06\x0f\x02\xcc\xa4\x05\x1c\x2f\x00\x1e\xdb\x3d\x78\xfb\x4b"
"\x55\x66\x8d\xda\x93\xae\xc9\x2a\x5d\xe2\x03\x71\x7a\xa4\x9c\x2d\x28"
"\x4a\xcf\xab\xe2\x62\xfc\xcf\xcb\xb2\xb7\x5a\x21\x83\xc4\xe1\x5a\x7b"
"\x6e\xb6\x5c\xa8\x10\x4e\x1b\x4d\xa1\xfb\xb7\x7a\xb2\xfc\x04\x3a\xea"
"\xd8\x7c\x32\xab\x87\x5e\xe7\xc2\xe7\xb7\x01\x9c\x90\x2c\xd3\xb4\x3e"
"\xae\xb1\xa5\xfb\x13\x5c\x0c\x7d\xce\xe8\xfe\x65\x16\xa3\x28\x03\x2f"
"\x88\xc0\x42\x89\x18\x24\x65\x9e\x9e\x94\x26\x5c\x80\x3b\x35\xee\x5f"
"\x83\xa2\xb2\x10\x52\x01\x06\xb8\xa3\x58\xb5\x0a\xb7\xa1\xfa\x89\xaf"
"\x9c\x25\x1f\xe5\x29\x4b\x3d\x18\x02\xd5\x67\x6d\x95\xf1\x60\xec\x97"
"\xb1\xad\x94\x87\x41\xb2\x04\x46\x42\xc3\x7b\x4a\x6c\xc6\xc0\x4e\xff"
"\xc1\x67\x2d\xb7\xe4\xb6\x8d\x78\x7d\x9a\x7a\x48\x3b\xf2\xaa\x74\xfc"
"\x33\x57\xde\x50\xe8\xc7\x7d\x95\xa3\xd3\x61\xc0\x40\xba\xbb\x17\x16"
"\x07\xca\xac\x2a\x35\x59\xad\x4f\x75\x46\x5f\x49\xc0\xd0\xae\x37\x16"
"\xdb\x6e\x00\xcb\x11\xdb\x4a\x5f\xad\xe2\xa5\x7c\x10\x23\xbf\x70\xcc"
"\x77\x73\x7c\x3b\x42\xaa\xe5\x01\xb2\x0f\x76\x94\xa0\x0f\x16\xe2\xd0"
"\x17\x40\x35\xa2\xc2\x26\x56\xdc\x29\x88\x0a\xce\xbd\xbe\x8d\xdb\xd7"
"\x5c\x2f\x99\x8d\x8a\xc2\xdf\xad\x2b\xa3\xa5\x04\x76\x7b\x6b\x45\xa4"
"\x59\x57\xf2\x4d\x75\x8e\xd0\x24\xb3\x84\x9c\x11\xd4\x12\xa2\xa0\x3b"
"\x40\x47\x49\x70\x22\xd9\xc3\x0e\x23\xef\x4d\xf5\xc8\x96\x44\xf4\x8b"
"\xb5\x36\xf7\x94\x5b\x59\xd7\xbc\xdd\xff\x75\x44\x13\xd1\x35\x27\x3e"
"\xa8\xe7\x5f\x22\xf2\x16\xc6\xb9\x99\x0a\xe7\x18\x06\xf2\xc0\x0b\x40"
"\x25\xc4\x8b\x75\xc0\xf7\x3c\x49\x75\x79\x77\x37\x67\x07\x54\x28\x06"
"\x7e\x7f\x16\xf4\xdd\xe3\x74\xf8\x21\x1f\xef\x42\xcb\x46\x8e\x62\x3d"
"\xaf\x60\xb3\x56\x9d\x46\x2f\x4f\x19\xea\xcd\xb3\xed\x70\xee\xeb\xb4"
"\x48\x3f\x8f\xd7\x77\xd4\x43\xe8\xb4\x04\x26\xdb\x6f\xe2\x90\x68\xc0"
"\xca\x3d\x34\x14\x44\x2e\x86\x3a\x15\x47\x04\xb0\xe5\x1b\xc6\x64\xa1"
"\x37\xb2\x6b\xe7\x19\xf4\xf7\xc9\xa5\x67\x8a\x67\x4d\xfc\x95\xdf\x80"
"\xb9\xce\x37\x5d\xd6\x49\xc8\xc7\x04\xe5\x09\xbd\x88\xc8\xe6\x3d\x8c"
"\x7d\xd6\x70\x71\x11\x5c\x89\x82\xba\x46\xaf\x4d\x6a\xdc\xc9\xf6\x8a"
"\x75\xb9\x39\x7b\x03\x51\x53\xfa\xf4\x63\x66\xe7\x20\x5d\xd8\xd6\xf3"
"\x75\x25\xc1\xa0\xe9\x46\x10\xdd\x94\x32\x3f\x6c\x15\xd0\x85\x19\x71"
"\x49\xbf\xd6\x65\x55\x48\xcf\xd9\xc5\x2c\x97\x11\x93\x7f\x79\xab\xb1"
"\xa1\x24\xf1\x21\x04\x65\x48\x3c\xd3\xb2\xd7\x83\x78\xcf\xb8\x5e\xd8"
"\x2e\x7d\xa0\xf6\xeb\x6d\x27\x9f\x2a\xe4\x43\x69\xdd\xb4\x58\x1c\x55"
"\x92\x5d\x0f\x6f\x1b\xa4\x71\xeb\xa2\x81\xf2\x59\x15\x2f\x85\xa6\x54"
"\xfb\x39\xdd\xff\x3b\x48\x44\x39\xff\x15\x8e\x7c\x54\x19\xe0\x37\xf3"
"\xe3\xad\x03\x8f\x22\x11\xf1\x03\x31\x95\x56\x3c\x7f\x93\xcd\x54\xb9"
"\x09\x4f\x22\x6e\x78\x32\x71\xe1\xe5\xa2\xa2\xc1\x07\x12\xea\xb6\x25"
"\xd6\x49\x31\xcd\x4f\xfe\x67\x38\xd9\x7b\x9b\x5e\xf8\x28\xee\x9f\xb0"
"\x59\xfc\x01\xaf\x0e\x79\xc1\xe1\x4b\x1d\x25\x98\x8c\x69\xa3\x99\x73"
"\x13\x2f\x02\x76\x8f\x79\x71\xd3\x14\x88\xb8\x65\x8a\x20\x87\x8b\x7c"
"\x1d\xd7\xba\x02\xfc\x42\x93\x9d\xde\x3d\x4a\x33\x39\xa6\x5d\x50\x7d"
"\xc5\x9c\x51\x09\x7b\x40\x51\x77\x05\xda\x56\xe9\xeb\xf0\xaf\xa5\x32"
"\x82\xbf\x86\xdb\xb5\x8c\x54\x80\x69\xff\x6e\xb9\x5a\xad\xe7\xcc\x66"
"\xd7\xbb\xef\x72\x47\x79\xca\x1f\x73\x1b\x33\x46\xff\x17\x70\x50\x37"
"\x3d\x79\xff\x7b\x3e\x7f\x9b\xc0\xc1\xb4\xb2\x66\xa8\x87\x8b\x90\xba"
"\xaa\x03\x9d\x3e\x3b\x63\x97\x9a\xc3\xdf\x6e\x6f\x48\x59\xaf\xd5\x02"
"\x38\xc7\x54\x7a\x39\xb6\x08\x10\x93\x80\x44\xae\x18\x5d\x2b\xa3\xe0"
"\x0a\x4e\x73\x67\x68\x64\xae\x09\x0d\x81\xea\xee\x5e\xe6\xcf\x1d\x0a"
"\xb3\x78\xdd\x4d\xd8\x91\xe9\x37\xc2\xea\x54\x10\xe0\x51\x30\x93\x5e"
"\x00\x78\x5e\xc2\x7e\x92\x39\x11\xfa\xb9\x64\xc2\x71\x55\x65\x27\x69"
"\x7b\x52\x16\x06\x87\x46\x16\x02\xf8\x8d\xf1\x65\xd8\x84\xb3\x6e\xc2"
"\xb6\xc2\x5a\x2f\x33\xc7\x15\x68\x7e\x9d\xdb\xfb\x96\xd6\x86\x1a\xca"
"\x47\xda\x73\xd6\xf3\x14\x43\x45\xf4\x88\x43\xdd\x01\x4e\x5c\x5a\xd8"
"\xfe\x99\x57\x54\xbd\x9c\xf3\x2f\xce\x1e\x70\x27\x13\x2f\x20\x82\xfb"
"\x0a\x30\xb9\xde\xae\x84\xbe\xd4\xb2\x80\x45\x63\x40\x73\xc9\xc5\x8c"
"\x89\xd9\xe9\x9c\x81\x76\x91\x77\xc6\xd5\x94\xf8\x8a\x4f\xac\xfd\x4c"
"\x73\x5a\x20\x30\x7c\x73\x7a\xfa\xe5\x33\x66\x51\xb1\xb9\xbd\x52\x2d"
"\x60\x39\x94\x73\x29\x6b\x83\x1d\xbd\x93\x3d\x93\x99\x4b\xa3\x06\x42"
"\x79\xb1\x0e\xa0\xc5\x83\x3f\x41\xf1\x57\xea\x23\x02\x99\x3d\xbe\x43"
"\x3b\x1a\xa3\xa3\x76\x6d\x54\x39\x02\x04\x84\xf4\x11\x3c\x4c\x85\x94"
"\x65\xc3\xb4\x15\xc3\x43\x2f\x81\xdb\x87\x19\x53\x9d\x5b\xf3\x72\xaa"
"\xae\xa1\xcc\x43\xa6\xc5\xcb\xe5\x97\x58\xbf\xee\x29\x16\x58\x95\xac"
"\x4b\x00\x8e\x59\x5f\x43\x74\x91\xd8\x7a\xbe\xd0\x2c\xef\xcd\x9d\xb5"
"\x3d\x94\xd0\x2d\xae\x17\xb1\x18\xe5\xd6\x78\x74\x63\x18\x1f\x4b\x87"
"\xc1\x07\x72\xd2\xb1\x3f\x78\x09\x95\x9b\xc0\x48\x85\x06\x13\xd1\x7c"
"\xa5\x10\x55\xf2\xf4\x16\xa4\x4f\xe1\x80\xd2\xd5\x0c\x31\x2c\xca\x7c"
"\xb1\x4a\x2b\xdc\x33\x1f\x57\xa9\x81\x71\x39\xa2\x06\xfc\x76\xd5\x72"
"\x27\xff\xff\x2d\xe2\x0a\x4b\x8e\x37\x37\xfb\xb4\x29\x13\x77\x7c\x06"
"\x37\x6f\x79\x9e\xba\x36\x7e\x21\xf9\x4c\xa5\x98\x70\x5f\x5d\xcb\x76"
"\x7d\x6f\x84\xfa\xd6\xb0\xf6\x09\x5e\x53\xc4\xc4\x23\x4d\x0c\x1f\xbe"
"\x43\x4f\x6a\xb8\xf4\x3c\x00\x13\xee\x93\xb8\x39\x46\xee\x77\x59\xe8"
"\x9d\x7b\xdd\x1a\x32\xd7\xb3\x11\x0b\x93\x2a\x4d\x02\xda\x71\x1b\x75"
"\x7f\xe4\x3c\x06\xd2\x1e\x35\x81\x0d\x8f\xe9\x8b\x27\xfa\xea\x8a\xa1"
"\x2b\xc8\x71\x6e\xef\xc5\xc9\x7c\x45\xac\x33\xee\xec\x96\x4c\x52\x14"
"\xbc\x3a\x93\x59\xbd\xea\x1c\xcc\xab\x94\xf1\x5e\x36\x31\x9c\xb3\x4e"
"\xbc\xac\xed\xb8\x2c\x2e\xd3\xde\x5a\x8a\x8f\x00\x11\xe8\xf7\x4e\x82"
"\xd7\xf9\x60\x93\x53\x0e\x76\x69\x28\x39\xd7\x96\x19\x39\xad\xfd\xee"
"\xea\xff\x19\xd1\x1e\xfc\xaf\xb6\xd5\x46\xfe\xf2\x71\xe8\x9d\x6c\xc2"
"\x38\xa0\x81\xff\x58\xce\xfc\xce\x3f\xbf\x46\x25\xa7\xe7\xde\x40\xe4"
"\x2e\x07\xb3\x44\x49\xe1\x5e\x06\x5c\xc7\x34\x86\x63\xa5\x21\x90\x20"
"\x2c\x7a\xf2\x88\xa4\x51\x0d\xe0\x3d\xab\x19\xd2\x62\x85\xed\xa8\x91"
"\x56\xd5\x0d\xd3\x85\xa6\x03\x33\xba\x5b\xbf\x5d\x77\xcd\x70\x07\xad"
"\x15\x19\xad\x54\x70\xde\x3d\xd6\xd6\x08\x0c\xaf\xcc\xf8\xa9\x74\x06"
"\xbb\x6b\x68\xa1\xf0\xc4\x54\x98\x20\xa7\x3c\x88\x0f\x47\x5f\x73\x2a"
"\xe0\x03\x98\xe8\xbd\x1f\x49\x08\xb7\x80\x7f\xb3\x3b\x72\x68\x5e\xc3"
"\x7a\x2d\x3f\x76\x64\x13\xa6\x04\x59\x51\x62\x46\xe5\xa1\xd9\x98\xa2"
"\x01\x7a\xef\x09\x48\xa6\x8c\xb0\xb3\xe3\x5c\xb8\x0d\xd3\x49\xe8\x91"
"\xae\xf5\x95\xdc\x4d\x47\x0e\x8a\xc3\x2a\x30\x8e\x15\xfc\x37\xd0\x6a"
"\xea\xc2\x89\xc0\x52\x3f\x48\x3e\x1f\xf7\x40\x8c\x60\xed\xdd\xab\x65"
"\x2f\x2e\xf9\x1d\x4f\x2b\x01\x98\x7b\x0f\x46\xda\x03\x4e\x5c\x3f\x74"
"\x5a\x7e\xe8\x10\x1a\x39\x34\xc5\x4e\x24\xb4\x8e\xc0\x27\x5e\x2d\x06"
"\x87\xdc\x74\x6b\x08\x27\xcb\xf6\x52\xf4\x06\xc6\xb9\x5f\x27\x22\xe5"
"\x8c\x05\xf7\x52\xce\x21\x26\x59\x6e\x1c\xd7\x65\x5b\x90\x48\x01\x78"
"\x4c\x41\x6b\x22\xf7\x3d\x32\x46\x78\xe2\x72\x4f\x43\xf1\xfe\x68\x7c"
"\x7e\x8a\x60\xc2\x8b\x82\xb6\x52\x83\x41\xb6\x48\xcd\xd5\x6f\xed\x7c"
"\xdc\xbb\x15\x75\x91\x2d\x5e\xcd\x36\xde\xa3\xbc\xa0\xb7\x42\x7d\x83"
"\x92\xc6\x28\x94\x55\xe8\xf8\xd2\xab\x22\x42\x72\x92\x51\xae\x03\x3a"
"\x9e\x02\x21\x0e\x62\xdf\x05\x46\xa7\x4b\x33\x3a\x1c\x48\xf9\x5f\xd5"
"\x4a\xcb\x57\x41\x25\x9e\x8c\x54\x88\xef\xee\xe3\x27\x41\x5c\xc1\x94"
"\x51\x43\x2c\x6f\x14\xc2\x76\x93\x10\x2a\x3c\xd8\x48\x57\xcd\x65\x86"
"\xfc\x5c\xa9\xa9\x3e\xb0\x14\x5f\xac\x06\x62\xff\x86\x10\x7f\x99\x8a"
"\x8e\xf7\xdf\x8a\xa1\x40\x46\xc5\x5b\x03\xd3\xd4\x7f\x88\xa8\xd6\x0f"
"\x77\x74\xa2\xee\x08\x75\x88\x97\xfb\x41\x1a\x94\xb3\xc2\xfc\x5d\x5f"
"\x0d\xb4\x2c\x04\x56\xec\x01\x45\x08\xe5\x24\x7d\x33\xae\x6c\x96\x2d"
"\x35\x60\x3f\xf8\x45\x4c\x16\xf8\x34\x28\x56\x93\x51\x25\x10\x2b\xb7"
"\x84\xed\x71\x48\x87\x07\x1f\x3d\x99\x8e\xfd\xd9\x92\x3c\x95\x4a\xb6"
"\xce\x43\x1b\x63\xee\x35\x6b\x0c\x78\x5f\x2f\x47\xb9\x0e\x29\x38\x9f"
"\x22\xfc\x5b\x59\xa7\x0e\xfa\xea\x2b\xd4\x01\x95\xaf\x44\x86\x22\x0d"
"\x70\x2e\x30\xbf\xc4\x3c\x10\xec\x23\xea\x62\x83\x99\x4a\x7d\xde\x4d"
"\xcb\x61\xfe\xa6\xb6\x51\xfb\x1d\x62\x45\x8d\x07\x41\xa1\x28\x30\x05"
"\x2f\xcc\x46\x0d\xb0\x43\xaf\xe5\x25\x62\x9b\x40\xd7\xce\xe6\x58\xe4"
"\xcb\x5e\x93\x0e\xd6\x24\x80\x6c\x43\xa0\x06\xdc\x93\x36\xd0\x7c\x2b"
"\x80\x81\xc1\x28\xad\x27\x06\xf4\x82\x61\xf7\x89\x70\x84\xc2\x97\xa1"
"\xa6\x61\x3b\xc1\x8f\x5a\x38\xd4\x42\x76\x8a\xf3\x80\x41\xef\xe0\x3d"
"\x15\x2e\xf9\x5f\xf5\x69\xe7\x6d\xb2\x39\x1f\x45\x09\xd7\xf3\x39\xd9"
"\x2f\xdb\x4a\x89\x36\x49\x49\xda\x39\x32\xba\x5c\x04\xc2\x4a\x56\x0a"
"\xd8\x0a\x3c\xe6\x54\x57\x83\x76\xe5\x99\xaf\xf3\x56\x5b\x1d\x53\x1f"
"\x30\x91\x2b\x99\xe6\x61\x9e\xbe\x93\xcc\x0b\x81\xea\x99\x35\xfd\x46"
"\xed\xb4\x4a\x78\xf6\x15\x25\x54\x90\xa4\xb6\x21\x50\x1f\x2a\x9e\x4d"
"\x24\x62\x4c\x4d\xac\x92\x74\x11\x8c\x67\x58\x4f\x5d\x37\x47\x55\x53"
"\x4d\x7f\x68\xf6\x79\xc4\xff\x51\x6a\x9c\x86\x1a\x0e\x7e\x65\x86\x8f"
"\xcb\x2b\xf1\xcb\x9a\xea\x4e\x05\xdf\x72\x27\x9f\xdb\x0d\x2b\x9e\x93"
"\x5c\x5a\xf3\xcf\x47\x4b\xed\x79\xdf\xc2\x48\xc1\xf5\xae\xa4\xb8\xb3"
"\x2c\x5d\x29\x5e\x57\x07\x9d\x0f\xe6\x62\xa4\x6b\x7f\x71\xcd\x47\x74"
"\x4d\xb8\x6c\x50\xb7\x04\xc9\x71\xd9\x01\x95\xc7\xb2\xc7\x43\x9a\x2d"
"\x78\xcc\xfa\x79\xb5\xfc\x2b\xff\x6b\xbf\x84\x02\x62\xbf\x89\x39\x4b"
"\x3e\x64\x91\x95\x32\x64\xd2\x70\x0c\x83\x8f\xa2\xc7\xb3\x42\x52\x60"
"\x0c\x96\x54\xe5\x02\xdc\xea\x39\xcb\x6b\xc3\xeb\x69\x99\x2e\x23\x4b"
"\x4c\xa7\xdb\x2f\x45\x85\x8d\x62\x84\xca\x62\x70\xd6\xb2\xf0\xe5\x8f"
"\xde\xd8\xa7\xb4\xa3\x02\xa9\x7b\xc6\x41\xdf\x07\x72\x0b\xa2\xb2\x6b"
"\xbf\xcc\x80\x7c\xa0\xab\xb1\xb4\x43\x22\x26\x9c\x21\xc5\xec\x68\xcb"
"\x06\x8e\xa8\x80\x67\xd9\x05\xea\x91\x7b\xb0\x3e\xef\xda\xeb\xde\xab"
"\xf2\xd0\xdc\xe8\x09\x97\xc9\x15\xc8\x94\x9d\xe9\x92\x58\x7c\x2c\xb5"
"\xfe\x36\xd7\xd3\xe5\xdb\x21\xb0\x94\xb8\xb7\x79\x40\xb5\xf0\x77\x22"
"\xe4\x7a\x08\xd3\x67\xe5\xf8\x4c\x96\xec\x66\x4b\x72\x93\x4b\x99\xb3"
"\x10\x9a\xf6\x5d\x77\xe8\x6a\xbd\x68\x59\xcd\xdf\x4b\xba\xe1\xf0\x93"
"\x04\x62\xdf\x15\xfd\xdb\xc4\x85\x62\xea\x35\x11\xa8\x06\x5e\xf0\x28"
"\xcf\x12\xf1\x4d\xcf\x6e\xbe\xcd\x8d\x88\x48\x36\x17\x4f\xaf\x1a\xa6"
"\x09\xe5\xf1\xee\x11\x62\xdf\xa1\x3b\xdc\x1f\xa7\xcf\xaa\xdb\xa8\x5c"
"\x72\xe9\x75\x8f\x03\xa7\x55\xd0\xbe\x53\xf8\xd2\xa1\xdf\xb1\xc6\x8c"
"\xc1\x64\xb0\xa0\x78\x0d\x97\x1a\x96\xea\x2c\x4d\x4c\xa0\x39\x8c\x22"
"\x35\x98\x0a\x93\x07\xb3\xd5\xbd\x3b\x01\x0a\x3a\xd0\xa5\xdb\xed\x28"
"\x81\xa9\x70\x0a\xf5\x61\xac\x8c\x7e\x36\xbb\x2f\xc4\xc4\x0e\x9c\xf9"
"\x6f\x06\x81\x7f\xb9\x03\x72\x9a\x7d\xb6\xff\x95\x76\x97\xc9\xed\xe7"
"\x88\x5d\x94\xff\x1a\xa7\x08\x26\xad\x01\xa9\xb0\x3c\x37\xb0\x96\x9b"
"\xe0\xda\xf6\x0a\xf9\x31\x09\xeb\x1d\xee\x72\xe4\x36\x3f\x51\xaf\x62"
"\xaf\x6f\xb2\xa6\xdf\x3b\xec\x89\x82\x2a\x7a\x0b\x67\x80\x58\xfa\x3f"
"\xef\x86\xfa\xec\x21\x6e\xb6\x99\x21\x62\xf8\xdc\xbf\x71\x9c\x14\x8c"
"\xd2\xf9\xc5\x5f\x49\x01\x20\x3a\x9a\x8a\x2c\x3e\x90\xf3\x94\x3d\xbc"
"\x10\x36\x0a\x1a\x49\x70\x0d\x1d\xfb\xf6\x6d\x69\xf6\xfb\xaf\x50\x6c"
"\x8b\xcc\xe8\xbb\x0d\x87\x2a\x02\x23\x89\x26\x40\x7a\x4e\xdd\xd5\xd0"
"\xfc\x5a\x75\x2f\x90\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
4096));
NONFAILING(*(uint16_t*)0x20002444 = 0x1000);
syscall(__NR_write, (intptr_t)r[2], 0x20001440, 0x1006);
break;
}
}
int main(void)
{
syscall(__NR_mmap, 0x1ffff000, 0x1000, 0, 0x32, -1, 0);
syscall(__NR_mmap, 0x20000000, 0x1000000, 7, 0x32, -1, 0);
syscall(__NR_mmap, 0x21000000, 0x1000, 0, 0x32, -1, 0);
setup_binfmt_misc();
install_segv_handler();
use_temporary_dir();
do_sandbox_none();
return 0;
}
|
152271.c | /*
* Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
* From ASN.1 module "EUTRA-RRC-Definitions"
* found in "/home/user/openairinterface5g/openair2/RRC/LTE/MESSAGES/asn1c/ASN1_files/lte-rrc-14.7.0.asn1"
* `asn1c -pdu=all -fcompound-names -gen-PER -no-gen-OER -no-gen-example -D /home/user/openairinterface5g/cmake_targets/basic_simulator/enb/CMakeFiles/RRC_Rel14`
*/
#include "RRCConnectionResumeRequest-r13-IEs.h"
static int
memb_truncatedResumeID_r13_constraint_2(const asn_TYPE_descriptor_t *td, const void *sptr,
asn_app_constraint_failed_f *ctfailcb, void *app_key) {
const BIT_STRING_t *st = (const BIT_STRING_t *)sptr;
size_t size;
if(!sptr) {
ASN__CTFAIL(app_key, td, sptr,
"%s: value not given (%s:%d)",
td->name, __FILE__, __LINE__);
return -1;
}
if(st->size > 0) {
/* Size in bits */
size = 8 * st->size - (st->bits_unused & 0x07);
} else {
size = 0;
}
if((size == 24)) {
/* Constraint check succeeded */
return 0;
} else {
ASN__CTFAIL(app_key, td, sptr,
"%s: constraint failed (%s:%d)",
td->name, __FILE__, __LINE__);
return -1;
}
}
static int
memb_shortResumeMAC_I_r13_constraint_1(const asn_TYPE_descriptor_t *td, const void *sptr,
asn_app_constraint_failed_f *ctfailcb, void *app_key) {
const BIT_STRING_t *st = (const BIT_STRING_t *)sptr;
size_t size;
if(!sptr) {
ASN__CTFAIL(app_key, td, sptr,
"%s: value not given (%s:%d)",
td->name, __FILE__, __LINE__);
return -1;
}
if(st->size > 0) {
/* Size in bits */
size = 8 * st->size - (st->bits_unused & 0x07);
} else {
size = 0;
}
if((size == 16)) {
/* Constraint check succeeded */
return 0;
} else {
ASN__CTFAIL(app_key, td, sptr,
"%s: constraint failed (%s:%d)",
td->name, __FILE__, __LINE__);
return -1;
}
}
static int
memb_spare_constraint_1(const asn_TYPE_descriptor_t *td, const void *sptr,
asn_app_constraint_failed_f *ctfailcb, void *app_key) {
const BIT_STRING_t *st = (const BIT_STRING_t *)sptr;
size_t size;
if(!sptr) {
ASN__CTFAIL(app_key, td, sptr,
"%s: value not given (%s:%d)",
td->name, __FILE__, __LINE__);
return -1;
}
if(st->size > 0) {
/* Size in bits */
size = 8 * st->size - (st->bits_unused & 0x07);
} else {
size = 0;
}
if((size == 1)) {
/* Constraint check succeeded */
return 0;
} else {
ASN__CTFAIL(app_key, td, sptr,
"%s: constraint failed (%s:%d)",
td->name, __FILE__, __LINE__);
return -1;
}
}
static asn_per_constraints_t asn_PER_memb_truncatedResumeID_r13_constr_4 CC_NOTUSED = {
{ APC_UNCONSTRAINED, -1, -1, 0, 0 },
{ APC_CONSTRAINED, 0, 0, 24, 24 } /* (SIZE(24..24)) */,
0, 0 /* No PER value map */
};
static asn_per_constraints_t asn_PER_type_resumeIdentity_r13_constr_2 CC_NOTUSED = {
{ APC_CONSTRAINED, 1, 1, 0, 1 } /* (0..1) */,
{ APC_UNCONSTRAINED, -1, -1, 0, 0 },
0, 0 /* No PER value map */
};
static asn_per_constraints_t asn_PER_memb_shortResumeMAC_I_r13_constr_5 CC_NOTUSED = {
{ APC_UNCONSTRAINED, -1, -1, 0, 0 },
{ APC_CONSTRAINED, 0, 0, 16, 16 } /* (SIZE(16..16)) */,
0, 0 /* No PER value map */
};
static asn_per_constraints_t asn_PER_memb_spare_constr_7 CC_NOTUSED = {
{ APC_UNCONSTRAINED, -1, -1, 0, 0 },
{ APC_CONSTRAINED, 0, 0, 1, 1 } /* (SIZE(1..1)) */,
0, 0 /* No PER value map */
};
static asn_TYPE_member_t asn_MBR_resumeIdentity_r13_2[] = {
{ ATF_NOFLAGS, 0, offsetof(struct RRCConnectionResumeRequest_r13_IEs__resumeIdentity_r13, choice.resumeID_r13),
(ASN_TAG_CLASS_CONTEXT | (0 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_ResumeIdentity_r13,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"resumeID-r13"
},
{ ATF_NOFLAGS, 0, offsetof(struct RRCConnectionResumeRequest_r13_IEs__resumeIdentity_r13, choice.truncatedResumeID_r13),
(ASN_TAG_CLASS_CONTEXT | (1 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_BIT_STRING,
0,
{ 0, &asn_PER_memb_truncatedResumeID_r13_constr_4, memb_truncatedResumeID_r13_constraint_2 },
0, 0, /* No default value */
"truncatedResumeID-r13"
},
};
static const asn_TYPE_tag2member_t asn_MAP_resumeIdentity_r13_tag2el_2[] = {
{ (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* resumeID-r13 */
{ (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 } /* truncatedResumeID-r13 */
};
static asn_CHOICE_specifics_t asn_SPC_resumeIdentity_r13_specs_2 = {
sizeof(struct RRCConnectionResumeRequest_r13_IEs__resumeIdentity_r13),
offsetof(struct RRCConnectionResumeRequest_r13_IEs__resumeIdentity_r13, _asn_ctx),
offsetof(struct RRCConnectionResumeRequest_r13_IEs__resumeIdentity_r13, present),
sizeof(((struct RRCConnectionResumeRequest_r13_IEs__resumeIdentity_r13 *)0)->present),
asn_MAP_resumeIdentity_r13_tag2el_2,
2, /* Count of tags in the map */
0, 0,
-1 /* Extensions start */
};
static /* Use -fall-defs-global to expose */
asn_TYPE_descriptor_t asn_DEF_resumeIdentity_r13_2 = {
"resumeIdentity-r13",
"resumeIdentity-r13",
&asn_OP_CHOICE,
0, /* No effective tags (pointer) */
0, /* No effective tags (count) */
0, /* No tags (pointer) */
0, /* No tags (count) */
{ 0, &asn_PER_type_resumeIdentity_r13_constr_2, CHOICE_constraint },
asn_MBR_resumeIdentity_r13_2,
2, /* Elements count */
&asn_SPC_resumeIdentity_r13_specs_2 /* Additional specs */
};
asn_TYPE_member_t asn_MBR_RRCConnectionResumeRequest_r13_IEs_1[] = {
{ ATF_NOFLAGS, 0, offsetof(struct RRCConnectionResumeRequest_r13_IEs, resumeIdentity_r13),
(ASN_TAG_CLASS_CONTEXT | (0 << 2)),
+1, /* EXPLICIT tag at current level */
&asn_DEF_resumeIdentity_r13_2,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"resumeIdentity-r13"
},
{ ATF_NOFLAGS, 0, offsetof(struct RRCConnectionResumeRequest_r13_IEs, shortResumeMAC_I_r13),
(ASN_TAG_CLASS_CONTEXT | (1 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_BIT_STRING,
0,
{ 0, &asn_PER_memb_shortResumeMAC_I_r13_constr_5, memb_shortResumeMAC_I_r13_constraint_1 },
0, 0, /* No default value */
"shortResumeMAC-I-r13"
},
{ ATF_NOFLAGS, 0, offsetof(struct RRCConnectionResumeRequest_r13_IEs, resumeCause_r13),
(ASN_TAG_CLASS_CONTEXT | (2 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_ResumeCause,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
"resumeCause-r13"
},
{ ATF_NOFLAGS, 0, offsetof(struct RRCConnectionResumeRequest_r13_IEs, spare),
(ASN_TAG_CLASS_CONTEXT | (3 << 2)),
-1, /* IMPLICIT tag at current level */
&asn_DEF_BIT_STRING,
0,
{ 0, &asn_PER_memb_spare_constr_7, memb_spare_constraint_1 },
0, 0, /* No default value */
"spare"
},
};
static const ber_tlv_tag_t asn_DEF_RRCConnectionResumeRequest_r13_IEs_tags_1[] = {
(ASN_TAG_CLASS_UNIVERSAL | (16 << 2))
};
static const asn_TYPE_tag2member_t asn_MAP_RRCConnectionResumeRequest_r13_IEs_tag2el_1[] = {
{ (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* resumeIdentity-r13 */
{ (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 }, /* shortResumeMAC-I-r13 */
{ (ASN_TAG_CLASS_CONTEXT | (2 << 2)), 2, 0, 0 }, /* resumeCause-r13 */
{ (ASN_TAG_CLASS_CONTEXT | (3 << 2)), 3, 0, 0 } /* spare */
};
asn_SEQUENCE_specifics_t asn_SPC_RRCConnectionResumeRequest_r13_IEs_specs_1 = {
sizeof(struct RRCConnectionResumeRequest_r13_IEs),
offsetof(struct RRCConnectionResumeRequest_r13_IEs, _asn_ctx),
asn_MAP_RRCConnectionResumeRequest_r13_IEs_tag2el_1,
4, /* Count of tags in the map */
0, 0, 0, /* Optional elements (not needed) */
-1, /* First extension addition */
};
asn_TYPE_descriptor_t asn_DEF_RRCConnectionResumeRequest_r13_IEs = {
"RRCConnectionResumeRequest-r13-IEs",
"RRCConnectionResumeRequest-r13-IEs",
&asn_OP_SEQUENCE,
asn_DEF_RRCConnectionResumeRequest_r13_IEs_tags_1,
sizeof(asn_DEF_RRCConnectionResumeRequest_r13_IEs_tags_1)
/sizeof(asn_DEF_RRCConnectionResumeRequest_r13_IEs_tags_1[0]), /* 1 */
asn_DEF_RRCConnectionResumeRequest_r13_IEs_tags_1, /* Same as above */
sizeof(asn_DEF_RRCConnectionResumeRequest_r13_IEs_tags_1)
/sizeof(asn_DEF_RRCConnectionResumeRequest_r13_IEs_tags_1[0]), /* 1 */
{ 0, 0, SEQUENCE_constraint },
asn_MBR_RRCConnectionResumeRequest_r13_IEs_1,
4, /* Elements count */
&asn_SPC_RRCConnectionResumeRequest_r13_IEs_specs_1 /* Additional specs */
};
|
773249.c | /*************************************************************************************************/
/*!
* \file
*
* \brief Example Cycling Speed and Cadence Service Server implementation.
*
* Copyright (c) 2016-2018 Arm Ltd. All Rights Reserved.
* ARM Ltd. confidential and proprietary.
*
* IMPORTANT. Your use of this file is governed by a Software License Agreement
* ("Agreement") that must be accepted in order to download or otherwise receive a
* copy of this file. You may not use or copy this file for any purpose other than
* as described in the Agreement. If you do not agree to all of the terms of the
* Agreement do not use this file and delete all copies in your possession or control;
* if you do not have a copy of the Agreement, you must contact ARM Ltd. prior
* to any use, copying or further distribution of this software.
*/
/*************************************************************************************************/
#include "wsf_types.h"
#include "att_api.h"
#include "att_uuid.h"
#include "wsf_trace.h"
#include "util/bstream.h"
#include "svc_ch.h"
#include "svc_cscs.h"
#include "svc_cfg.h"
/**************************************************************************************************
Macros
**************************************************************************************************/
/*! Characteristic read permissions */
#ifndef CSCS_SEC_PERMIT_READ
#define CSCS_SEC_PERMIT_READ (ATTS_PERMIT_READ | ATTS_PERMIT_READ_ENC)
#endif
/*! Characteristic write permissions */
#ifndef CSCS_SEC_PERMIT_WRITE
#define CSCS_SEC_PERMIT_WRITE (ATTS_PERMIT_WRITE | ATTS_PERMIT_WRITE_ENC)
#endif
/**************************************************************************************************
Service variables
**************************************************************************************************/
/* Cycling Speed service declaration */
static const uint8_t cscsValSvc[] = {UINT16_TO_BYTES(ATT_UUID_CYCLING_SPEED_SERVICE)};
static const uint16_t cscsLenSvc = sizeof(cscsValSvc);
/* Cycling Speed Feature characteristic */
static const uint8_t cscsValFeatureCh[] = {ATT_PROP_READ, UINT16_TO_BYTES(CSCS_CSF_HDL), UINT16_TO_BYTES(ATT_UUID_CYCLING_SPEED_FEATURE)};
static const uint16_t cscsLenFeatureCh = sizeof(cscsValFeatureCh);
/* Cycling Speed Feature */
/* TODO: Set Supported Feature Bits */
static uint16_t cscsValFeature[] = {CSCS_WRDS_FEATURE_BIT};
static const uint16_t cscsLenFeature = sizeof(cscsValFeature);
/* Cycling Speed Measurement characteristic */
static const uint8_t cscsValMeasurementCh[] = {ATT_PROP_NOTIFY, UINT16_TO_BYTES(CSCS_CSM_HDL), UINT16_TO_BYTES(ATT_UUID_CYCLING_SPEED_MEASUREMENT)};
static const uint16_t cscsLenMeasurementCh = sizeof(cscsValMeasurementCh);
/* Cycling Speed Measurement */
/* Note these are dummy values */
static const uint8_t cscsValMeasurement[] = { 0 };
static const uint16_t cscsLenMeasurement = CH_CSCS_MEASUREMENT_LEN;
/* Cycling Speed Measurement client characteristic configuration */
static uint8_t cscsValMeasurementChCcc[] = {UINT16_TO_BYTES(0x0000) };
static const uint16_t cscsLenMeasurementChCcc = sizeof(cscsValMeasurementChCcc);
/* Cycling Speed Sensor Location characteristic */
static const uint8_t cscsValLocationCh[] = {ATT_PROP_READ, UINT16_TO_BYTES(CSCS_SL_HDL), UINT16_TO_BYTES(ATT_UUID_SENSOR_LOCATION)};
static const uint16_t cscsLenLocationCh = sizeof(cscsValLocationCh);
/* Cycling Speed Sensor Location */
/* Note these are dummy values */
static uint8_t cscsValLocation[] = { 0 };
static const uint16_t cscsLenLocation = sizeof(cscsValLocation);
/* Attribute list for CSCS group */
static const attsAttr_t cscsList[] =
{
/* Cycling Speed Service declaration */
{
attPrimSvcUuid,
(uint8_t *) cscsValSvc,
(uint16_t *) &cscsLenSvc,
sizeof(cscsValSvc),
0,
ATTS_PERMIT_READ
},
/* Cycling Speed Feature characteristic */
{
attChUuid,
(uint8_t *)cscsValFeatureCh,
(uint16_t *) &cscsLenFeatureCh,
sizeof(cscsValFeatureCh),
0,
ATTS_PERMIT_READ
},
/* Cycling Speed Feature value */
{
attCsfChUuid,
(uint8_t *)cscsValFeature,
(uint16_t *) &cscsLenFeature,
sizeof(cscsValFeature),
0,
CSCS_SEC_PERMIT_READ
},
/* Cycling Speed Measurement characteristic */
{
attChUuid,
(uint8_t *)cscsValMeasurementCh,
(uint16_t *)&cscsLenMeasurementCh,
sizeof(cscsValMeasurementCh),
0,
ATTS_PERMIT_READ
},
/* Cycling Speed Measurement value */
{
attCsmChUuid,
(uint8_t *)cscsValMeasurement,
(uint16_t *)&cscsLenMeasurement,
sizeof(cscsValMeasurement),
0,
0
},
/* Characteristic CCC descriptor */
{
attCliChCfgUuid,
cscsValMeasurementChCcc,
(uint16_t *)&cscsLenMeasurementChCcc,
sizeof(cscsValMeasurementChCcc),
ATTS_SET_CCC,
(ATTS_PERMIT_READ | CSCS_SEC_PERMIT_WRITE)
},
/* Cycling Speed Sensor Location characteristic */
{
attChUuid,
(uint8_t *)cscsValLocationCh,
(uint16_t *)&cscsLenLocationCh,
sizeof(cscsValLocationCh),
0,
ATTS_PERMIT_READ
},
/* Cycling Speed Sensor Location value */
{
attSlChUuid,
(uint8_t *)cscsValLocation,
(uint16_t *)&cscsLenLocation,
sizeof(cscsValLocation),
0,
CSCS_SEC_PERMIT_READ
},
};
/* CSCS group structure */
static attsGroup_t svcCscsGroup =
{
NULL,
(attsAttr_t *) cscsList,
NULL,
NULL,
CSCS_START_HDL,
CSCS_END_HDL
};
/*************************************************************************************************/
/*!
* \brief Add the services to the attribute server.
*
* \return None.
*/
/*************************************************************************************************/
void SvcCscsAddGroup(void)
{
AttsAddGroup(&svcCscsGroup);
}
/*************************************************************************************************/
/*!
* \brief Remove the services from the attribute server.
*
* \return None.
*/
/*************************************************************************************************/
void SvcCscsRemoveGroup(void)
{
AttsRemoveGroup(CSCS_START_HDL);
}
/*************************************************************************************************/
/*!
* \brief Register callbacks for the service.
*
* \param writeCback Write callback function.
*
* \return None.
*/
/*************************************************************************************************/
void SvcCscsCbackRegister(attsReadCback_t readCback, attsWriteCback_t writeCback)
{
svcCscsGroup.readCback = readCback;
svcCscsGroup.writeCback = writeCback;
}
|
881325.c | /* blas/dznrm2.f -- translated by f2c (version 20050501).
You must link the resulting object file with libf2c:
on Microsoft Windows system, link with libf2c.lib;
on Linux or Unix systems, link with .../path/to/libf2c.a -lm
or, if you install libf2c.a in a standard place, with -lf2c -lm
-- in that order, at the end of the command line, as in
cc *.o -lf2c -lm
Source for libf2c is in /netlib/f2c/libf2c.zip, e.g.,
http://www.netlib.org/f2c/libf2c.zip
*/
#ifdef __cplusplus
extern "C" {
#endif
#include "v3p_netlib.h"
/*< DOUBLE PRECISION FUNCTION DZNRM2( N, X, INCX ) >*/
doublereal dznrm2_(integer *n, doublecomplex *x, integer *incx)
{
/* System generated locals */
integer i__1, i__2, i__3;
doublereal ret_val, d__1;
/* Builtin functions */
double d_imag(doublecomplex *), sqrt(doublereal);
/* Local variables */
integer ix;
doublereal ssq, temp, norm, scale;
/* .. Scalar Arguments .. */
/*< INTEGER INCX, N >*/
/* .. Array Arguments .. */
/*< COMPLEX*16 X( * ) >*/
/* .. */
/* DZNRM2 returns the euclidean norm of a vector via the function */
/* name, so that */
/* DZNRM2 := sqrt( conjg( x' )*x ) */
/* -- This version written on 25-October-1982. */
/* Modified on 14-October-1993 to inline the call to ZLASSQ. */
/* Sven Hammarling, Nag Ltd. */
/* .. Parameters .. */
/*< DOUBLE PRECISION ONE , ZERO >*/
/*< PARAMETER ( ONE = 1.0D+0, ZERO = 0.0D+0 ) >*/
/* .. Local Scalars .. */
/*< INTEGER IX >*/
/*< DOUBLE PRECISION NORM, SCALE, SSQ, TEMP >*/
/* .. Intrinsic Functions .. */
/*< INTRINSIC ABS, DIMAG, DBLE, SQRT >*/
/* .. */
/* .. Executable Statements .. */
/*< IF( N.LT.1 .OR. INCX.LT.1 )THEN >*/
/* Parameter adjustments */
--x;
/* Function Body */
if (*n < 1 || *incx < 1) {
/*< NORM = ZERO >*/
norm = 0.;
/*< ELSE >*/
} else {
/*< SCALE = ZERO >*/
scale = 0.;
/*< SSQ = ONE >*/
ssq = 1.;
/* The following loop is equivalent to this call to the LAPACK */
/* auxiliary routine: */
/* CALL ZLASSQ( N, X, INCX, SCALE, SSQ ) */
/*< DO 10, IX = 1, 1 + ( N - 1 )*INCX, INCX >*/
i__1 = (*n - 1) * *incx + 1;
i__2 = *incx;
for (ix = 1; i__2 < 0 ? ix >= i__1 : ix <= i__1; ix += i__2) {
/*< IF( DBLE( X( IX ) ).NE.ZERO )THEN >*/
i__3 = ix;
if (x[i__3].r != 0.) {
/*< TEMP = ABS( DBLE( X( IX ) ) ) >*/
i__3 = ix;
temp = (d__1 = x[i__3].r, abs(d__1));
/*< IF( SCALE.LT.TEMP )THEN >*/
if (scale < temp) {
/*< SSQ = ONE + SSQ*( SCALE/TEMP )**2 >*/
/* Computing 2nd power */
d__1 = scale / temp;
ssq = ssq * (d__1 * d__1) + 1.;
/*< SCALE = TEMP >*/
scale = temp;
/*< ELSE >*/
} else {
/*< SSQ = SSQ + ( TEMP/SCALE )**2 >*/
/* Computing 2nd power */
d__1 = temp / scale;
ssq += d__1 * d__1;
/*< END IF >*/
}
/*< END IF >*/
}
/*< IF( DIMAG( X( IX ) ).NE.ZERO )THEN >*/
if (d_imag(&x[ix]) != 0.) {
/*< TEMP = ABS( DIMAG( X( IX ) ) ) >*/
temp = (d__1 = d_imag(&x[ix]), abs(d__1));
/*< IF( SCALE.LT.TEMP )THEN >*/
if (scale < temp) {
/*< SSQ = ONE + SSQ*( SCALE/TEMP )**2 >*/
/* Computing 2nd power */
d__1 = scale / temp;
ssq = ssq * (d__1 * d__1) + 1.;
/*< SCALE = TEMP >*/
scale = temp;
/*< ELSE >*/
} else {
/*< SSQ = SSQ + ( TEMP/SCALE )**2 >*/
/* Computing 2nd power */
d__1 = temp / scale;
ssq += d__1 * d__1;
/*< END IF >*/
}
/*< END IF >*/
}
/*< 10 CONTINUE >*/
/* L10: */
}
/*< NORM = SCALE * SQRT( SSQ ) >*/
norm = scale * sqrt(ssq);
/*< END IF >*/
}
/*< DZNRM2 = NORM >*/
ret_val = norm;
/*< RETURN >*/
return ret_val;
/* End of DZNRM2. */
/*< END >*/
} /* dznrm2_ */
#ifdef __cplusplus
}
#endif
|
792487.c | /*
Copyright (C) 2008 Joseph Jordan <[email protected]>
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1.The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in a
product, an acknowledgment in the product documentation would be
appreciated but is not required.
2.Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3.This notice may not be removed or altered from any source distribution.
*/
/****************************************************************************
* WiiUFtpServer
* 2021-12-05:Laf111:V7-0
***************************************************************************/
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <unistd.h>
#include <whb/log.h>
#include <whb/log_console.h>
#include <errno.h>
#include <sys/fcntl.h>
#include <nsysnet/_socket.h>
#include <coreinit/memdefaultheap.h>
#include <nn/ac.h>
#include "vrt.h"
#include "ftp.h"
#include "net.h"
#define SOCKET_MOPT_STACK_SIZE 0x2000
extern int somemopt (int req_type, char* mem, unsigned int memlen, int flags);
extern void display(const char *fmt, ...);
static uint32_t nbFilesDL = 0;
static uint32_t nbFilesUL = 0;
#ifdef LOG2FILE
extern void writeToLog(const char *fmt, ...);
#endif
static uint32_t hostIpAddress = 0;
static const int retriesNumber = (int) ((float)(NET_TIMEOUT) / ((float)NET_RETRY_TIME_STEP_MILLISECS/1000.0));
static OSThread *socketThread=NULL;
static OSThread socketOptThread;
static uint8_t *socketOptThreadStack=NULL;
static bool initDone = false;
int socketOptThreadMain(int argc UNUSED, const char **argv UNUSED)
{
void *buf = MEMAllocFromDefaultHeapEx(SOMEMOPT_BUFFER_SIZE, 64);
if (buf == NULL)
{
display("! ERROR : Socket optimizer: OUT OF MEMORY!");
return -ENOMEM;
}
if (somemopt(0x01, buf, SOMEMOPT_BUFFER_SIZE, 0) == -1 && errno != 50)
{if (!initDone) display("! ERROR : somemopt failed !");}
MEMFreeToDefaultHeap(buf);
return 0;
}
int socketThreadMain(int argc UNUSED, const char **argv UNUSED)
{
socketOptThreadStack = MEMAllocFromDefaultHeapEx(SOCKET_MOPT_STACK_SIZE, 8);
if (socketOptThreadStack == NULL || !OSCreateThread(&socketOptThread, socketOptThreadMain, 0, NULL, socketOptThreadStack + SOCKET_MOPT_STACK_SIZE, SOCKET_MOPT_STACK_SIZE, 0, OS_THREAD_ATTRIB_AFFINITY_CPU0))
return 1;
OSSetThreadName(&socketOptThread, "Socket memory optimizer thread");
OSResumeThread(&socketOptThread);
#ifdef LOG2FILE
writeToLog("network timeout = %d sec", NET_TIMEOUT);
writeToLog("network retries number = %d", retriesNumber);
#endif
return 0;
}
static bool retry(int32_t socketError) {
bool status = false;
// retry
if (socketError == -EINPROGRESS ||
socketError == -EALREADY ||
socketError == -EBUSY ||
socketError == -ETIME ||
socketError == -EISCONN) status = true;
#ifdef LOG2FILE
if (status) display("~ WARNING : Retrying transfer after = %d (%s)", socketError, strerror(socketError));
#endif
return status;
}
void initialize_network()
{
unsigned int nn_startupid;
ACInitialize();
ACGetStartupId(&nn_startupid);
ACConnectWithConfigId(nn_startupid);
ACGetAssignedAddress(&hostIpAddress);
// use default thread on Core 0
socketThread=OSGetDefaultThread(0);
if (socketThread == NULL) {
display("! ERROR : when getting socketThread!");
return;
}
if (!OSSetThreadPriority(socketThread, 0))
display("~ WARNING: Error changing net thread priority!");
OSSetThreadName(socketThread, "Network thread on CPU0");
OSRunThread(socketThread, socketThreadMain, 0, NULL);
OSResumeThread(socketThread);
#ifdef LOG2FILE
writeToLog("socketThreadMain ready");
#endif
int ret;
OSJoinThread(socketThread, &ret);
#ifdef LOG2FILE
writeToLog("socketThreadMain Launched");
#endif
}
void finalize_network()
{
display(" Files received : %d", nbFilesUL);
display(" Files sent : %d", nbFilesDL);
display("------------------------------------------------------------");
if (socketOptThreadStack != NULL) socket_lib_finish();
int ret;
OSJoinThread(&socketOptThread, &ret);
if (socketOptThreadStack != NULL) MEMFreeToDefaultHeap(socketOptThreadStack);
}
int32_t network_socket(uint32_t domain,uint32_t type,uint32_t protocol)
{
int sock = socket(domain, type, protocol);
if(sock < 0)
{
int err = -errno;
return (err < 0) ? err : sock;
}
if (type == SOCK_STREAM)
{
int enable = 1;
// Reuse socket
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable))!=0)
{if (!initDone) display("! ERROR : SO_REUSEADDR activation failed !");}
// Activate WinScale
if (setsockopt(sock, SOL_SOCKET, SO_WINSCALE, &enable, sizeof(enable))!=0)
{if (!initDone) display("! ERROR : WinScale activation failed !");}
// SO_NOSLOWSTART
if (setsockopt(sock, SOL_SOCKET, SO_NOSLOWSTART, &enable, sizeof(enable))!=0)
{if (!initDone) display("! ERROR : Disable slow start feature failed !");}
// socket memory optimization
int nbTries=0;
try_again_someopt:
if (setsockopt(sock, SOL_SOCKET, SO_RUSRBUF, &enable, sizeof(enable))!=0)
{
OSSleepTicks(OSMillisecondsToTicks(NET_RETRY_TIME_STEP_MILLISECS));
nbTries++;
if (nbTries <= retriesNumber) goto try_again_someopt;
else if (!initDone) display("! ERROR : Socket memory optimization failed !");
}
if (!initDone) {
initDone = true;
display(" 1 client only using a max of %d slots for up/download!", NB_SIMULTANEOUS_TRANSFERS);
display(" (set your client's timeout greater than %d seconds)", (NET_TIMEOUT+1)*NB_NET_TIME_OUT);
}
}
return sock;
}
int32_t network_bind(int32_t s,struct sockaddr *name,int32_t namelen)
{
int res = bind(s, name, namelen);
if (res < 0)
{
int err = -errno;
return (err < 0) ? err : res;
}
return res;
}
int32_t network_listen(int32_t s,uint32_t backlog)
{
int res = listen(s, backlog);
if (res < 0)
{
int err = -errno;
return (err < 0) ? err : res;
}
return res;
}
int32_t network_accept(int32_t s,struct sockaddr *addr,int32_t *addrlen)
{
socklen_t addrl=(socklen_t) *addrlen;
int res = accept(s, addr, &addrl);
if (res < 0)
{
int err = -errno;
return (err < 0) ? err : res;
}
return res;
}
int32_t network_connect(int32_t s,struct sockaddr *addr, int32_t addrlen)
{
int res = connect(s, addr, addrlen);
if (res < 0)
{
int err = -errno;
return (err < 0) ? err : res;
}
return res;
}
int32_t network_read(int32_t s,void *mem,int32_t len)
{
int res = recv(s, mem, len, 0);
if (res < 0)
{
int err = -errno;
return (err < 0) ? err : res;
}
return res;
}
uint32_t network_gethostip()
{
return hostIpAddress;
}
int32_t network_write(int32_t s, const void *mem, int32_t len)
{
int32_t transfered = 0;
while (len)
{
int ret = send(s, mem, len, 0);
if (ret < 0)
{
int err = -errno;
transfered = (err < 0) ? err : ret;
break;
}
mem += ret;
transfered += ret;
len -= ret;
}
return transfered;
}
int32_t network_close(int32_t s)
{
if (s < 0)
return -1;
return close(s);
}
int32_t set_blocking(int32_t s, bool blocking) {
int32_t block = !blocking;
setsockopt(s, SOL_SOCKET, SO_NONBLOCK, &block, sizeof(block));
return 0;
}
int32_t network_close_blocking(int32_t s) {
set_blocking(s, true);
return network_close(s);
}
int32_t send_exact(int32_t s, char *buf, int32_t length) {
int buf_size = length;
int32_t result = 0;
int32_t remaining = length;
int32_t bytes_transfered;
uint32_t retryNumber = 0;
while (remaining) {
retry:
// BLOCKING MODE
set_blocking(s, true);
bytes_transfered = network_write(s, buf, MIN(remaining, (int) buf_size));
set_blocking(s, false);
if (bytes_transfered > 0) {
remaining -= bytes_transfered;
buf += bytes_transfered;
} else if (bytes_transfered < 0) {
if (retry(bytes_transfered)) {
OSSleepTicks(OSMillisecondsToTicks(NET_RETRY_TIME_STEP_MILLISECS));
retryNumber++;
if (retryNumber <= retriesNumber) goto retry;
}
display("! ERROR : network_write failed = %d afer %d attempts", bytes_transfered, retriesNumber);
display("! ERROR : errno = %d (%s)", errno, strerror(errno));
result = bytes_transfered;
break;
} else {
// result = bytes_transfered = 0
result = bytes_transfered;
break;
}
}
return result;
}
static void setExtraSocketOptimizations(int32_t s)
{
int enable = 1;
// SO_OOBINLINE
if (setsockopt(s, SOL_SOCKET, SO_OOBINLINE, &enable, sizeof(enable))!=0)
{display("! ERROR : Force to leave received OOB data in line failed !");}
// TCP_NODELAY
if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &enable, sizeof(enable))!=0)
{display("! ERROR : Disable Nagle's algorithm failed !");}
// Deactivate TCP SAck
if (setsockopt(s, SOL_SOCKET, SO_TCPSACK, &enable, sizeof(enable))!=0)
{display("! ERROR : TCP SAck activation failed !");}
}
int32_t send_from_file(int32_t s, connection_t* connection) {
// return code
int32_t result = 0;
int buf_size = USER_BUFFER_SIZE;
if (connection->dataTransferOffset == 0) {
setExtraSocketOptimizations(s);
// max value for SNDBUF = SOMEMOPT_MIN_BUFFER_SIZE (the system double the value set)
int sockbuf_size = SOMEMOPT_MIN_BUFFER_SIZE;
if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, &sockbuf_size, sizeof(sockbuf_size))!=0)
{display("! ERROR : SNDBUF failed !");
}
}
int32_t bytes_read = buf_size;
bytes_read = fread(connection->userBuffer, 1, buf_size, connection->f);
if (bytes_read > 0) {
uint32_t retryNumber = 0;
int32_t remaining = bytes_read;
// to let buffer on file be larger than socket one
while (remaining) {
send_again:
// BLOCKING MODE
set_blocking(s, true);
result = network_write(s, connection->userBuffer, MIN(remaining, (int) bytes_read));
set_blocking(s, false);
if (result < 0) {
if (retry(result)) {
OSSleepTicks(OSMillisecondsToTicks(NET_RETRY_TIME_STEP_MILLISECS));
retryNumber++;
if (retryNumber <= retriesNumber) goto send_again;
}
display("! ERROR : network_write = %d afer %d attempts", result, retriesNumber);
display("! ERROR : errno = %d (%s)", errno, strerror(errno));
// result = error, connection will be closed
break;
} else {
// data block sent sucessfully, continue
connection->dataTransferOffset += result;
connection->bytesTransfered = result;
remaining -= result;
}
}
}
if (result >=0) {
// check bytes read (now because on the last sending, data is already sent here = result)
if (bytes_read < buf_size) {
if (bytes_read < 0 || feof(connection->f) == 0 || ferror(connection->f) != 0) {
// ERROR : not on eof file or read error, or error on stream => ERROR
display("! ERROR : failed to read file!");
display("! ERROR : fread = %d and bytes = %d", bytes_read, buf_size);
display("! ERROR : errno = %d (%s)", errno, strerror(errno));
result = -100;
}
}
// result = 0 and EOF
if ((feof(connection->f) != 0) && (result == 0)) {
// SUCESS : eof file, last data bloc sent
nbFilesDL++;
}
}
connection->bytesTransfered = result;
return result;
}
int32_t recv_to_file(int32_t s, connection_t* connection) {
// return code
int32_t result = 0;
int buf_size = USER_BUFFER_SIZE;
if (connection->dataTransferOffset == 0) {
// begin of a transfer, set socket buffer an extra opt
setExtraSocketOptimizations(s);
// (the system double the value set)
int sockbuf_size = buf_size/2;
if (setsockopt(s, SOL_SOCKET, SO_RCVBUF, &sockbuf_size, sizeof(sockbuf_size))!=0)
{display("! ERROR : RCVBUF failed !");}
}
uint32_t retryNumber = 0;
int32_t bytes_received = buf_size;
read_again:
// BLOCKING MODE
set_blocking(s, true);
bytes_received = network_read(s, connection->userBuffer, buf_size);
set_blocking(s, false);
if (bytes_received == 0) {
// SUCCESS, no more to write to file
nbFilesUL++;
result = 0;
} else if (bytes_received < 0 && bytes_received != -EAGAIN) {
if (retry(bytes_received)) {
OSSleepTicks(OSMillisecondsToTicks(NET_RETRY_TIME_STEP_MILLISECS));
retryNumber++;
if (retryNumber <= retriesNumber) goto read_again;
}
display("! ERROR : network_read failed = %d afer %d attempts", bytes_received, retriesNumber);
display("! ERROR : errno = %d (%s)", errno, strerror(errno));
// result = error, connection will be closed
result = bytes_received;
} else {
// bytes_received > 0
// write bytes_received to f
result = fwrite(connection->userBuffer, 1, bytes_received, connection->f);
if (result < 0 && result != -EAGAIN && result < bytes_received) {
// error when writing f
display("! ERROR : failed to write file!");
display("! ERROR : fwrite = %d and bytes=%d", result, bytes_received);
display("! ERROR : errno = %d (%s)", errno, strerror(errno));
result = -100;
} else {
connection->dataTransferOffset+=result;
connection->bytesTransfered = result;
}
}
connection->bytesTransfered = result;
return result;
} |
968616.c | /*******************************************************************************
* Filename: target_core_xcopy.c
*
* This file contains support for SPC-4 Extended-Copy offload with generic
* TCM backends.
*
* Copyright (c) 2011-2013 Datera, Inc. All rights reserved.
*
* Author:
* Nicholas A. Bellinger <[email protected]>
*
* 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/slab.h>
#include <linux/spinlock.h>
#include <linux/list.h>
#include <linux/configfs.h>
#include <scsi/scsi_proto.h>
#include <asm/unaligned.h>
#include <target/target_core_base.h>
#include <target/target_core_backend.h>
#include <target/target_core_fabric.h>
#include "target_core_internal.h"
#include "target_core_pr.h"
#include "target_core_ua.h"
#include "target_core_xcopy.h"
static struct workqueue_struct *xcopy_wq = NULL;
static int target_xcopy_gen_naa_ieee(struct se_device *dev, unsigned char *buf)
{
int off = 0;
buf[off++] = (0x6 << 4);
buf[off++] = 0x01;
buf[off++] = 0x40;
buf[off] = (0x5 << 4);
spc_parse_naa_6h_vendor_specific(dev, &buf[off]);
return 0;
}
static int target_xcopy_locate_se_dev_e4(struct se_cmd *se_cmd, struct xcopy_op *xop,
bool src)
{
struct se_device *se_dev;
unsigned char tmp_dev_wwn[XCOPY_NAA_IEEE_REGEX_LEN], *dev_wwn;
int rc;
if (src)
dev_wwn = &xop->dst_tid_wwn[0];
else
dev_wwn = &xop->src_tid_wwn[0];
mutex_lock(&g_device_mutex);
list_for_each_entry(se_dev, &g_device_list, g_dev_node) {
if (!se_dev->dev_attrib.emulate_3pc)
continue;
memset(&tmp_dev_wwn[0], 0, XCOPY_NAA_IEEE_REGEX_LEN);
target_xcopy_gen_naa_ieee(se_dev, &tmp_dev_wwn[0]);
rc = memcmp(&tmp_dev_wwn[0], dev_wwn, XCOPY_NAA_IEEE_REGEX_LEN);
if (rc != 0)
continue;
if (src) {
xop->dst_dev = se_dev;
pr_debug("XCOPY 0xe4: Setting xop->dst_dev: %p from located"
" se_dev\n", xop->dst_dev);
} else {
xop->src_dev = se_dev;
pr_debug("XCOPY 0xe4: Setting xop->src_dev: %p from located"
" se_dev\n", xop->src_dev);
}
rc = target_depend_item(&se_dev->dev_group.cg_item);
if (rc != 0) {
pr_err("configfs_depend_item attempt failed:"
" %d for se_dev: %p\n", rc, se_dev);
mutex_unlock(&g_device_mutex);
return rc;
}
pr_debug("Called configfs_depend_item for se_dev: %p"
" se_dev->se_dev_group: %p\n", se_dev,
&se_dev->dev_group);
mutex_unlock(&g_device_mutex);
return 0;
}
mutex_unlock(&g_device_mutex);
pr_debug_ratelimited("Unable to locate 0xe4 descriptor for EXTENDED_COPY\n");
return -EINVAL;
}
static int target_xcopy_parse_tiddesc_e4(struct se_cmd *se_cmd, struct xcopy_op *xop,
unsigned char *p, bool src)
{
unsigned char *desc = p;
unsigned short ript;
u8 desig_len;
/*
* Extract RELATIVE INITIATOR PORT IDENTIFIER
*/
ript = get_unaligned_be16(&desc[2]);
pr_debug("XCOPY 0xe4: RELATIVE INITIATOR PORT IDENTIFIER: %hu\n", ript);
/*
* Check for supported code set, association, and designator type
*/
if ((desc[4] & 0x0f) != 0x1) {
pr_err("XCOPY 0xe4: code set of non binary type not supported\n");
return -EINVAL;
}
if ((desc[5] & 0x30) != 0x00) {
pr_err("XCOPY 0xe4: association other than LUN not supported\n");
return -EINVAL;
}
if ((desc[5] & 0x0f) != 0x3) {
pr_err("XCOPY 0xe4: designator type unsupported: 0x%02x\n",
(desc[5] & 0x0f));
return -EINVAL;
}
/*
* Check for matching 16 byte length for NAA IEEE Registered Extended
* Assigned designator
*/
desig_len = desc[7];
if (desig_len != 16) {
pr_err("XCOPY 0xe4: invalid desig_len: %d\n", (int)desig_len);
return -EINVAL;
}
pr_debug("XCOPY 0xe4: desig_len: %d\n", (int)desig_len);
/*
* Check for NAA IEEE Registered Extended Assigned header..
*/
if ((desc[8] & 0xf0) != 0x60) {
pr_err("XCOPY 0xe4: Unsupported DESIGNATOR TYPE: 0x%02x\n",
(desc[8] & 0xf0));
return -EINVAL;
}
if (src) {
memcpy(&xop->src_tid_wwn[0], &desc[8], XCOPY_NAA_IEEE_REGEX_LEN);
/*
* Determine if the source designator matches the local device
*/
if (!memcmp(&xop->local_dev_wwn[0], &xop->src_tid_wwn[0],
XCOPY_NAA_IEEE_REGEX_LEN)) {
xop->op_origin = XCOL_SOURCE_RECV_OP;
xop->src_dev = se_cmd->se_dev;
pr_debug("XCOPY 0xe4: Set xop->src_dev %p from source"
" received xop\n", xop->src_dev);
}
} else {
memcpy(&xop->dst_tid_wwn[0], &desc[8], XCOPY_NAA_IEEE_REGEX_LEN);
/*
* Determine if the destination designator matches the local device
*/
if (!memcmp(&xop->local_dev_wwn[0], &xop->dst_tid_wwn[0],
XCOPY_NAA_IEEE_REGEX_LEN)) {
xop->op_origin = XCOL_DEST_RECV_OP;
xop->dst_dev = se_cmd->se_dev;
pr_debug("XCOPY 0xe4: Set xop->dst_dev: %p from destination"
" received xop\n", xop->dst_dev);
}
}
return 0;
}
static int target_xcopy_parse_target_descriptors(struct se_cmd *se_cmd,
struct xcopy_op *xop, unsigned char *p,
unsigned short tdll, sense_reason_t *sense_ret)
{
struct se_device *local_dev = se_cmd->se_dev;
unsigned char *desc = p;
int offset = tdll % XCOPY_TARGET_DESC_LEN, rc, ret = 0;
unsigned short start = 0;
bool src = true;
*sense_ret = TCM_INVALID_PARAMETER_LIST;
if (offset != 0) {
pr_err("XCOPY target descriptor list length is not"
" multiple of %d\n", XCOPY_TARGET_DESC_LEN);
return -EINVAL;
}
if (tdll > 64) {
pr_err("XCOPY target descriptor supports a maximum"
" two src/dest descriptors, tdll: %hu too large..\n", tdll);
return -EINVAL;
}
/*
* Generate an IEEE Registered Extended designator based upon the
* se_device the XCOPY was received upon..
*/
memset(&xop->local_dev_wwn[0], 0, XCOPY_NAA_IEEE_REGEX_LEN);
target_xcopy_gen_naa_ieee(local_dev, &xop->local_dev_wwn[0]);
while (start < tdll) {
/*
* Check target descriptor identification with 0xE4 type with
* use VPD 0x83 WWPN matching ..
*/
switch (desc[0]) {
case 0xe4:
rc = target_xcopy_parse_tiddesc_e4(se_cmd, xop,
&desc[0], src);
if (rc != 0)
goto out;
/*
* Assume target descriptors are in source -> destination order..
*/
if (src)
src = false;
else
src = true;
start += XCOPY_TARGET_DESC_LEN;
desc += XCOPY_TARGET_DESC_LEN;
ret++;
break;
default:
pr_err("XCOPY unsupported descriptor type code:"
" 0x%02x\n", desc[0]);
goto out;
}
}
if (xop->op_origin == XCOL_SOURCE_RECV_OP)
rc = target_xcopy_locate_se_dev_e4(se_cmd, xop, true);
else
rc = target_xcopy_locate_se_dev_e4(se_cmd, xop, false);
/*
* If a matching IEEE NAA 0x83 descriptor for the requested device
* is not located on this node, return COPY_ABORTED with ASQ/ASQC
* 0x0d/0x02 - COPY_TARGET_DEVICE_NOT_REACHABLE to request the
* initiator to fall back to normal copy method.
*/
if (rc < 0) {
*sense_ret = TCM_COPY_TARGET_DEVICE_NOT_REACHABLE;
goto out;
}
pr_debug("XCOPY TGT desc: Source dev: %p NAA IEEE WWN: 0x%16phN\n",
xop->src_dev, &xop->src_tid_wwn[0]);
pr_debug("XCOPY TGT desc: Dest dev: %p NAA IEEE WWN: 0x%16phN\n",
xop->dst_dev, &xop->dst_tid_wwn[0]);
return ret;
out:
return -EINVAL;
}
static int target_xcopy_parse_segdesc_02(struct se_cmd *se_cmd, struct xcopy_op *xop,
unsigned char *p)
{
unsigned char *desc = p;
int dc = (desc[1] & 0x02);
unsigned short desc_len;
desc_len = get_unaligned_be16(&desc[2]);
if (desc_len != 0x18) {
pr_err("XCOPY segment desc 0x02: Illegal desc_len:"
" %hu\n", desc_len);
return -EINVAL;
}
xop->stdi = get_unaligned_be16(&desc[4]);
xop->dtdi = get_unaligned_be16(&desc[6]);
pr_debug("XCOPY seg desc 0x02: desc_len: %hu stdi: %hu dtdi: %hu, DC: %d\n",
desc_len, xop->stdi, xop->dtdi, dc);
xop->nolb = get_unaligned_be16(&desc[10]);
xop->src_lba = get_unaligned_be64(&desc[12]);
xop->dst_lba = get_unaligned_be64(&desc[20]);
pr_debug("XCOPY seg desc 0x02: nolb: %hu src_lba: %llu dst_lba: %llu\n",
xop->nolb, (unsigned long long)xop->src_lba,
(unsigned long long)xop->dst_lba);
if (dc != 0) {
xop->dbl = (desc[29] & 0xff) << 16;
xop->dbl |= (desc[30] & 0xff) << 8;
xop->dbl |= desc[31] & 0xff;
pr_debug("XCOPY seg desc 0x02: DC=1 w/ dbl: %u\n", xop->dbl);
}
return 0;
}
static int target_xcopy_parse_segment_descriptors(struct se_cmd *se_cmd,
struct xcopy_op *xop, unsigned char *p,
unsigned int sdll)
{
unsigned char *desc = p;
unsigned int start = 0;
int offset = sdll % XCOPY_SEGMENT_DESC_LEN, rc, ret = 0;
if (offset != 0) {
pr_err("XCOPY segment descriptor list length is not"
" multiple of %d\n", XCOPY_SEGMENT_DESC_LEN);
return -EINVAL;
}
while (start < sdll) {
/*
* Check segment descriptor type code for block -> block
*/
switch (desc[0]) {
case 0x02:
rc = target_xcopy_parse_segdesc_02(se_cmd, xop, desc);
if (rc < 0)
goto out;
ret++;
start += XCOPY_SEGMENT_DESC_LEN;
desc += XCOPY_SEGMENT_DESC_LEN;
break;
default:
pr_err("XCOPY unsupported segment descriptor"
"type: 0x%02x\n", desc[0]);
goto out;
}
}
return ret;
out:
return -EINVAL;
}
/*
* Start xcopy_pt ops
*/
struct xcopy_pt_cmd {
bool remote_port;
struct se_cmd se_cmd;
struct xcopy_op *xcopy_op;
struct completion xpt_passthrough_sem;
unsigned char sense_buffer[TRANSPORT_SENSE_BUFFER];
};
struct se_portal_group xcopy_pt_tpg;
static struct se_session xcopy_pt_sess;
static struct se_node_acl xcopy_pt_nacl;
static char *xcopy_pt_get_fabric_name(void)
{
return "xcopy-pt";
}
static int xcopy_pt_get_cmd_state(struct se_cmd *se_cmd)
{
return 0;
}
static void xcopy_pt_undepend_remotedev(struct xcopy_op *xop)
{
struct se_device *remote_dev;
if (xop->op_origin == XCOL_SOURCE_RECV_OP)
remote_dev = xop->dst_dev;
else
remote_dev = xop->src_dev;
pr_debug("Calling configfs_undepend_item for"
" remote_dev: %p remote_dev->dev_group: %p\n",
remote_dev, &remote_dev->dev_group.cg_item);
target_undepend_item(&remote_dev->dev_group.cg_item);
}
static void xcopy_pt_release_cmd(struct se_cmd *se_cmd)
{
struct xcopy_pt_cmd *xpt_cmd = container_of(se_cmd,
struct xcopy_pt_cmd, se_cmd);
kfree(xpt_cmd);
}
static int xcopy_pt_check_stop_free(struct se_cmd *se_cmd)
{
struct xcopy_pt_cmd *xpt_cmd = container_of(se_cmd,
struct xcopy_pt_cmd, se_cmd);
complete(&xpt_cmd->xpt_passthrough_sem);
return 0;
}
static int xcopy_pt_write_pending(struct se_cmd *se_cmd)
{
return 0;
}
static int xcopy_pt_write_pending_status(struct se_cmd *se_cmd)
{
return 0;
}
static int xcopy_pt_queue_data_in(struct se_cmd *se_cmd)
{
return 0;
}
static int xcopy_pt_queue_status(struct se_cmd *se_cmd)
{
return 0;
}
static const struct target_core_fabric_ops xcopy_pt_tfo = {
.get_fabric_name = xcopy_pt_get_fabric_name,
.get_cmd_state = xcopy_pt_get_cmd_state,
.release_cmd = xcopy_pt_release_cmd,
.check_stop_free = xcopy_pt_check_stop_free,
.write_pending = xcopy_pt_write_pending,
.write_pending_status = xcopy_pt_write_pending_status,
.queue_data_in = xcopy_pt_queue_data_in,
.queue_status = xcopy_pt_queue_status,
};
/*
* End xcopy_pt_ops
*/
int target_xcopy_setup_pt(void)
{
xcopy_wq = alloc_workqueue("xcopy_wq", WQ_MEM_RECLAIM, 0);
if (!xcopy_wq) {
pr_err("Unable to allocate xcopy_wq\n");
return -ENOMEM;
}
memset(&xcopy_pt_tpg, 0, sizeof(struct se_portal_group));
INIT_LIST_HEAD(&xcopy_pt_tpg.se_tpg_node);
INIT_LIST_HEAD(&xcopy_pt_tpg.acl_node_list);
INIT_LIST_HEAD(&xcopy_pt_tpg.tpg_sess_list);
xcopy_pt_tpg.se_tpg_tfo = &xcopy_pt_tfo;
memset(&xcopy_pt_nacl, 0, sizeof(struct se_node_acl));
INIT_LIST_HEAD(&xcopy_pt_nacl.acl_list);
INIT_LIST_HEAD(&xcopy_pt_nacl.acl_sess_list);
memset(&xcopy_pt_sess, 0, sizeof(struct se_session));
INIT_LIST_HEAD(&xcopy_pt_sess.sess_list);
INIT_LIST_HEAD(&xcopy_pt_sess.sess_acl_list);
INIT_LIST_HEAD(&xcopy_pt_sess.sess_cmd_list);
spin_lock_init(&xcopy_pt_sess.sess_cmd_lock);
xcopy_pt_nacl.se_tpg = &xcopy_pt_tpg;
xcopy_pt_nacl.nacl_sess = &xcopy_pt_sess;
xcopy_pt_sess.se_tpg = &xcopy_pt_tpg;
xcopy_pt_sess.se_node_acl = &xcopy_pt_nacl;
return 0;
}
void target_xcopy_release_pt(void)
{
if (xcopy_wq)
destroy_workqueue(xcopy_wq);
}
static void target_xcopy_setup_pt_port(
struct xcopy_pt_cmd *xpt_cmd,
struct xcopy_op *xop,
bool remote_port)
{
struct se_cmd *ec_cmd = xop->xop_se_cmd;
struct se_cmd *pt_cmd = &xpt_cmd->se_cmd;
if (xop->op_origin == XCOL_SOURCE_RECV_OP) {
/*
* Honor destination port reservations for X-COPY PUSH emulation
* when CDB is received on local source port, and READs blocks to
* WRITE on remote destination port.
*/
if (remote_port) {
xpt_cmd->remote_port = remote_port;
} else {
pt_cmd->se_lun = ec_cmd->se_lun;
pt_cmd->se_dev = ec_cmd->se_dev;
pr_debug("Honoring local SRC port from ec_cmd->se_dev:"
" %p\n", pt_cmd->se_dev);
pt_cmd->se_lun = ec_cmd->se_lun;
pr_debug("Honoring local SRC port from ec_cmd->se_lun: %p\n",
pt_cmd->se_lun);
}
} else {
/*
* Honor source port reservation for X-COPY PULL emulation
* when CDB is received on local desintation port, and READs
* blocks from the remote source port to WRITE on local
* destination port.
*/
if (remote_port) {
xpt_cmd->remote_port = remote_port;
} else {
pt_cmd->se_lun = ec_cmd->se_lun;
pt_cmd->se_dev = ec_cmd->se_dev;
pr_debug("Honoring local DST port from ec_cmd->se_dev:"
" %p\n", pt_cmd->se_dev);
pt_cmd->se_lun = ec_cmd->se_lun;
pr_debug("Honoring local DST port from ec_cmd->se_lun: %p\n",
pt_cmd->se_lun);
}
}
}
static void target_xcopy_init_pt_lun(struct se_device *se_dev,
struct se_cmd *pt_cmd, bool remote_port)
{
/*
* Don't allocate + init an pt_cmd->se_lun if honoring local port for
* reservations. The pt_cmd->se_lun pointer will be setup from within
* target_xcopy_setup_pt_port()
*/
if (remote_port) {
pr_debug("Setup emulated se_dev: %p from se_dev\n",
pt_cmd->se_dev);
pt_cmd->se_lun = &se_dev->xcopy_lun;
pt_cmd->se_dev = se_dev;
}
pt_cmd->se_cmd_flags |= SCF_SE_LUN_CMD;
}
static int target_xcopy_setup_pt_cmd(
struct xcopy_pt_cmd *xpt_cmd,
struct xcopy_op *xop,
struct se_device *se_dev,
unsigned char *cdb,
bool remote_port,
bool alloc_mem)
{
struct se_cmd *cmd = &xpt_cmd->se_cmd;
sense_reason_t sense_rc;
int ret = 0, rc;
/*
* Setup LUN+port to honor reservations based upon xop->op_origin for
* X-COPY PUSH or X-COPY PULL based upon where the CDB was received.
*/
target_xcopy_init_pt_lun(se_dev, cmd, remote_port);
xpt_cmd->xcopy_op = xop;
target_xcopy_setup_pt_port(xpt_cmd, xop, remote_port);
cmd->tag = 0;
sense_rc = target_setup_cmd_from_cdb(cmd, cdb);
if (sense_rc) {
ret = -EINVAL;
goto out;
}
if (alloc_mem) {
rc = target_alloc_sgl(&cmd->t_data_sg, &cmd->t_data_nents,
cmd->data_length, false, false);
if (rc < 0) {
ret = rc;
goto out;
}
/*
* Set this bit so that transport_free_pages() allows the
* caller to release SGLs + physical memory allocated by
* transport_generic_get_mem()..
*/
cmd->se_cmd_flags |= SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC;
} else {
/*
* Here the previously allocated SGLs for the internal READ
* are mapped zero-copy to the internal WRITE.
*/
sense_rc = transport_generic_map_mem_to_cmd(cmd,
xop->xop_data_sg, xop->xop_data_nents,
NULL, 0);
if (sense_rc) {
ret = -EINVAL;
goto out;
}
pr_debug("Setup PASSTHROUGH_NOALLOC t_data_sg: %p t_data_nents:"
" %u\n", cmd->t_data_sg, cmd->t_data_nents);
}
return 0;
out:
return ret;
}
static int target_xcopy_issue_pt_cmd(struct xcopy_pt_cmd *xpt_cmd)
{
struct se_cmd *se_cmd = &xpt_cmd->se_cmd;
sense_reason_t sense_rc;
sense_rc = transport_generic_new_cmd(se_cmd);
if (sense_rc)
return -EINVAL;
if (se_cmd->data_direction == DMA_TO_DEVICE)
target_execute_cmd(se_cmd);
wait_for_completion_interruptible(&xpt_cmd->xpt_passthrough_sem);
pr_debug("target_xcopy_issue_pt_cmd(): SCSI status: 0x%02x\n",
se_cmd->scsi_status);
return (se_cmd->scsi_status) ? -EINVAL : 0;
}
static int target_xcopy_read_source(
struct se_cmd *ec_cmd,
struct xcopy_op *xop,
struct se_device *src_dev,
sector_t src_lba,
u32 src_sectors)
{
struct xcopy_pt_cmd *xpt_cmd;
struct se_cmd *se_cmd;
u32 length = (src_sectors * src_dev->dev_attrib.block_size);
int rc;
unsigned char cdb[16];
bool remote_port = (xop->op_origin == XCOL_DEST_RECV_OP);
xpt_cmd = kzalloc(sizeof(struct xcopy_pt_cmd), GFP_KERNEL);
if (!xpt_cmd) {
pr_err("Unable to allocate xcopy_pt_cmd\n");
return -ENOMEM;
}
init_completion(&xpt_cmd->xpt_passthrough_sem);
se_cmd = &xpt_cmd->se_cmd;
memset(&cdb[0], 0, 16);
cdb[0] = READ_16;
put_unaligned_be64(src_lba, &cdb[2]);
put_unaligned_be32(src_sectors, &cdb[10]);
pr_debug("XCOPY: Built READ_16: LBA: %llu Sectors: %u Length: %u\n",
(unsigned long long)src_lba, src_sectors, length);
transport_init_se_cmd(se_cmd, &xcopy_pt_tfo, &xcopy_pt_sess, length,
DMA_FROM_DEVICE, 0, &xpt_cmd->sense_buffer[0]);
xop->src_pt_cmd = xpt_cmd;
rc = target_xcopy_setup_pt_cmd(xpt_cmd, xop, src_dev, &cdb[0],
remote_port, true);
if (rc < 0) {
ec_cmd->scsi_status = xpt_cmd->se_cmd.scsi_status;
transport_generic_free_cmd(se_cmd, 0);
return rc;
}
xop->xop_data_sg = se_cmd->t_data_sg;
xop->xop_data_nents = se_cmd->t_data_nents;
pr_debug("XCOPY-READ: Saved xop->xop_data_sg: %p, num: %u for READ"
" memory\n", xop->xop_data_sg, xop->xop_data_nents);
rc = target_xcopy_issue_pt_cmd(xpt_cmd);
if (rc < 0) {
ec_cmd->scsi_status = xpt_cmd->se_cmd.scsi_status;
transport_generic_free_cmd(se_cmd, 0);
return rc;
}
/*
* Clear off the allocated t_data_sg, that has been saved for
* zero-copy WRITE submission reuse in struct xcopy_op..
*/
se_cmd->t_data_sg = NULL;
se_cmd->t_data_nents = 0;
return 0;
}
static int target_xcopy_write_destination(
struct se_cmd *ec_cmd,
struct xcopy_op *xop,
struct se_device *dst_dev,
sector_t dst_lba,
u32 dst_sectors)
{
struct xcopy_pt_cmd *xpt_cmd;
struct se_cmd *se_cmd;
u32 length = (dst_sectors * dst_dev->dev_attrib.block_size);
int rc;
unsigned char cdb[16];
bool remote_port = (xop->op_origin == XCOL_SOURCE_RECV_OP);
xpt_cmd = kzalloc(sizeof(struct xcopy_pt_cmd), GFP_KERNEL);
if (!xpt_cmd) {
pr_err("Unable to allocate xcopy_pt_cmd\n");
return -ENOMEM;
}
init_completion(&xpt_cmd->xpt_passthrough_sem);
se_cmd = &xpt_cmd->se_cmd;
memset(&cdb[0], 0, 16);
cdb[0] = WRITE_16;
put_unaligned_be64(dst_lba, &cdb[2]);
put_unaligned_be32(dst_sectors, &cdb[10]);
pr_debug("XCOPY: Built WRITE_16: LBA: %llu Sectors: %u Length: %u\n",
(unsigned long long)dst_lba, dst_sectors, length);
transport_init_se_cmd(se_cmd, &xcopy_pt_tfo, &xcopy_pt_sess, length,
DMA_TO_DEVICE, 0, &xpt_cmd->sense_buffer[0]);
xop->dst_pt_cmd = xpt_cmd;
rc = target_xcopy_setup_pt_cmd(xpt_cmd, xop, dst_dev, &cdb[0],
remote_port, false);
if (rc < 0) {
struct se_cmd *src_cmd = &xop->src_pt_cmd->se_cmd;
ec_cmd->scsi_status = xpt_cmd->se_cmd.scsi_status;
/*
* If the failure happened before the t_mem_list hand-off in
* target_xcopy_setup_pt_cmd(), Reset memory + clear flag so that
* core releases this memory on error during X-COPY WRITE I/O.
*/
src_cmd->se_cmd_flags &= ~SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC;
src_cmd->t_data_sg = xop->xop_data_sg;
src_cmd->t_data_nents = xop->xop_data_nents;
transport_generic_free_cmd(se_cmd, 0);
return rc;
}
rc = target_xcopy_issue_pt_cmd(xpt_cmd);
if (rc < 0) {
ec_cmd->scsi_status = xpt_cmd->se_cmd.scsi_status;
se_cmd->se_cmd_flags &= ~SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC;
transport_generic_free_cmd(se_cmd, 0);
return rc;
}
return 0;
}
static void target_xcopy_do_work(struct work_struct *work)
{
struct xcopy_op *xop = container_of(work, struct xcopy_op, xop_work);
struct se_device *src_dev = xop->src_dev, *dst_dev = xop->dst_dev;
struct se_cmd *ec_cmd = xop->xop_se_cmd;
sector_t src_lba = xop->src_lba, dst_lba = xop->dst_lba, end_lba;
unsigned int max_sectors;
int rc;
unsigned short nolb = xop->nolb, cur_nolb, max_nolb, copied_nolb = 0;
end_lba = src_lba + nolb;
/*
* Break up XCOPY I/O into hw_max_sectors sized I/O based on the
* smallest max_sectors between src_dev + dev_dev, or
*/
max_sectors = min(src_dev->dev_attrib.hw_max_sectors,
dst_dev->dev_attrib.hw_max_sectors);
max_sectors = min_t(u32, max_sectors, XCOPY_MAX_SECTORS);
max_nolb = min_t(u16, max_sectors, ((u16)(~0U)));
pr_debug("target_xcopy_do_work: nolb: %hu, max_nolb: %hu end_lba: %llu\n",
nolb, max_nolb, (unsigned long long)end_lba);
pr_debug("target_xcopy_do_work: Starting src_lba: %llu, dst_lba: %llu\n",
(unsigned long long)src_lba, (unsigned long long)dst_lba);
while (src_lba < end_lba) {
cur_nolb = min(nolb, max_nolb);
pr_debug("target_xcopy_do_work: Calling read src_dev: %p src_lba: %llu,"
" cur_nolb: %hu\n", src_dev, (unsigned long long)src_lba, cur_nolb);
rc = target_xcopy_read_source(ec_cmd, xop, src_dev, src_lba, cur_nolb);
if (rc < 0)
goto out;
src_lba += cur_nolb;
pr_debug("target_xcopy_do_work: Incremented READ src_lba to %llu\n",
(unsigned long long)src_lba);
pr_debug("target_xcopy_do_work: Calling write dst_dev: %p dst_lba: %llu,"
" cur_nolb: %hu\n", dst_dev, (unsigned long long)dst_lba, cur_nolb);
rc = target_xcopy_write_destination(ec_cmd, xop, dst_dev,
dst_lba, cur_nolb);
if (rc < 0) {
transport_generic_free_cmd(&xop->src_pt_cmd->se_cmd, 0);
goto out;
}
dst_lba += cur_nolb;
pr_debug("target_xcopy_do_work: Incremented WRITE dst_lba to %llu\n",
(unsigned long long)dst_lba);
copied_nolb += cur_nolb;
nolb -= cur_nolb;
transport_generic_free_cmd(&xop->src_pt_cmd->se_cmd, 0);
xop->dst_pt_cmd->se_cmd.se_cmd_flags &= ~SCF_PASSTHROUGH_SG_TO_MEM_NOALLOC;
transport_generic_free_cmd(&xop->dst_pt_cmd->se_cmd, 0);
}
xcopy_pt_undepend_remotedev(xop);
kfree(xop);
pr_debug("target_xcopy_do_work: Final src_lba: %llu, dst_lba: %llu\n",
(unsigned long long)src_lba, (unsigned long long)dst_lba);
pr_debug("target_xcopy_do_work: Blocks copied: %hu, Bytes Copied: %u\n",
copied_nolb, copied_nolb * dst_dev->dev_attrib.block_size);
pr_debug("target_xcopy_do_work: Setting X-COPY GOOD status -> sending response\n");
target_complete_cmd(ec_cmd, SAM_STAT_GOOD);
return;
out:
xcopy_pt_undepend_remotedev(xop);
kfree(xop);
/*
* Don't override an error scsi status if it has already been set
*/
if (ec_cmd->scsi_status == SAM_STAT_GOOD) {
pr_warn_ratelimited("target_xcopy_do_work: rc: %d, Setting X-COPY"
" CHECK_CONDITION -> sending response\n", rc);
ec_cmd->scsi_status = SAM_STAT_CHECK_CONDITION;
}
target_complete_cmd(ec_cmd, ec_cmd->scsi_status);
}
sense_reason_t target_do_xcopy(struct se_cmd *se_cmd)
{
struct se_device *dev = se_cmd->se_dev;
struct xcopy_op *xop = NULL;
unsigned char *p = NULL, *seg_desc;
unsigned int list_id, list_id_usage, sdll, inline_dl, sa;
sense_reason_t ret = TCM_INVALID_PARAMETER_LIST;
int rc;
unsigned short tdll;
if (!dev->dev_attrib.emulate_3pc) {
pr_err("EXTENDED_COPY operation explicitly disabled\n");
return TCM_UNSUPPORTED_SCSI_OPCODE;
}
sa = se_cmd->t_task_cdb[1] & 0x1f;
if (sa != 0x00) {
pr_err("EXTENDED_COPY(LID4) not supported\n");
return TCM_UNSUPPORTED_SCSI_OPCODE;
}
xop = kzalloc(sizeof(struct xcopy_op), GFP_KERNEL);
if (!xop) {
pr_err("Unable to allocate xcopy_op\n");
return TCM_OUT_OF_RESOURCES;
}
xop->xop_se_cmd = se_cmd;
p = transport_kmap_data_sg(se_cmd);
if (!p) {
pr_err("transport_kmap_data_sg() failed in target_do_xcopy\n");
kfree(xop);
return TCM_OUT_OF_RESOURCES;
}
list_id = p[0];
list_id_usage = (p[1] & 0x18) >> 3;
/*
* Determine TARGET DESCRIPTOR LIST LENGTH + SEGMENT DESCRIPTOR LIST LENGTH
*/
tdll = get_unaligned_be16(&p[2]);
sdll = get_unaligned_be32(&p[8]);
inline_dl = get_unaligned_be32(&p[12]);
if (inline_dl != 0) {
pr_err("XCOPY with non zero inline data length\n");
goto out;
}
pr_debug("Processing XCOPY with list_id: 0x%02x list_id_usage: 0x%02x"
" tdll: %hu sdll: %u inline_dl: %u\n", list_id, list_id_usage,
tdll, sdll, inline_dl);
rc = target_xcopy_parse_target_descriptors(se_cmd, xop, &p[16], tdll, &ret);
if (rc <= 0)
goto out;
if (xop->src_dev->dev_attrib.block_size !=
xop->dst_dev->dev_attrib.block_size) {
pr_err("XCOPY: Non matching src_dev block_size: %u + dst_dev"
" block_size: %u currently unsupported\n",
xop->src_dev->dev_attrib.block_size,
xop->dst_dev->dev_attrib.block_size);
xcopy_pt_undepend_remotedev(xop);
ret = TCM_LOGICAL_UNIT_COMMUNICATION_FAILURE;
goto out;
}
pr_debug("XCOPY: Processed %d target descriptors, length: %u\n", rc,
rc * XCOPY_TARGET_DESC_LEN);
seg_desc = &p[16];
seg_desc += (rc * XCOPY_TARGET_DESC_LEN);
rc = target_xcopy_parse_segment_descriptors(se_cmd, xop, seg_desc, sdll);
if (rc <= 0) {
xcopy_pt_undepend_remotedev(xop);
goto out;
}
transport_kunmap_data_sg(se_cmd);
pr_debug("XCOPY: Processed %d segment descriptors, length: %u\n", rc,
rc * XCOPY_SEGMENT_DESC_LEN);
INIT_WORK(&xop->xop_work, target_xcopy_do_work);
queue_work(xcopy_wq, &xop->xop_work);
return TCM_NO_SENSE;
out:
if (p)
transport_kunmap_data_sg(se_cmd);
kfree(xop);
return ret;
}
static sense_reason_t target_rcr_operating_parameters(struct se_cmd *se_cmd)
{
unsigned char *p;
p = transport_kmap_data_sg(se_cmd);
if (!p) {
pr_err("transport_kmap_data_sg failed in"
" target_rcr_operating_parameters\n");
return TCM_OUT_OF_RESOURCES;
}
if (se_cmd->data_length < 54) {
pr_err("Receive Copy Results Op Parameters length"
" too small: %u\n", se_cmd->data_length);
transport_kunmap_data_sg(se_cmd);
return TCM_INVALID_CDB_FIELD;
}
/*
* Set SNLID=1 (Supports no List ID)
*/
p[4] = 0x1;
/*
* MAXIMUM TARGET DESCRIPTOR COUNT
*/
put_unaligned_be16(RCR_OP_MAX_TARGET_DESC_COUNT, &p[8]);
/*
* MAXIMUM SEGMENT DESCRIPTOR COUNT
*/
put_unaligned_be16(RCR_OP_MAX_SG_DESC_COUNT, &p[10]);
/*
* MAXIMUM DESCRIPTOR LIST LENGTH
*/
put_unaligned_be32(RCR_OP_MAX_DESC_LIST_LEN, &p[12]);
/*
* MAXIMUM SEGMENT LENGTH
*/
put_unaligned_be32(RCR_OP_MAX_SEGMENT_LEN, &p[16]);
/*
* MAXIMUM INLINE DATA LENGTH for SA 0x04 (NOT SUPPORTED)
*/
put_unaligned_be32(0x0, &p[20]);
/*
* HELD DATA LIMIT
*/
put_unaligned_be32(0x0, &p[24]);
/*
* MAXIMUM STREAM DEVICE TRANSFER SIZE
*/
put_unaligned_be32(0x0, &p[28]);
/*
* TOTAL CONCURRENT COPIES
*/
put_unaligned_be16(RCR_OP_TOTAL_CONCURR_COPIES, &p[34]);
/*
* MAXIMUM CONCURRENT COPIES
*/
p[36] = RCR_OP_MAX_CONCURR_COPIES;
/*
* DATA SEGMENT GRANULARITY (log 2)
*/
p[37] = RCR_OP_DATA_SEG_GRAN_LOG2;
/*
* INLINE DATA GRANULARITY log 2)
*/
p[38] = RCR_OP_INLINE_DATA_GRAN_LOG2;
/*
* HELD DATA GRANULARITY
*/
p[39] = RCR_OP_HELD_DATA_GRAN_LOG2;
/*
* IMPLEMENTED DESCRIPTOR LIST LENGTH
*/
p[43] = 0x2;
/*
* List of implemented descriptor type codes (ordered)
*/
p[44] = 0x02; /* Copy Block to Block device */
p[45] = 0xe4; /* Identification descriptor target descriptor */
/*
* AVAILABLE DATA (n-3)
*/
put_unaligned_be32(42, &p[0]);
transport_kunmap_data_sg(se_cmd);
target_complete_cmd(se_cmd, GOOD);
return TCM_NO_SENSE;
}
sense_reason_t target_do_receive_copy_results(struct se_cmd *se_cmd)
{
unsigned char *cdb = &se_cmd->t_task_cdb[0];
int sa = (cdb[1] & 0x1f), list_id = cdb[2];
sense_reason_t rc = TCM_NO_SENSE;
pr_debug("Entering target_do_receive_copy_results: SA: 0x%02x, List ID:"
" 0x%02x, AL: %u\n", sa, list_id, se_cmd->data_length);
if (list_id != 0) {
pr_err("Receive Copy Results with non zero list identifier"
" not supported\n");
return TCM_INVALID_CDB_FIELD;
}
switch (sa) {
case RCR_SA_OPERATING_PARAMETERS:
rc = target_rcr_operating_parameters(se_cmd);
break;
case RCR_SA_COPY_STATUS:
case RCR_SA_RECEIVE_DATA:
case RCR_SA_FAILED_SEGMENT_DETAILS:
default:
pr_err("Unsupported SA for receive copy results: 0x%02x\n", sa);
return TCM_INVALID_CDB_FIELD;
}
return rc;
}
|
195071.c | /* CLI Definitions for GDB, the GNU debugger.
Copyright (C) 2002-2021 Free Software Foundation, Inc.
This file is part of GDB.
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, see <http://www.gnu.org/licenses/>. */
#include "defs.h"
#include "cli-interp.h"
#include "interps.h"
#include "event-top.h"
#include "ui-out.h"
#include "cli-out.h"
#include "top.h" /* for "execute_command" */
#include "infrun.h"
#include "observable.h"
#include "gdbthread.h"
#include "thread-fsm.h"
#include "inferior.h"
cli_interp_base::cli_interp_base (const char *name)
: interp (name)
{}
cli_interp_base::~cli_interp_base ()
{}
/* The console interpreter. */
class cli_interp final : public cli_interp_base
{
public:
explicit cli_interp (const char *name);
~cli_interp ();
void init (bool top_level) override;
void resume () override;
void suspend () override;
gdb_exception exec (const char *command_str) override;
ui_out *interp_ui_out () override;
/* The ui_out for the console interpreter. */
cli_ui_out *cli_uiout;
};
cli_interp::cli_interp (const char *name)
: cli_interp_base (name)
{
/* Create a default uiout builder for the CLI. */
this->cli_uiout = cli_out_new (gdb_stdout);
}
cli_interp::~cli_interp ()
{
delete cli_uiout;
}
/* Suppress notification struct. */
struct cli_suppress_notification cli_suppress_notification =
{
0 /* user_selected_context_changed */
};
/* Returns the INTERP's data cast as cli_interp if INTERP is a CLI,
and returns NULL otherwise. */
static struct cli_interp *
as_cli_interp (struct interp *interp)
{
return dynamic_cast<cli_interp *> (interp);
}
/* Longjmp-safe wrapper for "execute_command". */
static struct gdb_exception safe_execute_command (struct ui_out *uiout,
const char *command,
int from_tty);
/* See cli-interp.h.
Breakpoint hits should always be mirrored to a console. Deciding
what to mirror to a console wrt to breakpoints and random stops
gets messy real fast. E.g., say "s" trips on a breakpoint. We'd
clearly want to mirror the event to the console in this case. But
what about more complicated cases like "s&; thread n; s&", and one
of those steps spawning a new thread, and that thread hitting a
breakpoint? It's impossible in general to track whether the thread
had any relation to the commands that had been executed. So we
just simplify and always mirror breakpoints and random events to
all consoles.
OTOH, we should print the source line to the console when stepping
or other similar commands, iff the step was started by that console
(or in MI's case, by a console command), but not if it was started
with MI's -exec-step or similar. */
int
should_print_stop_to_console (struct interp *console_interp,
struct thread_info *tp)
{
if ((bpstat_what (tp->control.stop_bpstat).main_action
== BPSTAT_WHAT_STOP_NOISY)
|| tp->thread_fsm == NULL
|| tp->thread_fsm->command_interp == console_interp
|| !tp->thread_fsm->finished_p ())
return 1;
return 0;
}
/* Observers for several run control events. If the interpreter is
quiet (i.e., another interpreter is being run with
interpreter-exec), print nothing. */
/* Observer for the normal_stop notification. */
static void
cli_on_normal_stop (struct bpstats *bs, int print_frame)
{
if (!print_frame)
return;
SWITCH_THRU_ALL_UIS ()
{
struct interp *interp = top_level_interpreter ();
struct cli_interp *cli = as_cli_interp (interp);
struct thread_info *thread;
if (cli == NULL)
continue;
thread = inferior_thread ();
if (should_print_stop_to_console (interp, thread))
print_stop_event (cli->cli_uiout);
}
}
/* Observer for the signal_received notification. */
static void
cli_on_signal_received (enum gdb_signal siggnal)
{
SWITCH_THRU_ALL_UIS ()
{
struct cli_interp *cli = as_cli_interp (top_level_interpreter ());
if (cli == NULL)
continue;
print_signal_received_reason (cli->cli_uiout, siggnal);
}
}
/* Observer for the end_stepping_range notification. */
static void
cli_on_end_stepping_range (void)
{
SWITCH_THRU_ALL_UIS ()
{
struct cli_interp *cli = as_cli_interp (top_level_interpreter ());
if (cli == NULL)
continue;
print_end_stepping_range_reason (cli->cli_uiout);
}
}
/* Observer for the signalled notification. */
static void
cli_on_signal_exited (enum gdb_signal siggnal)
{
SWITCH_THRU_ALL_UIS ()
{
struct cli_interp *cli = as_cli_interp (top_level_interpreter ());
if (cli == NULL)
continue;
print_signal_exited_reason (cli->cli_uiout, siggnal);
}
}
/* Observer for the exited notification. */
static void
cli_on_exited (int exitstatus)
{
SWITCH_THRU_ALL_UIS ()
{
struct cli_interp *cli = as_cli_interp (top_level_interpreter ());
if (cli == NULL)
continue;
print_exited_reason (cli->cli_uiout, exitstatus);
}
}
/* Observer for the no_history notification. */
static void
cli_on_no_history (void)
{
SWITCH_THRU_ALL_UIS ()
{
struct cli_interp *cli = as_cli_interp (top_level_interpreter ());
if (cli == NULL)
continue;
print_no_history_reason (cli->cli_uiout);
}
}
/* Observer for the sync_execution_done notification. */
static void
cli_on_sync_execution_done (void)
{
struct cli_interp *cli = as_cli_interp (top_level_interpreter ());
if (cli == NULL)
return;
display_gdb_prompt (NULL);
}
/* Observer for the command_error notification. */
static void
cli_on_command_error (void)
{
struct cli_interp *cli = as_cli_interp (top_level_interpreter ());
if (cli == NULL)
return;
display_gdb_prompt (NULL);
}
/* Observer for the user_selected_context_changed notification. */
static void
cli_on_user_selected_context_changed (user_selected_what selection)
{
/* This event is suppressed. */
if (cli_suppress_notification.user_selected_context)
return;
thread_info *tp = inferior_ptid != null_ptid ? inferior_thread () : NULL;
SWITCH_THRU_ALL_UIS ()
{
struct cli_interp *cli = as_cli_interp (top_level_interpreter ());
if (cli == NULL)
continue;
if (selection & USER_SELECTED_INFERIOR)
print_selected_inferior (cli->cli_uiout);
if (tp != NULL
&& ((selection & (USER_SELECTED_THREAD | USER_SELECTED_FRAME))))
print_selected_thread_frame (cli->cli_uiout, selection);
}
}
/* pre_command_loop implementation. */
void
cli_interp_base::pre_command_loop ()
{
display_gdb_prompt (0);
}
/* These implement the cli out interpreter: */
void
cli_interp::init (bool top_level)
{
}
void
cli_interp::resume ()
{
struct ui *ui = current_ui;
struct cli_interp *cli = this;
struct ui_file *stream;
/*sync_execution = 1; */
/* gdb_setup_readline will change gdb_stdout. If the CLI was
previously writing to gdb_stdout, then set it to the new
gdb_stdout afterwards. */
stream = cli->cli_uiout->set_stream (gdb_stdout);
if (stream != gdb_stdout)
{
cli->cli_uiout->set_stream (stream);
stream = NULL;
}
gdb_setup_readline (1);
ui->input_handler = command_line_handler;
if (stream != NULL)
cli->cli_uiout->set_stream (gdb_stdout);
}
void
cli_interp::suspend ()
{
gdb_disable_readline ();
}
gdb_exception
cli_interp::exec (const char *command_str)
{
struct cli_interp *cli = this;
struct ui_file *old_stream;
struct gdb_exception result;
/* gdb_stdout could change between the time cli_uiout was
initialized and now. Since we're probably using a different
interpreter which has a new ui_file for gdb_stdout, use that one
instead of the default.
It is important that it gets reset everytime, since the user
could set gdb to use a different interpreter. */
old_stream = cli->cli_uiout->set_stream (gdb_stdout);
result = safe_execute_command (cli->cli_uiout, command_str, 1);
cli->cli_uiout->set_stream (old_stream);
return result;
}
bool
cli_interp_base::supports_command_editing ()
{
return true;
}
static struct gdb_exception
safe_execute_command (struct ui_out *command_uiout, const char *command,
int from_tty)
{
struct gdb_exception e;
/* Save and override the global ``struct ui_out'' builder. */
scoped_restore saved_uiout = make_scoped_restore (¤t_uiout,
command_uiout);
try
{
execute_command (command, from_tty);
}
catch (gdb_exception &exception)
{
e = std::move (exception);
}
/* FIXME: cagney/2005-01-13: This shouldn't be needed. Instead the
caller should print the exception. */
exception_print (gdb_stderr, e);
return e;
}
ui_out *
cli_interp::interp_ui_out ()
{
struct cli_interp *cli = (struct cli_interp *) this;
return cli->cli_uiout;
}
/* These hold the pushed copies of the gdb output files.
If NULL then nothing has yet been pushed. */
struct saved_output_files
{
ui_file *out;
ui_file *err;
ui_file *log;
ui_file *targ;
ui_file *targerr;
ui_file *file_to_delete;
};
static saved_output_files saved_output;
/* See cli-interp.h. */
void
cli_interp_base::set_logging (ui_file_up logfile, bool logging_redirect,
bool debug_redirect)
{
if (logfile != nullptr)
{
saved_output.out = gdb_stdout;
saved_output.err = gdb_stderr;
saved_output.log = gdb_stdlog;
saved_output.targ = gdb_stdtarg;
saved_output.targerr = gdb_stdtargerr;
/* If something is being redirected, then grab logfile. */
ui_file *logfile_p = nullptr;
if (logging_redirect || debug_redirect)
{
logfile_p = logfile.get ();
saved_output.file_to_delete = logfile_p;
}
/* If something is not being redirected, then a tee containing both the
logfile and stdout. */
ui_file *tee = nullptr;
if (!logging_redirect || !debug_redirect)
{
tee = new tee_file (gdb_stdout, std::move (logfile));
saved_output.file_to_delete = tee;
}
/* Make sure that the call to logfile's dtor does not delete the
underlying pointer if we still keep a reference to it. If
logfile_p is not referenced as the file_to_delete, then either
the logfile is not used (no redirection) and it should be
deleted, or a tee took ownership of the pointer. */
if (logfile_p != nullptr && saved_output.file_to_delete == logfile_p)
logfile.release ();
gdb_stdout = logging_redirect ? logfile_p : tee;
gdb_stdlog = debug_redirect ? logfile_p : tee;
gdb_stderr = logging_redirect ? logfile_p : tee;
gdb_stdtarg = logging_redirect ? logfile_p : tee;
gdb_stdtargerr = logging_redirect ? logfile_p : tee;
}
else
{
/* Delete the correct file. If it's the tee then the logfile will also
be deleted. */
delete saved_output.file_to_delete;
gdb_stdout = saved_output.out;
gdb_stderr = saved_output.err;
gdb_stdlog = saved_output.log;
gdb_stdtarg = saved_output.targ;
gdb_stdtargerr = saved_output.targerr;
saved_output.out = nullptr;
saved_output.err = nullptr;
saved_output.log = nullptr;
saved_output.targ = nullptr;
saved_output.targerr = nullptr;
saved_output.file_to_delete = nullptr;
}
}
/* Factory for CLI interpreters. */
static struct interp *
cli_interp_factory (const char *name)
{
return new cli_interp (name);
}
/* Standard gdb initialization hook. */
void _initialize_cli_interp ();
void
_initialize_cli_interp ()
{
interp_factory_register (INTERP_CONSOLE, cli_interp_factory);
/* If changing this, remember to update tui-interp.c as well. */
gdb::observers::normal_stop.attach (cli_on_normal_stop, "cli-interp");
gdb::observers::end_stepping_range.attach (cli_on_end_stepping_range,
"cli-interp");
gdb::observers::signal_received.attach (cli_on_signal_received, "cli-interp");
gdb::observers::signal_exited.attach (cli_on_signal_exited, "cli-interp");
gdb::observers::exited.attach (cli_on_exited, "cli-interp");
gdb::observers::no_history.attach (cli_on_no_history, "cli-interp");
gdb::observers::sync_execution_done.attach (cli_on_sync_execution_done,
"cli-interp");
gdb::observers::command_error.attach (cli_on_command_error, "cli-interp");
gdb::observers::user_selected_context_changed.attach
(cli_on_user_selected_context_changed, "cli-interp");
}
|
532393.c | /*++
Copyright (c) 1997-2011 Microsoft Corporation
Module Name:
USBVIEW.C
Abstract:
This is the GUI goop for the USBVIEW application.
Environment:
user mode
Revision History:
04-25-97 : created
11-20-02 : minor changes to support more reporting options
04/13/2005 : major bug fixing
07/01/2008 : add UVC 1.1 support and move to Dev branch
--*/
/*****************************************************************************
I N C L U D E S
*****************************************************************************/
#include "resource.h"
#include "uvcview.h"
#include "h264.h"
#include "xmlhelper.h"
#include <commdlg.h>
/*****************************************************************************
D E F I N E S
*****************************************************************************/
// window control defines
//
#define SIZEBAR 0
#define WINDOWSCALEFACTOR 15
/*****************************************************************************
L O C A L T Y P E D E F S
*****************************************************************************/
typedef struct _TREEITEMINFO
{
struct _TREEITEMINFO *Next;
USHORT Depth;
PCHAR Name;
} TREEITEMINFO, *PTREEITEMINFO;
/*****************************************************************************
L O C A L E N U M S
*****************************************************************************/
typedef enum _USBVIEW_SAVE_FILE_TYPE
{
UsbViewNone = 0,
UsbViewXmlFile,
UsbViewTxtFile
} USBVIEW_SAVE_FILE_TYPE;
/*****************************************************************************
L O C A L F U N C T I O N P R O T O T Y P E S
*****************************************************************************/
int WINAPI
WinMain (
_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPSTR lpszCmdLine,
_In_ int nCmdShow
);
BOOL
CreateMainWindow (
int nCmdShow
);
VOID
ResizeWindows (
BOOL bSizeBar,
int BarLocation
);
LRESULT CALLBACK
MainDlgProc (
HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam
);
BOOL
USBView_OnInitDialog (
HWND hWnd,
HWND hWndFocus,
LPARAM lParam
);
VOID
USBView_OnClose (
HWND hWnd
);
VOID
USBView_OnCommand (
HWND hWnd,
int id,
HWND hwndCtl,
UINT codeNotify
);
VOID
USBView_OnLButtonDown (
HWND hWnd,
BOOL fDoubleClick,
int x,
int y,
UINT keyFlags
);
VOID
USBView_OnLButtonUp (
HWND hWnd,
int x,
int y,
UINT keyFlags
);
VOID
USBView_OnMouseMove (
HWND hWnd,
int x,
int y,
UINT keyFlags
);
VOID
USBView_OnSize (
HWND hWnd,
UINT state,
int cx,
int cy
);
LRESULT
USBView_OnNotify (
HWND hWnd,
int DlgItem,
LPNMHDR lpNMHdr
);
BOOL
USBView_OnDeviceChange (
HWND hwnd,
UINT uEvent,
DWORD dwEventData
);
VOID DestroyTree (VOID);
VOID RefreshTree (VOID);
LRESULT CALLBACK
AboutDlgProc (
HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam
);
VOID
WalkTree (
_In_ HTREEITEM hTreeItem,
_In_ LPFNTREECALLBACK lpfnTreeCallback,
_In_opt_ PVOID pContext
);
VOID
ExpandItem (
HWND hTreeWnd,
HTREEITEM hTreeItem,
PVOID pContext
);
VOID
AddItemInformationToFile(
HWND hTreeWnd,
HTREEITEM hTreeItem,
PVOID pContext
);
DWORD
DisplayLastError(
_Inout_updates_bytes_(count) char *szString,
int count);
VOID AddItemInformationToXmlView(
HWND hTreeWnd,
HTREEITEM hTreeItem,
PVOID pContext
);
HRESULT InitializeConsole();
VOID UnInitializeConsole();
BOOL IsStdOutFile();
VOID DisplayMessage(DWORD dwMsgId, ...);
VOID PrintString(LPTSTR lpszString);
LPTSTR WStringToAnsiString(LPWSTR lpwszString);
VOID WaitForKeyPress();
BOOL ProcessCommandLine();
HRESULT ProcessCommandSaveFile(LPTSTR szFileName, DWORD dwCreationDisposition, USBVIEW_SAVE_FILE_TYPE fileType);
HRESULT SaveAllInformationAsText(LPTSTR lpstrTextFileName, DWORD dwCreationDisposition);
HRESULT SaveAllInformationAsXml(LPTSTR lpstrTextFileName , DWORD dwCreationDisposition);
/*****************************************************************************
G L O B A L S
*****************************************************************************/
BOOL gDoConfigDesc = TRUE;
BOOL gDoAnnotation = TRUE;
BOOL gLogDebug = FALSE;
int TotalHubs = 0;
extern DEVICE_GUID_LIST gHubList;
extern DEVICE_GUID_LIST gDeviceList;
/*****************************************************************************
G L O B A L S P R I V A T E T O T H I S F I L E
*****************************************************************************/
HINSTANCE ghInstance = NULL;
HWND ghMainWnd = NULL;
HWND ghTreeWnd = NULL;
HWND ghEditWnd = NULL;
HWND ghStatusWnd = NULL;
HMENU ghMainMenu = NULL;
HTREEITEM ghTreeRoot = NULL;
HCURSOR ghSplitCursor = NULL;
HDEVNOTIFY gNotifyDevHandle = NULL;
HDEVNOTIFY gNotifyHubHandle = NULL;
HANDLE ghStdOut = NULL;
BOOL gbConsoleFile = FALSE;
BOOL gbConsoleInitialized = FALSE;
BOOL gbButtonDown = FALSE;
BOOL gDoAutoRefresh = TRUE;
int gBarLocation = 0;
int giGoodDevice = 0;
int giBadDevice = 0;
int giComputer = 0;
int giHub = 0;
int giNoDevice = 0;
int giGoodSsDevice = 0;
int giNoSsDevice = 0;
/*****************************************************************************
WinMain()
*****************************************************************************/
int WINAPI
WinMain (
_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPSTR lpszCmdLine,
_In_ int nCmdShow
)
{
MSG msg;
HACCEL hAccel;
int retStatus = 0;
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpszCmdLine);
InitXmlHelper();
ghInstance = hInstance;
ghSplitCursor = LoadCursor(ghInstance,
MAKEINTRESOURCE(IDC_SPLIT));
if (!ghSplitCursor)
{
OOPS();
return retStatus;
}
hAccel = LoadAccelerators(ghInstance,
MAKEINTRESOURCE(IDACCEL));
if (!hAccel)
{
OOPS();
return retStatus;
}
if (!CreateTextBuffer())
{
return retStatus;
}
if (!ProcessCommandLine())
{
// There were no command line flags, open GUI
if (CreateMainWindow(nCmdShow))
{
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(ghMainWnd,
hAccel,
&msg) &&
!IsDialogMessage(ghMainWnd,
&msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
retStatus = 1;
}
}
DestroyTextBuffer();
ReleaseXmlWriter();
CHECKFORLEAKS();
return retStatus;
}
/*****************************************************************************
ProcessCommandLine()
Parses the command line and takes appropriate actions. Returns FALSE If there is no action to
perform
*****************************************************************************/
BOOL ProcessCommandLine()
{
LPWSTR *szArgList = NULL;
LPTSTR szArg = NULL;
LPTSTR szAnsiArg= NULL;
BOOL quietMode = FALSE;
HRESULT hr = S_OK;
DWORD dwCreationDisposition = CREATE_NEW;
USBVIEW_SAVE_FILE_TYPE fileType = UsbViewNone;
int nArgs = 0;
int i = 0;
BOOL bStatus = FALSE;
BOOL bStopArgProcessing = FALSE;
szArgList = CommandLineToArgvW(GetCommandLineW(), &nArgs);
// If there are no arguments we return false
bStatus = (nArgs > 1)? TRUE:FALSE;
if (NULL != szArgList)
{
if (nArgs > 1)
{
// If there are arguments, initialize console for ouput
InitializeConsole();
}
for (i = 1; (i < nArgs) && (bStopArgProcessing == FALSE); i++)
{
// Convert argument to ANSI string for futher processing
szAnsiArg = WStringToAnsiString(szArgList[i]);
if(NULL == szAnsiArg)
{
DisplayMessage(IDS_USBVIEW_INVALIDARG, szAnsiArg);
DisplayMessage(IDS_USBVIEW_USAGE);
break;
}
if (0 == _stricmp(szAnsiArg, "/?"))
{
DisplayMessage(IDS_USBVIEW_USAGE);
break;
}
else if (NULL != StrStrI(szAnsiArg, "/saveall:"))
{
fileType = UsbViewTxtFile;
}
else if (NULL != StrStrI(szAnsiArg, "/savexml:"))
{
fileType = UsbViewXmlFile;
}
else if (0 == _stricmp(szAnsiArg, "/f"))
{
dwCreationDisposition = CREATE_ALWAYS;
}
else if (0 == _stricmp(szAnsiArg, "/q"))
{
quietMode = TRUE;
}
else
{
DisplayMessage(IDS_USBVIEW_INVALIDARG, szAnsiArg);
DisplayMessage(IDS_USBVIEW_USAGE);
bStopArgProcessing = TRUE;
}
if (fileType != UsbViewNone)
{
// Save view information as to file
szArg = strchr(szAnsiArg, ':');
if (NULL == szArg || strlen(szArg) == 1)
{
// No ':' or just a ':'
DisplayMessage(IDS_USBVIEW_INVALID_FILENAME, szAnsiArg);
DisplayMessage(IDS_USBVIEW_USAGE);
bStopArgProcessing = TRUE;
}
else
{
hr = ProcessCommandSaveFile(szArg + 1, dwCreationDisposition, fileType);
if (FAILED(hr))
{
// No more processing
bStopArgProcessing = TRUE;
}
fileType = UsbViewNone;
}
}
if (NULL != szAnsiArg)
{
LocalFree(szAnsiArg);
}
}
if(!quietMode)
{
WaitForKeyPress();
}
if (gbConsoleInitialized)
{
UnInitializeConsole();
}
LocalFree(szArgList);
}
return bStatus;
}
/*****************************************************************************
ProcessCommandSaveFile()
Process the save file command line
*****************************************************************************/
HRESULT ProcessCommandSaveFile(LPTSTR szFileName, DWORD dwCreationDisposition, USBVIEW_SAVE_FILE_TYPE fileType)
{
HRESULT hr = S_OK;
LPTSTR szErrorBuffer = NULL;
if (UsbViewNone == fileType || NULL == szFileName)
{
hr = E_INVALIDARG;
// Invalid arguments, return
return (hr);
}
// The UI is not created yet, open the UI, but HIDE it
CreateMainWindow(SW_HIDE);
if (UsbViewXmlFile == fileType)
{
hr = SaveAllInformationAsXml(szFileName, dwCreationDisposition);
}
if (UsbViewTxtFile == fileType)
{
hr = SaveAllInformationAsText(szFileName, dwCreationDisposition);
}
if (FAILED(hr))
{
if (GetLastError() == ERROR_FILE_EXISTS || hr == HRESULT_FROM_WIN32(ERROR_FILE_EXISTS))
{
// The operation failed because the file we tried to write to already existed and '/f' option
// was not present. Display error message to user describing '/f' option
switch(fileType)
{
case UsbViewXmlFile:
DisplayMessage(IDS_USBVIEW_FILE_EXISTS_XML, szFileName);
break;
case UsbViewTxtFile:
DisplayMessage(IDS_USBVIEW_FILE_EXISTS_TXT, szFileName);
break;
default:
DisplayMessage(IDS_USBVIEW_INTERNAL_ERROR);
break;
}
}
else
{
// Try to obtain system error message
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
hr,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &szErrorBuffer, // FormatMessage expects this buffer to be cast as LPTSTR
0,
NULL);
PrintString("Unable to save file.\n");
PrintString(szErrorBuffer);
LocalFree(szErrorBuffer);
}
}
else
{
// Display file saved to message in console
DisplayMessage(IDS_USBVIEW_SAVED_TO, szFileName);
}
return (hr);
}
/*****************************************************************************
InitializeConsole()
Initializes the std output in console
*****************************************************************************/
HRESULT InitializeConsole()
{
HRESULT hr = S_OK;
SetLastError(0);
// Find if STD_OUTPUT is a console or has been redirected to a File
gbConsoleFile = IsStdOutFile();
if (!gbConsoleFile)
{
// Output is not redirected and GUI application do not have console by default, create a console
if(AllocConsole())
{
#pragma warning(disable:4996) // We don' need the FILE * returned by freopen
// Reopen STDOUT , STDIN and STDERR
if((freopen("conout$", "w", stdout) != NULL) &&
(freopen("conin$", "r", stdin) != NULL) &&
(freopen("conout$","w", stderr) != NULL))
{
gbConsoleInitialized = TRUE;
ghStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
}
#pragma warning(default:4996)
}
}
if (INVALID_HANDLE_VALUE == ghStdOut || FALSE == gbConsoleInitialized)
{
hr = HRESULT_FROM_WIN32(GetLastError());
OOPS();
}
return hr;
}
/*****************************************************************************
UnInitializeConsole()
UnInitializes the console
*****************************************************************************/
VOID UnInitializeConsole()
{
gbConsoleInitialized = FALSE;
FreeConsole();
}
/*****************************************************************************
IsStdOutFile()
Finds if the STD_OUTPUT has been redirected to a file
*****************************************************************************/
BOOL IsStdOutFile()
{
unsigned htype;
HANDLE hFile;
// 1 = STDOUT
hFile = (HANDLE) _get_osfhandle(1);
htype = GetFileType(hFile);
htype &= ~FILE_TYPE_REMOTE;
// Check if file type is character file
if (FILE_TYPE_DISK == htype)
{
return TRUE;
}
return FALSE;
}
/*****************************************************************************
DisplayMessage()
Displays a message to standard output
*****************************************************************************/
VOID DisplayMessage(DWORD dwResId, ...)
{
CHAR szFormat[4096];
HRESULT hr = S_OK;
LPTSTR lpszMessage = NULL;
DWORD dwLen = 0;
va_list ap;
va_start(ap, dwResId);
// Initialize console if needed
if (!gbConsoleInitialized)
{
hr = InitializeConsole();
if (FAILED(hr))
{
OOPS();
return;
}
}
// Load the string resource
dwLen = LoadString(GetModuleHandle(NULL),
dwResId,
szFormat,
ARRAYSIZE(szFormat)
);
if(0 == dwLen)
{
PrintString("Unable to find message for given resource ID");
// Return if resource ID could not be found
return;
}
dwLen = FormatMessage(
FORMAT_MESSAGE_FROM_STRING | FORMAT_MESSAGE_ALLOCATE_BUFFER,
szFormat,
dwResId,
0,
(LPTSTR) &lpszMessage,
ARRAYSIZE(szFormat),
&ap);
if (dwLen > 0)
{
PrintString(lpszMessage);
LocalFree(lpszMessage);
}
else
{
PrintString("Unable to find message for given ID");
}
va_end(ap);
return;
}
/*****************************************************************************
WStringToAnsiString()
Converts the Wide char string to ANSI string and returns the allocated ANSI string.
*****************************************************************************/
LPTSTR WStringToAnsiString(LPWSTR lpwszString)
{
int strLen = 0;
LPTSTR szAnsiBuffer = NULL;
szAnsiBuffer = LocalAlloc(LPTR, (MAX_PATH + 1) * sizeof(CHAR));
// Convert string from from WCHAR to ANSI
if (NULL != szAnsiBuffer)
{
strLen = WideCharToMultiByte(
CP_ACP,
0,
lpwszString,
-1,
szAnsiBuffer,
MAX_PATH + 1,
NULL,
NULL);
if (strLen > 0)
{
return szAnsiBuffer;
}
}
return NULL;
}
/*****************************************************************************
PrintString()
Displays a string to standard output
*****************************************************************************/
VOID PrintString(LPTSTR lpszString)
{
DWORD dwBytesWritten = 0;
size_t Len = 0;
LPSTR lpOemString = NULL;
if (INVALID_HANDLE_VALUE == ghStdOut || NULL == lpszString)
{
OOPS();
// Return if invalid inputs
return;
}
if (FAILED(StringCchLength(lpszString, OUTPUT_MESSAGE_MAX_LENGTH, &Len)))
{
OOPS();
// Return if string is too long
return;
}
if (gbConsoleFile)
{
// Console has been redirected to a file, ex: `usbview /savexml:xx > test.txt`. We need to use WriteFile instead of
// WriteConsole for text output.
lpOemString = (LPSTR) LocalAlloc(LPTR, (Len + 1) * sizeof(CHAR));
if (lpOemString != NULL)
{
if (CharToOemBuff(lpszString, lpOemString, (DWORD) Len))
{
WriteFile(ghStdOut, (LPVOID) lpOemString, (DWORD) Len, &dwBytesWritten, NULL);
}
else
{
OOPS();
}
}
}
else
{
// Write to std out in console
WriteConsole(ghStdOut, (LPVOID) lpszString, (DWORD) Len, &dwBytesWritten, NULL);
}
return;
}
/*****************************************************************************
WaitForKeyPress()
Waits for key press in case of console
*****************************************************************************/
VOID WaitForKeyPress()
{
// Wait for key press if console
if (!gbConsoleFile && gbConsoleInitialized)
{
DisplayMessage(IDS_USBVIEW_PRESSKEY);
(VOID) _getch();
}
return;
}
/*****************************************************************************
CreateMainWindow()
*****************************************************************************/
BOOL
CreateMainWindow (
int nCmdShow
)
{
RECT rc;
InitCommonControls();
ghMainWnd = CreateDialog(ghInstance,
MAKEINTRESOURCE(IDD_MAINDIALOG),
NULL,
(DLGPROC) MainDlgProc);
if (ghMainWnd == NULL)
{
OOPS();
return FALSE;
}
GetWindowRect(ghMainWnd, &rc);
gBarLocation = (rc.right - rc.left) / 3;
ResizeWindows(FALSE, 0);
ShowWindow(ghMainWnd, nCmdShow);
UpdateWindow(ghMainWnd);
return TRUE;
}
/*****************************************************************************
ResizeWindows()
Handles resizing the two child windows of the main window. If
bSizeBar is true, then the sizing is happening because the user is
moving the bar. If bSizeBar is false, the sizing is happening
because of the WM_SIZE or something like that.
*****************************************************************************/
VOID
ResizeWindows (
BOOL bSizeBar,
int BarLocation
)
{
RECT MainClientRect;
RECT MainWindowRect;
RECT TreeWindowRect;
RECT StatusWindowRect;
int right;
// Is the user moving the bar?
//
if (!bSizeBar)
{
BarLocation = gBarLocation;
}
GetClientRect(ghMainWnd, &MainClientRect);
GetWindowRect(ghStatusWnd, &StatusWindowRect);
// Make sure the bar is in a OK location
//
if (bSizeBar)
{
if (BarLocation <
GetSystemMetrics(SM_CXSCREEN)/WINDOWSCALEFACTOR)
{
return;
}
if ((MainClientRect.right - BarLocation) <
GetSystemMetrics(SM_CXSCREEN)/WINDOWSCALEFACTOR)
{
return;
}
}
// Save the bar location
//
gBarLocation = BarLocation;
// Move the tree window
//
MoveWindow(ghTreeWnd,
0,
0,
BarLocation,
MainClientRect.bottom - StatusWindowRect.bottom + StatusWindowRect.top,
TRUE);
// Get the size of the window (in case move window failed
//
GetWindowRect(ghTreeWnd, &TreeWindowRect);
GetWindowRect(ghMainWnd, &MainWindowRect);
right = TreeWindowRect.right - MainWindowRect.left;
// Move the edit window with respect to the tree window
//
MoveWindow(ghEditWnd,
right+SIZEBAR,
0,
MainClientRect.right-(right+SIZEBAR),
MainClientRect.bottom - StatusWindowRect.bottom + StatusWindowRect.top,
TRUE);
// Move the Status window with respect to the tree window
//
MoveWindow(ghStatusWnd,
0,
MainClientRect.bottom - StatusWindowRect.bottom + StatusWindowRect.top,
MainClientRect.right,
StatusWindowRect.bottom - StatusWindowRect.top,
TRUE);
}
/*****************************************************************************
MainWndProc()
*****************************************************************************/
LRESULT CALLBACK
MainDlgProc (
HWND hWnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam
)
{
switch (uMsg)
{
HANDLE_MSG(hWnd, WM_INITDIALOG, USBView_OnInitDialog);
HANDLE_MSG(hWnd, WM_CLOSE, USBView_OnClose);
HANDLE_MSG(hWnd, WM_COMMAND, USBView_OnCommand);
HANDLE_MSG(hWnd, WM_LBUTTONDOWN, USBView_OnLButtonDown);
HANDLE_MSG(hWnd, WM_LBUTTONUP, USBView_OnLButtonUp);
HANDLE_MSG(hWnd, WM_MOUSEMOVE, USBView_OnMouseMove);
HANDLE_MSG(hWnd, WM_SIZE, USBView_OnSize);
HANDLE_MSG(hWnd, WM_NOTIFY, USBView_OnNotify);
HANDLE_MSG(hWnd, WM_DEVICECHANGE, USBView_OnDeviceChange);
}
return 0;
}
/*****************************************************************************
USBView_OnInitDialog()
*****************************************************************************/
BOOL
USBView_OnInitDialog (
HWND hWnd,
HWND hWndFocus,
LPARAM lParam
)
{
HFONT hFont;
HIMAGELIST himl;
HICON hicon;
DEV_BROADCAST_DEVICEINTERFACE broadcastInterface;
UNREFERENCED_PARAMETER(lParam);
UNREFERENCED_PARAMETER(hWndFocus);
// Register to receive notification when a USB device is plugged in.
broadcastInterface.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE);
broadcastInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
memcpy( &(broadcastInterface.dbcc_classguid),
&(GUID_DEVINTERFACE_USB_DEVICE),
sizeof(struct _GUID));
gNotifyDevHandle = RegisterDeviceNotification(hWnd,
&broadcastInterface,
DEVICE_NOTIFY_WINDOW_HANDLE);
// Now register for Hub notifications.
memcpy( &(broadcastInterface.dbcc_classguid),
&(GUID_CLASS_USBHUB),
sizeof(struct _GUID));
gNotifyHubHandle = RegisterDeviceNotification(hWnd,
&broadcastInterface,
DEVICE_NOTIFY_WINDOW_HANDLE);
gHubList.DeviceInfo = INVALID_HANDLE_VALUE;
InitializeListHead(&gHubList.ListHead);
gDeviceList.DeviceInfo = INVALID_HANDLE_VALUE;
InitializeListHead(&gDeviceList.ListHead);
//end add
ghTreeWnd = GetDlgItem(hWnd, IDC_TREE);
//added
if ((himl = ImageList_Create(15, 15,
FALSE, 2, 0)) == NULL)
{
OOPS();
}
if(himl != NULL)
{
hicon = LoadIcon(ghInstance, MAKEINTRESOURCE(IDI_ICON));
giGoodDevice = ImageList_AddIcon(himl, hicon);
hicon = LoadIcon(ghInstance, MAKEINTRESOURCE(IDI_BADICON));
giBadDevice = ImageList_AddIcon(himl, hicon);
hicon = LoadIcon(ghInstance, MAKEINTRESOURCE(IDI_COMPUTER));
giComputer = ImageList_AddIcon(himl, hicon);
hicon = LoadIcon(ghInstance, MAKEINTRESOURCE(IDI_HUB));
giHub = ImageList_AddIcon(himl, hicon);
hicon = LoadIcon(ghInstance, MAKEINTRESOURCE(IDI_NODEVICE));
giNoDevice = ImageList_AddIcon(himl, hicon);
hicon = LoadIcon(ghInstance, MAKEINTRESOURCE(IDI_SSICON));
giGoodSsDevice = ImageList_AddIcon(himl, hicon);
hicon = LoadIcon(ghInstance, MAKEINTRESOURCE(IDI_NOSSDEVICE));
giNoSsDevice = ImageList_AddIcon(himl, hicon);
TreeView_SetImageList(ghTreeWnd, himl, TVSIL_NORMAL);
// end add
}
ghEditWnd = GetDlgItem(hWnd, IDC_EDIT);
#ifdef H264_SUPPORT
// set the edit control to have a max text limit size
SendMessage(ghEditWnd, EM_LIMITTEXT, 0 /* USE DEFAULT MAX*/, 0);
#endif
ghStatusWnd = GetDlgItem(hWnd, IDC_STATUS);
ghMainMenu = GetMenu(hWnd);
if (ghMainMenu == NULL)
{
OOPS();
}
{
CHAR pszFont[256];
CHAR pszHeight[8];
memset(pszFont, 0, sizeof(pszFont));
LoadString(ghInstance, IDS_STANDARD_FONT, pszFont, sizeof(pszFont) - 1);
memset(pszHeight, 0, sizeof(pszHeight));
LoadString(ghInstance, IDS_STANDARD_FONT_HEIGHT, pszHeight, sizeof(pszHeight) - 1);
hFont = CreateFont((int) pszHeight[0], 0, 0, 0,
400, 0, 0, 0,
0, 1, 2, 1,
49, pszFont);
}
SendMessage(ghEditWnd,
WM_SETFONT,
(WPARAM) hFont,
0);
RefreshTree();
return FALSE;
}
/*****************************************************************************
USBView_OnClose()
*****************************************************************************/
VOID
USBView_OnClose (
HWND hWnd
)
{
UNREFERENCED_PARAMETER(hWnd);
DestroyTree();
PostQuitMessage(0);
}
/*****************************************************************************
AddItemInformationToFile()
Saves the information about the current item to the list
*****************************************************************************/
VOID
AddItemInformationToFile(
HWND hTreeWnd,
HTREEITEM hTreeItem,
PVOID pContext
)
{
HRESULT hr = S_OK;
HANDLE hf = NULL;
DWORD dwBytesWritten = 0;
hf = *((PHANDLE) pContext);
ResetTextBuffer();
hr = UpdateTreeItemDeviceInfo(hTreeWnd, hTreeItem);
if (FAILED(hr))
{
OOPS();
}
else
{
WriteFile(hf, GetTextBuffer(), GetTextBufferPos()*sizeof(CHAR), &dwBytesWritten, NULL);
}
ResetTextBuffer();
}
/*****************************************************************************
SaveAllInformationAsText()
Saves the entire USB tree as a text file
*****************************************************************************/
HRESULT
SaveAllInformationAsText(
LPTSTR lpstrTextFileName,
DWORD dwCreationDisposition
)
{
HRESULT hr = S_OK;
HANDLE hf = NULL;
hf = CreateFile(lpstrTextFileName,
GENERIC_WRITE,
0,
NULL,
dwCreationDisposition,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hf == INVALID_HANDLE_VALUE)
{
hr = HRESULT_FROM_WIN32(GetLastError());
OOPS();
}
else
{
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
// CreateFile() sets this error if we are overwriting an existing file
// Reset this error to avoid false alarms
SetLastError(0);
}
if (ghTreeRoot == NULL)
{
// If tree has not been populated yet, try a refresh
RefreshTree();
}
if (ghTreeRoot)
{
LockFile(hf, 0, 0, 0, 0);
WalkTreeTopDown(ghTreeRoot, AddItemInformationToFile, &hf, NULL);
UnlockFile(hf, 0, 0, 0, 0);
CloseHandle(hf);
hr = S_OK;
}
else
{
hr = HRESULT_FROM_WIN32(GetLastError());
OOPS();
}
}
ResetTextBuffer();
return hr;
}
/*****************************************************************************
USBView_OnCommand()
*****************************************************************************/
VOID
USBView_OnCommand (
HWND hWnd,
int id,
HWND hwndCtl,
UINT codeNotify
)
{
MENUITEMINFO menuInfo;
char szFile[MAX_PATH + 1];
OPENFILENAME ofn;
HANDLE hf = NULL;
DWORD dwBytesWritten = 0;
int nTextLength = 0;
size_t lengthToNull = 0;
HRESULT hr = S_OK;
UNREFERENCED_PARAMETER(hwndCtl);
UNREFERENCED_PARAMETER(codeNotify);
//initialize save dialog variables
memset(szFile, 0, sizeof(szFile));
memset(&ofn, 0, sizeof(OPENFILENAME));
ofn.lStructSize = sizeof(OPENFILENAME);
ofn.hwndOwner = hWnd;
ofn.nFilterIndex = 1;
ofn.lpstrFile = szFile;
ofn.nMaxFile = MAX_PATH;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = 0;
ofn.lpstrTitle = NULL;
ofn.Flags = OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST;
switch (id)
{
case ID_AUTO_REFRESH:
gDoAutoRefresh = !gDoAutoRefresh;
menuInfo.cbSize = sizeof(menuInfo);
menuInfo.fMask = MIIM_STATE;
menuInfo.fState = gDoAutoRefresh ? MFS_CHECKED : MFS_UNCHECKED;
SetMenuItemInfo(ghMainMenu,
id,
FALSE,
&menuInfo);
break;
case ID_SAVE:
{
// initialize the save file name
StringCchCopy(szFile, MAX_PATH, "USBView.txt");
ofn.lpstrFilter = "Text\0*.TXT\0\0";
ofn.lpstrDefExt = "txt";
//call dialog box
if (! GetSaveFileName(&ofn))
{
OOPS();
break;
}
//create new file
hf = CreateFile((LPTSTR)ofn.lpstrFile,
GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hf == INVALID_HANDLE_VALUE)
{
OOPS();
}
else
{
char *szText = NULL;
//get data from display window to transfer to file
nTextLength = GetWindowTextLength(ghEditWnd);
nTextLength++;
szText = ALLOC((DWORD)nTextLength);
if (NULL != szText)
{
GetWindowText(ghEditWnd, (LPSTR) szText, nTextLength);
//
// Constrain length to the first null, which should be at
// the end of the window text. This prevents writing extra
// null characters.
//
if (StringCchLength(szText, nTextLength, &lengthToNull) == S_OK)
{
nTextLength = (int) lengthToNull;
//lock the file, write to the file, unlock file
LockFile(hf, 0, 0, 0, 0);
WriteFile(hf, szText, nTextLength, &dwBytesWritten, NULL);
UnlockFile(hf, 0, 0, 0, 0);
}
else
{
OOPS();
}
CloseHandle(hf);
FREE(szText);
}
else
{
OOPS();
}
}
break;
}
case ID_SAVEALL:
{
// initialize the save file name
StringCchCopy(szFile, MAX_PATH, "USBViewAll.txt");
ofn.lpstrFilter = "Text\0*.txt\0\0";
ofn.lpstrDefExt = "txt";
//call dialog box
if (! GetSaveFileName(&ofn))
{
OOPS();
break;
}
// Save the file, overwrite in case of UI since UI gives popup for confirmation
hr = SaveAllInformationAsText(ofn.lpstrFile, CREATE_ALWAYS);
if (FAILED(hr))
{
OOPS();
}
break;
}
case ID_SAVEXML:
{
// initialize the save file name
StringCchCopy(szFile, MAX_PATH, "USBViewAll.xml");
ofn.lpstrFilter = "Xml\0*.xml\0\0";
ofn.lpstrDefExt = "xml";
//call dialog box
if (! GetSaveFileName(&ofn))
{
OOPS();
break;
}
// Save the file, overwrite in case of UI since UI gives popup for confirmation
hr = SaveAllInformationAsXml(ofn.lpstrFile, CREATE_ALWAYS);
if (FAILED(hr))
{
OOPS();
}
break;
}
case ID_CONFIG_DESCRIPTORS:
gDoConfigDesc = !gDoConfigDesc;
menuInfo.cbSize = sizeof(menuInfo);
menuInfo.fMask = MIIM_STATE;
menuInfo.fState = gDoConfigDesc ? MFS_CHECKED : MFS_UNCHECKED;
SetMenuItemInfo(ghMainMenu,
id,
FALSE,
&menuInfo);
break;
case ID_ANNOTATION:
gDoAnnotation = !gDoAnnotation;
menuInfo.cbSize = sizeof(menuInfo);
menuInfo.fMask = MIIM_STATE;
menuInfo.fState = gDoAnnotation ? MFS_CHECKED : MFS_UNCHECKED;
SetMenuItemInfo(ghMainMenu,
id,
FALSE,
&menuInfo);
break;
case ID_LOG_DEBUG:
gLogDebug = !gLogDebug;
menuInfo.cbSize = sizeof(menuInfo);
menuInfo.fMask = MIIM_STATE;
menuInfo.fState = gLogDebug ? MFS_CHECKED : MFS_UNCHECKED;
SetMenuItemInfo(ghMainMenu,
id,
FALSE,
&menuInfo);
break;
case ID_ABOUT:
DialogBox(ghInstance,
MAKEINTRESOURCE(IDD_ABOUT),
ghMainWnd,
(DLGPROC) AboutDlgProc);
break;
case ID_EXIT:
UnregisterDeviceNotification(gNotifyDevHandle);
UnregisterDeviceNotification(gNotifyHubHandle);
DestroyTree();
PostQuitMessage(0);
break;
case ID_REFRESH:
RefreshTree();
break;
}
}
/*****************************************************************************
USBView_OnLButtonDown()
*****************************************************************************/
VOID
USBView_OnLButtonDown (
HWND hWnd,
BOOL fDoubleClick,
int x,
int y,
UINT keyFlags
)
{
UNREFERENCED_PARAMETER(fDoubleClick);
UNREFERENCED_PARAMETER(x);
UNREFERENCED_PARAMETER(y);
UNREFERENCED_PARAMETER(keyFlags);
gbButtonDown = TRUE;
SetCapture(hWnd);
}
/*****************************************************************************
USBView_OnLButtonUp()
*****************************************************************************/
VOID
USBView_OnLButtonUp (
HWND hWnd,
int x,
int y,
UINT keyFlags
)
{
UNREFERENCED_PARAMETER(hWnd);
UNREFERENCED_PARAMETER(x);
UNREFERENCED_PARAMETER(y);
UNREFERENCED_PARAMETER(keyFlags);
gbButtonDown = FALSE;
ReleaseCapture();
}
/*****************************************************************************
USBView_OnMouseMove()
*****************************************************************************/
VOID
USBView_OnMouseMove (
HWND hWnd,
int x,
int y,
UINT keyFlags
)
{
UNREFERENCED_PARAMETER(hWnd);
UNREFERENCED_PARAMETER(y);
UNREFERENCED_PARAMETER(keyFlags);
SetCursor(ghSplitCursor);
if (gbButtonDown)
{
ResizeWindows(TRUE, x);
}
}
/*****************************************************************************
USBView_OnSize();
*****************************************************************************/
VOID
USBView_OnSize (
HWND hWnd,
UINT state,
int cx,
int cy
)
{
UNREFERENCED_PARAMETER(hWnd);
UNREFERENCED_PARAMETER(state);
UNREFERENCED_PARAMETER(cx);
UNREFERENCED_PARAMETER(cy);
ResizeWindows(FALSE, 0);
}
/*****************************************************************************
USBView_OnNotify()
*****************************************************************************/
LRESULT
USBView_OnNotify (
HWND hWnd,
int DlgItem,
LPNMHDR lpNMHdr
)
{
UNREFERENCED_PARAMETER(hWnd);
UNREFERENCED_PARAMETER(DlgItem);
if (lpNMHdr->code == TVN_SELCHANGED)
{
HTREEITEM hTreeItem;
hTreeItem = ((NM_TREEVIEW *)lpNMHdr)->itemNew.hItem;
if (hTreeItem)
{
UpdateEditControl(ghEditWnd,
ghTreeWnd,
hTreeItem);
}
}
return 0;
}
/*****************************************************************************
USBView_OnDeviceChange()
*****************************************************************************/
BOOL
USBView_OnDeviceChange (
HWND hwnd,
UINT uEvent,
DWORD dwEventData
)
{
UNREFERENCED_PARAMETER(hwnd);
UNREFERENCED_PARAMETER(dwEventData);
if (gDoAutoRefresh)
{
switch (uEvent)
{
case DBT_DEVICEARRIVAL:
case DBT_DEVICEREMOVECOMPLETE:
RefreshTree();
break;
}
}
return TRUE;
}
/*****************************************************************************
DestroyTree()
*****************************************************************************/
VOID DestroyTree (VOID)
{
// Clear the selection of the TreeView, so that when the tree is
// destroyed, the control won't try to constantly "shift" the
// selection to another item.
//
TreeView_SelectItem(ghTreeWnd, NULL);
// Destroy the current contents of the TreeView
//
if (ghTreeRoot)
{
WalkTree(ghTreeRoot, CleanupItem, NULL);
TreeView_DeleteAllItems(ghTreeWnd);
ghTreeRoot = NULL;
}
ClearDeviceList(&gDeviceList);
ClearDeviceList(&gHubList);
}
/*****************************************************************************
RefreshTree()
*****************************************************************************/
VOID RefreshTree (VOID)
{
CHAR statusText[128];
ULONG devicesConnected;
// Clear the edit control
//
SetWindowText(ghEditWnd, "");
// Destroy the current contents of the TreeView
//
DestroyTree();
// Create the root tree node
//
ghTreeRoot = AddLeaf(TVI_ROOT, 0, "My Computer", ComputerIcon);
if (ghTreeRoot != NULL)
{
// Enumerate all USB buses and populate the tree
//
EnumerateHostControllers(ghTreeRoot, &devicesConnected);
//
// Expand all tree nodes
//
WalkTree(ghTreeRoot, ExpandItem, NULL);
// Update Status Line with number of devices connected
//
memset(statusText, 0, sizeof(statusText));
StringCchPrintf(statusText, sizeof(statusText),
#ifdef H264_SUPPORT
"UVC Spec Version: %d.%d Version: %d.%d Devices Connected: %d Hubs Connected: %d",
UVC_SPEC_MAJOR_VERSION, UVC_SPEC_MINOR_VERSION, USBVIEW_MAJOR_VERSION, USBVIEW_MINOR_VERSION,
devicesConnected, TotalHubs);
#else
"Devices Connected: %d Hubs Connected: %d",
devicesConnected, TotalHubs);
#endif
SetWindowText(ghStatusWnd, statusText);
}
else
{
OOPS();
}
}
/*****************************************************************************
AboutDlgProc()
*****************************************************************************/
LRESULT CALLBACK
AboutDlgProc (
HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam
)
{
UNREFERENCED_PARAMETER(lParam);
switch (uMsg)
{
case WM_INITDIALOG:
{
HRESULT hr;
char TextBuffer[TEXT_ITEM_LENGTH];
HWND hItem;
hItem = GetDlgItem(hwnd, IDC_VERSION);
if (hItem != NULL)
{
hr = StringCbPrintfA(TextBuffer,
sizeof(TextBuffer),
"USBView version: %d.%d",
USBVIEW_MAJOR_VERSION,
USBVIEW_MINOR_VERSION);
if (SUCCEEDED(hr))
{
SetWindowText(hItem,TextBuffer);
}
}
hItem = GetDlgItem(hwnd, IDC_UVCVERSION);
if (hItem != NULL)
{
hr = StringCbPrintfA(TextBuffer,
sizeof(TextBuffer),
"USB Video Class Spec version: %d.%d",
UVC_SPEC_MAJOR_VERSION,
UVC_SPEC_MINOR_VERSION);
if (SUCCEEDED(hr))
{
SetWindowText(hItem,TextBuffer);
}
}
}
break;
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDOK:
case IDCANCEL:
EndDialog (hwnd, 0);
break;
}
break;
}
return FALSE;
}
/*****************************************************************************
AddLeaf()
*****************************************************************************/
HTREEITEM
AddLeaf (
HTREEITEM hTreeParent,
LPARAM lParam,
_In_ LPTSTR lpszText,
TREEICON TreeIcon
)
{
TV_INSERTSTRUCT tvins;
HTREEITEM hti;
memset(&tvins, 0, sizeof(tvins));
// Set the parent item
//
tvins.hParent = hTreeParent;
tvins.hInsertAfter = TVI_LAST;
// pszText and lParam members are valid
//
tvins.item.mask = TVIF_TEXT | TVIF_PARAM;
// Set the text of the item.
//
tvins.item.pszText = lpszText;
// Set the user context item
//
tvins.item.lParam = lParam;
// Add the item to the tree-view control.
//
hti = TreeView_InsertItem(ghTreeWnd, &tvins);
// added
tvins.item.mask = TVIF_IMAGE | TVIF_SELECTEDIMAGE;
tvins.item.hItem = hti;
// Determine which icon to display for the device
//
switch (TreeIcon)
{
case ComputerIcon:
tvins.item.iImage = giComputer;
tvins.item.iSelectedImage = giComputer;
break;
case HubIcon:
tvins.item.iImage = giHub;
tvins.item.iSelectedImage = giHub;
break;
case NoDeviceIcon:
tvins.item.iImage = giNoDevice;
tvins.item.iSelectedImage = giNoDevice;
break;
case GoodDeviceIcon:
tvins.item.iImage = giGoodDevice;
tvins.item.iSelectedImage = giGoodDevice;
break;
case GoodSsDeviceIcon:
tvins.item.iImage = giGoodSsDevice;
tvins.item.iSelectedImage = giGoodSsDevice;
break;
case NoSsDeviceIcon:
tvins.item.iImage = giNoSsDevice;
tvins.item.iSelectedImage = giNoSsDevice;
break;
case BadDeviceIcon:
default:
tvins.item.iImage = giBadDevice;
tvins.item.iSelectedImage = giBadDevice;
break;
}
TreeView_SetItem(ghTreeWnd, &tvins.item);
return hti;
}
/*****************************************************************************
WalkTreeTopDown()
*****************************************************************************/
VOID
WalkTreeTopDown(
_In_ HTREEITEM hTreeItem,
_In_ LPFNTREECALLBACK lpfnTreeCallback,
_In_opt_ PVOID pContext,
_In_opt_ LPFNTREENOTIFYCALLBACK lpfnTreeNotifyCallback
)
{
if (hTreeItem)
{
HTREEITEM hTreeChild = TreeView_GetChild(ghTreeWnd, hTreeItem);
HTREEITEM hTreeSibling = TreeView_GetNextSibling(ghTreeWnd, hTreeItem);
//
// Call the lpfnCallBack on the node itself.
//
(*lpfnTreeCallback)(ghTreeWnd, hTreeItem, pContext);
//
// Recursively call WalkTree on the node's first child.
//
if (hTreeChild)
{
WalkTreeTopDown(hTreeChild,
lpfnTreeCallback,
pContext,
lpfnTreeNotifyCallback);
}
//
// Recursively call WalkTree on the node's first sibling.
//
if (hTreeSibling)
{
WalkTreeTopDown(hTreeSibling,
lpfnTreeCallback,
pContext,
lpfnTreeNotifyCallback);
}
else
{
// If there are no more siblings, we have reached the end of
// list of child nodes. Call notify function
if (lpfnTreeNotifyCallback != NULL)
{
(*lpfnTreeNotifyCallback)(pContext);
}
}
}
}
/*****************************************************************************
WalkTree()
*****************************************************************************/
VOID
WalkTree (
_In_ HTREEITEM hTreeItem,
_In_ LPFNTREECALLBACK lpfnTreeCallback,
_In_opt_ PVOID pContext
)
{
if (hTreeItem)
{
// Recursively call WalkTree on the node's first child.
//
WalkTree(TreeView_GetChild(ghTreeWnd, hTreeItem),
lpfnTreeCallback,
pContext);
//
// Call the lpfnCallBack on the node itself.
//
(*lpfnTreeCallback)(ghTreeWnd, hTreeItem, pContext);
//
//
// Recursively call WalkTree on the node's first sibling.
//
WalkTree(TreeView_GetNextSibling(ghTreeWnd, hTreeItem),
lpfnTreeCallback,
pContext);
}
}
/*****************************************************************************
ExpandItem()
*****************************************************************************/
VOID
ExpandItem (
HWND hTreeWnd,
HTREEITEM hTreeItem,
PVOID pContext
)
{
//
// Make this node visible.
//
UNREFERENCED_PARAMETER(pContext);
TreeView_Expand(hTreeWnd, hTreeItem, TVE_EXPAND);
}
/*****************************************************************************
SaveAllInformationAsXML()
Saves the entire USB tree as an XML file
*****************************************************************************/
HRESULT
SaveAllInformationAsXml(
LPTSTR lpstrTextFileName,
DWORD dwCreationDisposition
)
{
HRESULT hr = S_OK;
if (ghTreeRoot == NULL)
{
// If tree has not been populated yet, try a refresh
RefreshTree();
}
if (ghTreeRoot)
{
WalkTreeTopDown(ghTreeRoot, AddItemInformationToXmlView, NULL, XmlNotifyEndOfNodeList);
hr = SaveXml(lpstrTextFileName, dwCreationDisposition);
}
else
{
hr = E_FAIL;
OOPS();
}
ResetTextBuffer();
return hr;
}
//*****************************************************************************
//
// AddItemInformationToXmlView
//
// hTreeItem - Handle of selected TreeView item for which information should
// be added to the XML View
//
//*****************************************************************************
VOID
AddItemInformationToXmlView(
HWND hTreeWnd,
HTREEITEM hTreeItem,
PVOID pContext
)
{
TV_ITEM tvi;
PVOID info;
PCHAR tviName = NULL;
UNREFERENCED_PARAMETER(pContext);
#ifdef H264_SUPPORT
ResetErrorCounts();
#endif
tviName = (PCHAR) ALLOC(256);
if (NULL == tviName)
{
return;
}
//
// Get the name of the TreeView item, along with the a pointer to the
// info we stored about the item in the item's lParam.
//
tvi.mask = TVIF_HANDLE | TVIF_TEXT | TVIF_PARAM;
tvi.hItem = hTreeItem;
tvi.pszText = (LPSTR) tviName;
tvi.cchTextMax = 256;
TreeView_GetItem(hTreeWnd,
&tvi);
info = (PVOID)tvi.lParam;
if (NULL != info)
{
//
// Add Item to XML object
//
switch (*(PUSBDEVICEINFOTYPE)info)
{
case HostControllerInfo:
XmlAddHostController(tviName, (PUSBHOSTCONTROLLERINFO) info);
break;
case RootHubInfo:
XmlAddRootHub(tviName, (PUSBROOTHUBINFO) info);
break;
case ExternalHubInfo:
XmlAddExternalHub(tviName, (PUSBEXTERNALHUBINFO) info);
break;
case DeviceInfo:
XmlAddUsbDevice(tviName, (PUSBDEVICEINFO) info);
break;
}
}
return;
}
/*****************************************************************************
DisplayLastError()
*****************************************************************************/
DWORD
DisplayLastError(
_Inout_updates_bytes_(count) char *szString,
int count)
{
LPVOID lpMsgBuf;
// get the last error code
DWORD dwError = GetLastError();
// get the system message for this error code
if (FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dwError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL ))
{
StringCchPrintf(szString, count, "Error: %s", (LPTSTR)lpMsgBuf );
}
// Free the local buffer
LocalFree( lpMsgBuf );
// return the error
return dwError;
}
#if DBG
/*****************************************************************************
Oops()
*****************************************************************************/
VOID
Oops
(
_In_ PCHAR File,
ULONG Line
)
{
char szBuf[1024];
LPTSTR lpMsgBuf;
DWORD dwGLE = GetLastError();
memset(szBuf, 0, sizeof(szBuf));
// get the system message for this error code
if (FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
dwGLE,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL))
{
StringCchPrintf(szBuf, sizeof(szBuf),
"File: %s, Line %d\r\nGetLastError 0x%x %u %s\n",
File, Line, dwGLE, dwGLE, lpMsgBuf);
}
else
{
StringCchPrintf(szBuf, sizeof(szBuf),
"File: %s, Line %d\r\nGetLastError 0x%x %u\r\n",
File, Line, dwGLE, dwGLE);
}
OutputDebugString(szBuf);
// Free the system allocated local buffer
LocalFree(lpMsgBuf);
return;
}
#endif
|
755687.c | #include <linux/module.h>
#include <linux/smp.h>
#include <linux/user.h>
#include <linux/elfcore.h>
#include <linux/sched.h>
#include <linux/in6.h>
#include <linux/interrupt.h>
#include <linux/string.h>
#include <asm/processor.h>
#include <linux/uaccess.h>
#include <asm/checksum.h>
#include <asm/io.h>
#include <asm/delay.h>
#include <asm/irq.h>
#include <asm/tlbflush.h>
#include <asm/pgtable.h>
/* platform dependent support */
EXPORT_SYMBOL(boot_cpu_data);
EXPORT_SYMBOL(dump_fpu);
EXPORT_SYMBOL(__ioremap);
EXPORT_SYMBOL(iounmap);
EXPORT_SYMBOL(strncpy_from_user);
EXPORT_SYMBOL(clear_user);
EXPORT_SYMBOL(__clear_user);
EXPORT_SYMBOL(strnlen_user);
#ifdef CONFIG_SMP
#ifdef CONFIG_CHIP_M32700_TS1
extern void *dcache_dummy;
EXPORT_SYMBOL(dcache_dummy);
#endif
EXPORT_SYMBOL(cpu_data);
/* TLB flushing */
EXPORT_SYMBOL(smp_flush_tlb_page);
#endif
extern int __ucmpdi2(unsigned long long a, unsigned long long b);
EXPORT_SYMBOL(__ucmpdi2);
/* compiler generated symbol */
extern void __ashldi3(void);
extern void __ashrdi3(void);
extern void __lshldi3(void);
extern void __lshrdi3(void);
extern void __muldi3(void);
EXPORT_SYMBOL(__ashldi3);
EXPORT_SYMBOL(__ashrdi3);
EXPORT_SYMBOL(__lshldi3);
EXPORT_SYMBOL(__lshrdi3);
EXPORT_SYMBOL(__muldi3);
/* memory and string operations */
EXPORT_SYMBOL(memcpy);
EXPORT_SYMBOL(memset);
EXPORT_SYMBOL(copy_page);
EXPORT_SYMBOL(clear_page);
EXPORT_SYMBOL(strlen);
EXPORT_SYMBOL(empty_zero_page);
EXPORT_SYMBOL(_inb);
EXPORT_SYMBOL(_inw);
EXPORT_SYMBOL(_inl);
EXPORT_SYMBOL(_outb);
EXPORT_SYMBOL(_outw);
EXPORT_SYMBOL(_outl);
EXPORT_SYMBOL(_inb_p);
EXPORT_SYMBOL(_inw_p);
EXPORT_SYMBOL(_inl_p);
EXPORT_SYMBOL(_outb_p);
EXPORT_SYMBOL(_outw_p);
EXPORT_SYMBOL(_outl_p);
EXPORT_SYMBOL(_insb);
EXPORT_SYMBOL(_insw);
EXPORT_SYMBOL(_insl);
EXPORT_SYMBOL(_outsb);
EXPORT_SYMBOL(_outsw);
EXPORT_SYMBOL(_outsl);
EXPORT_SYMBOL(_readb);
EXPORT_SYMBOL(_readw);
EXPORT_SYMBOL(_readl);
EXPORT_SYMBOL(_writeb);
EXPORT_SYMBOL(_writew);
EXPORT_SYMBOL(_writel);
|
861663.c | #include "iris.h"
#include "action_layer.h"
#include "eeconfig.h"
extern keymap_config_t keymap_config;
#define _QWERTY 0
#define _LOWER 1
#define _RAISE 2
#define _ADJUST 16
enum custom_keycodes {
QWERTY = SAFE_RANGE,
LOWER,
RAISE,
ADJUST,
};
#define KC_ KC_TRNS
#define KC_LOWR LOWER
#define KC_RASE RAISE
#define KC_RST RESET
#define KC_BL_S BL_STEP
#define KC_DBUG DEBUG
#define KC_RTOG RGB_TOG
#define KC_RMOD RGB_MOD
#define KC_RHUI RGB_HUI
#define KC_RHUD RGB_HUD
#define KC_RSAI RGB_SAI
#define KC_RSAD RGB_SAD
#define KC_RVAI RGB_VAI
#define KC_RVAD RGB_VAD
const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = {
[_QWERTY] = LAYOUT_kc(
//,----+----+----+----+----+----. ,----+----+----+----+----+----.
ESC , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 0 ,BSPC,
//|----+----+----+----+----+----| |----+----+----+----+----+----|
TAB , ,COMM,DOT , P , Y , F , G , C , R , L ,DEL ,
//|----+----+----+----+----+----| |----+----+----+----+----+----|
LSFT, A , O , E , U , I , D , H , T , N , S ,INS ,
//|----+----+----+----+----+----+----. ,----|----+----+----+----+----+----|
LCTL,QUOT, Q , J , K , X ,HOME, END , B , M , W , V , Z ,RSFT,
//`----+----+----+--+-+----+----+----/ \----+----+----+----+----+----+----'
LGUI,LOWR,ENT , SPC ,RASE,LALT
// `----+----+----' `----+----+----'
),
[_LOWER] = LAYOUT_kc(
//,----+----+----+----+----+----. ,----+----+----+----+----+----.
TILD,EXLM, AT ,HASH,DLR ,PERC, CIRC,AMPR,ASTR,LPRN,RPRN,BSPC,
//|----+----+----+----+----+----| |----+----+----+----+----+----|
RST , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 0 , ,
//|----+----+----+----+----+----| |----+----+----+----+----+----|
DEL , ,LEFT,RGHT, UP ,LBRC, RBRC, P4 , P5 , P6 ,PLUS,PIPE,
//|----+----+----+----+----+----+----. ,----|----+----+----+----+----+----|
BL_S, , , ,DOWN,LCBR,LPRN, RPRN,RCBR, P1 , P2 , P3 ,MINS, ,
//`----+----+----+--+-+----+----+----/ \----+----+----+----+----+----+----'
, ,DEL , DEL , , P0
// `----+----+----' `----+----+----'
),
[_RAISE] = LAYOUT_kc(
//,----+----+----+----+----+----. ,----+----+----+----+----+----.
F12 , F1 , F2 , F3 , F4 , F5 , F6 , F7 , F8 , F9 ,F10 ,F11 ,
//|----+----+----+----+----+----| |----+----+----+----+----+----|
,EXLM, AT ,HASH,DLR ,PERC, CIRC,AMPR,ASTR,LPRN,RPRN, ,
//|----+----+----+----+----+----| |----+----+----+----+----+----|
,MPRV,MNXT,VOLU,PGUP,UNDS, EQL ,HOME, , , ,BSLS,
//|----+----+----+----+----+----+----. ,----|----+----+----+----+----+----|
MUTE,MSTP,MPLY,VOLD,PGDN,MINS, , ,PLUS,END , , , , ,
//`----+----+----+--+-+----+----+----/ \----+----+----+----+----+----+----'
, , , , ,
// `----+----+----' `----+----+----'
),
[_ADJUST] = LAYOUT_kc(
//,----+----+----+----+----+----. ,----+----+----+----+----+----.
, , , , , , , , , , , ,
//|----+----+----+----+----+----| |----+----+----+----+----+----|
RTOG,RMOD,RHUI,RSAI,RVAI, , , , , , , ,
//|----+----+----+----+----+----| |----+----+----+----+----+----|
,DBUG,RHUD,RSAD,RVAD, , , , , , , ,
//|----+----+----+----+----+----+----. ,----|----+----+----+----+----+----|
BL_S,RST , , , , , , , , , , , , ,
//`----+----+----+--+-+----+----+----/ \----+----+----+----+----+----+----'
, , , , ,
// `----+----+----' `----+----+----'
)
};
void persistent_default_layer_set(uint16_t default_layer) {
eeconfig_update_default_layer(default_layer);
default_layer_set(default_layer);
}
bool process_record_user(uint16_t keycode, keyrecord_t *record) {
switch (keycode) {
case QWERTY:
if (record->event.pressed) {
persistent_default_layer_set(1UL<<_QWERTY);
}
return false;
break;
case LOWER:
if (record->event.pressed) {
layer_on(_LOWER);
update_tri_layer(_LOWER, _RAISE, _ADJUST);
} else {
layer_off(_LOWER);
update_tri_layer(_LOWER, _RAISE, _ADJUST);
}
return false;
break;
case RAISE:
if (record->event.pressed) {
layer_on(_RAISE);
update_tri_layer(_LOWER, _RAISE, _ADJUST);
} else {
layer_off(_RAISE);
update_tri_layer(_LOWER, _RAISE, _ADJUST);
}
return false;
break;
case ADJUST:
if (record->event.pressed) {
layer_on(_ADJUST);
} else {
layer_off(_ADJUST);
}
return false;
break;
}
return true;
}
|
846125.c | // SPDX-License-Identifier: GPL-2.0+
// imx-pcm-fiq.c -- ALSA Soc Audio Layer
//
// Copyright 2009 Sascha Hauer <[email protected]>
//
// This code is based on code copyrighted by Freescale,
// Liam Girdwood, Javier Martin and probably others.
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/dma-mapping.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/dmaengine_pcm.h>
#include <sound/initval.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <asm/fiq.h>
#include <linux/platform_data/asoc-imx-ssi.h>
#include "imx-ssi.h"
#include "imx-pcm.h"
struct imx_pcm_runtime_data {
unsigned int period;
int periods;
unsigned long offset;
struct hrtimer hrt;
int poll_time_ns;
struct snd_pcm_substream *substream;
atomic_t playing;
atomic_t capturing;
};
static enum hrtimer_restart snd_hrtimer_callback(struct hrtimer *hrt)
{
struct imx_pcm_runtime_data *iprtd =
container_of(hrt, struct imx_pcm_runtime_data, hrt);
struct snd_pcm_substream *substream = iprtd->substream;
struct pt_regs regs;
if (!atomic_read(&iprtd->playing) && !atomic_read(&iprtd->capturing))
return HRTIMER_NORESTART;
get_fiq_regs(®s);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
iprtd->offset = regs.ARM_r8 & 0xffff;
else
iprtd->offset = regs.ARM_r9 & 0xffff;
snd_pcm_period_elapsed(substream);
hrtimer_forward_now(hrt, ns_to_ktime(iprtd->poll_time_ns));
return HRTIMER_RESTART;
}
static struct fiq_handler fh = {
.name = DRV_NAME,
};
static int snd_imx_pcm_hw_params(struct snd_soc_component *component,
struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct imx_pcm_runtime_data *iprtd = runtime->private_data;
iprtd->periods = params_periods(params);
iprtd->period = params_period_bytes(params);
iprtd->offset = 0;
iprtd->poll_time_ns = 1000000000 / params_rate(params) *
params_period_size(params);
snd_pcm_set_runtime_buffer(substream, &substream->dma_buffer);
return 0;
}
static int snd_imx_pcm_prepare(struct snd_soc_component *component,
struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct imx_pcm_runtime_data *iprtd = runtime->private_data;
struct pt_regs regs;
get_fiq_regs(®s);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
regs.ARM_r8 = (iprtd->period * iprtd->periods - 1) << 16;
else
regs.ARM_r9 = (iprtd->period * iprtd->periods - 1) << 16;
set_fiq_regs(®s);
return 0;
}
static int imx_pcm_fiq;
static int snd_imx_pcm_trigger(struct snd_soc_component *component,
struct snd_pcm_substream *substream, int cmd)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct imx_pcm_runtime_data *iprtd = runtime->private_data;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
atomic_set(&iprtd->playing, 1);
else
atomic_set(&iprtd->capturing, 1);
hrtimer_start(&iprtd->hrt, ns_to_ktime(iprtd->poll_time_ns),
HRTIMER_MODE_REL);
enable_fiq(imx_pcm_fiq);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
atomic_set(&iprtd->playing, 0);
else
atomic_set(&iprtd->capturing, 0);
if (!atomic_read(&iprtd->playing) &&
!atomic_read(&iprtd->capturing))
disable_fiq(imx_pcm_fiq);
break;
default:
return -EINVAL;
}
return 0;
}
static snd_pcm_uframes_t
snd_imx_pcm_pointer(struct snd_soc_component *component,
struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct imx_pcm_runtime_data *iprtd = runtime->private_data;
return bytes_to_frames(substream->runtime, iprtd->offset);
}
static const struct snd_pcm_hardware snd_imx_hardware = {
.info = SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_PAUSE |
SNDRV_PCM_INFO_RESUME,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.buffer_bytes_max = IMX_SSI_DMABUF_SIZE,
.period_bytes_min = 128,
.period_bytes_max = 16 * 1024,
.periods_min = 4,
.periods_max = 255,
.fifo_size = 0,
};
static int snd_imx_open(struct snd_soc_component *component,
struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct imx_pcm_runtime_data *iprtd;
int ret;
iprtd = kzalloc(sizeof(*iprtd), GFP_KERNEL);
if (iprtd == NULL)
return -ENOMEM;
runtime->private_data = iprtd;
iprtd->substream = substream;
atomic_set(&iprtd->playing, 0);
atomic_set(&iprtd->capturing, 0);
hrtimer_init(&iprtd->hrt, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
iprtd->hrt.function = snd_hrtimer_callback;
ret = snd_pcm_hw_constraint_integer(substream->runtime,
SNDRV_PCM_HW_PARAM_PERIODS);
if (ret < 0) {
kfree(iprtd);
return ret;
}
snd_soc_set_runtime_hwparams(substream, &snd_imx_hardware);
return 0;
}
static int snd_imx_close(struct snd_soc_component *component,
struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct imx_pcm_runtime_data *iprtd = runtime->private_data;
hrtimer_cancel(&iprtd->hrt);
kfree(iprtd);
return 0;
}
static int snd_imx_pcm_mmap(struct snd_soc_component *component,
struct snd_pcm_substream *substream,
struct vm_area_struct *vma)
{
struct snd_pcm_runtime *runtime = substream->runtime;
int ret;
ret = dma_mmap_wc(substream->pcm->card->dev, vma, runtime->dma_area,
runtime->dma_addr, runtime->dma_bytes);
pr_debug("%s: ret: %d %p %pad 0x%08zx\n", __func__, ret,
runtime->dma_area,
&runtime->dma_addr,
runtime->dma_bytes);
return ret;
}
static int imx_pcm_preallocate_dma_buffer(struct snd_pcm *pcm, int stream)
{
struct snd_pcm_substream *substream = pcm->streams[stream].substream;
struct snd_dma_buffer *buf = &substream->dma_buffer;
size_t size = IMX_SSI_DMABUF_SIZE;
buf->dev.type = SNDRV_DMA_TYPE_DEV;
buf->dev.dev = pcm->card->dev;
buf->private_data = NULL;
buf->area = dma_alloc_wc(pcm->card->dev, size, &buf->addr, GFP_KERNEL);
if (!buf->area)
return -ENOMEM;
buf->bytes = size;
return 0;
}
static int imx_pcm_new(struct snd_soc_pcm_runtime *rtd)
{
struct snd_card *card = rtd->card->snd_card;
struct snd_pcm *pcm = rtd->pcm;
int ret;
ret = dma_coerce_mask_and_coherent(card->dev, DMA_BIT_MASK(32));
if (ret)
return ret;
if (pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream) {
ret = imx_pcm_preallocate_dma_buffer(pcm,
SNDRV_PCM_STREAM_PLAYBACK);
if (ret)
return ret;
}
if (pcm->streams[SNDRV_PCM_STREAM_CAPTURE].substream) {
ret = imx_pcm_preallocate_dma_buffer(pcm,
SNDRV_PCM_STREAM_CAPTURE);
if (ret)
return ret;
}
return 0;
}
static int ssi_irq;
static int snd_imx_pcm_new(struct snd_soc_component *component,
struct snd_soc_pcm_runtime *rtd)
{
struct snd_pcm *pcm = rtd->pcm;
struct snd_pcm_substream *substream;
int ret;
ret = imx_pcm_new(rtd);
if (ret)
return ret;
substream = pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream;
if (substream) {
struct snd_dma_buffer *buf = &substream->dma_buffer;
imx_ssi_fiq_tx_buffer = (unsigned long)buf->area;
}
substream = pcm->streams[SNDRV_PCM_STREAM_CAPTURE].substream;
if (substream) {
struct snd_dma_buffer *buf = &substream->dma_buffer;
imx_ssi_fiq_rx_buffer = (unsigned long)buf->area;
}
set_fiq_handler(&imx_ssi_fiq_start,
&imx_ssi_fiq_end - &imx_ssi_fiq_start);
return 0;
}
static void imx_pcm_free(struct snd_pcm *pcm)
{
struct snd_pcm_substream *substream;
struct snd_dma_buffer *buf;
int stream;
for (stream = 0; stream < 2; stream++) {
substream = pcm->streams[stream].substream;
if (!substream)
continue;
buf = &substream->dma_buffer;
if (!buf->area)
continue;
dma_free_wc(pcm->card->dev, buf->bytes, buf->area, buf->addr);
buf->area = NULL;
}
}
static void snd_imx_pcm_free(struct snd_soc_component *component,
struct snd_pcm *pcm)
{
mxc_set_irq_fiq(ssi_irq, 0);
release_fiq(&fh);
imx_pcm_free(pcm);
}
static const struct snd_soc_component_driver imx_soc_component_fiq = {
.open = snd_imx_open,
.close = snd_imx_close,
.hw_params = snd_imx_pcm_hw_params,
.prepare = snd_imx_pcm_prepare,
.trigger = snd_imx_pcm_trigger,
.pointer = snd_imx_pcm_pointer,
.mmap = snd_imx_pcm_mmap,
.pcm_construct = snd_imx_pcm_new,
.pcm_destruct = snd_imx_pcm_free,
};
int imx_pcm_fiq_init(struct platform_device *pdev,
struct imx_pcm_fiq_params *params)
{
int ret;
ret = claim_fiq(&fh);
if (ret) {
dev_err(&pdev->dev, "failed to claim fiq: %d", ret);
return ret;
}
mxc_set_irq_fiq(params->irq, 1);
ssi_irq = params->irq;
imx_pcm_fiq = params->irq;
imx_ssi_fiq_base = (unsigned long)params->base;
params->dma_params_tx->maxburst = 4;
params->dma_params_rx->maxburst = 6;
ret = devm_snd_soc_register_component(&pdev->dev, &imx_soc_component_fiq,
NULL, 0);
if (ret)
goto failed_register;
return 0;
failed_register:
mxc_set_irq_fiq(ssi_irq, 0);
release_fiq(&fh);
return ret;
}
EXPORT_SYMBOL_GPL(imx_pcm_fiq_init);
void imx_pcm_fiq_exit(struct platform_device *pdev)
{
}
EXPORT_SYMBOL_GPL(imx_pcm_fiq_exit);
MODULE_LICENSE("GPL");
|
414299.c |
# define S(M, L, N, R) J(M, P) (L, N, R )
# define QL(L, R)/* L,*/QR(L, /*N,*/ R)//
# define P( L, N, R) L, N, R//
# define LP( L, N, R) U L, D L, (N, R)
# define R( L, R)W (Y(J(E,X)(K(L, R ))))
# define RP( L, N, R)(L, N), H R, T R//
# define HP( L, N, R) L, N, R//
# define K( L, R)/* L,*/J(F, V)(L, R)J \
( Q,sym_ ( K, M ( L, B R))) (L, R )
# define Q( L, R)/* L,*/QR(L, /*N,*/ R)//
# define E( X)E3(X)
# define break H ,
# define E0(/**/X)X
# define I( X, E) K
# define EX(X)E3(X)
#define E1(_I_)E0 (E0(E0(E0(E0(E0(E0 (E0( _I_ ))))))))
#define E2(_O_)E1 (E1(E1(E1(E1(E1(E1 (E1( _O_ ))))))))
#define E3(_C_)E2 (E2(E2(E2(E2(E2(E2 (E2( _C_ ))))))))
#define E4(_C_)E3 (E3(E3(E3(E3(E3(E3 (E3( _C_ ))))))))
#define E5(_C_)E4 (E4(E4(E4(E4(E4(E4 (E4( _C_ ))))))))
#define E6(_2_)E5 (E5(E5(E5(E5(E5(E5 (E5( _2_ ))))))))
#define E7(_0_)E6 (E6(E6(E6(E6(E6(E6 (E6( _0_ ))))))))
#define E8(_1_)E7 (E7(E7(E7(E7(E7(E7 (E7( _1_ ))))))))
#define E9(_5_)E8 (E8(E8(E8(E8(E8(E8 (E8( _5_ ))))))))
#define QS( L, R) (S (M( L, B R),\
A R , A J(G(L, _) ,B R), C R ))
#define QR( L, R) I sym_(,)(O, (C, \
C)) (C J(G(L, _) ,B R),QS(L, R ))
#define sym__(_ , __ ) _
#define A(A, B , C ) A
#define F(A, _) sym_(_,)
#define sym_(__ , _ ) _
#define B(A, B , C ) B
#define J(A, J) G(A, J)
#define sym___( ___, __)
#define C(A, B , C ) C
#define G(J, G) J ## G
#define RY(Y) Y
#define Y( Y) Y
#define LY(Y) Y
# define Z( L, R) J (B L, /*N,*/ Y)
# define N( L, R) J (G(L, _), B R)
# define HY(L ) (A L, halting)
# define T( R, L) G(sym_, R)(L, (,))
# define H( R, L) G(sym_, R)(R, _ )
# define M( L, R) B J( G(L, _), R )
# define D( L, R) G(sym_, R)(R, _ )
# define U( L, R) G(sym_, R)(L, (,))
# define F0(L, R) F( L, /*N,*/R )
# define F1(L, R) F0( L, /*N,*/R)~
# define F2(L, R) F1( L, /*N,*\R)~
# define F3(L,*/R )R\t<L[B R]>\t-> \
Z (/*)*/ N( L, R) , R) (N( L, R) )\n
# define FV(L, R) F( L, /*N,*/R )
# define QH(L, R) QS( L, /*N,*/ R)
int puts (char*);
# define W(W)O(W)
int main () {puts
# define O(W)#W//
( R ( A, tape));}
|
692143.c | /*++
Copyright (c) 1990-1994 Microsoft Corporation
Module Name:
local.c
Abstract:
This module provides all the public exported APIs relating to Printer
and Job management for the Local Print Providor
Author:
Dave Snipp (DaveSn) 15-Mar-1991
Revision History:
16-Jun-1992 JohnRo net print vs. UNICODE.
July 1994 MattFe Caching
--*/
#include "precomp.h"
#define NOTIFY_TIMEOUT 10000
DWORD
LMStartDocPrinter(
HANDLE hPrinter,
DWORD Level,
LPBYTE pDocInfo
)
{
PWSPOOL pSpool=(PWSPOOL)hPrinter;
WCHAR szFileName[MAX_PATH];
PDOC_INFO_1 pDocInfo1=(PDOC_INFO_1)pDocInfo;
QUERY_PRINT_JOB_INFO JobInfo;
IO_STATUS_BLOCK Iosb;
VALIDATEW32HANDLE( pSpool );
if (pSpool->Status) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
pSpool->Status |= WSPOOL_STATUS_STARTDOC;
if(StrNCatBuff(szFileName,
COUNTOF(szFileName),
pSpool->pServer,
L"\\",
pSpool->pShare,
NULL) != ERROR_SUCCESS)
{
return FALSE;
}
pSpool->hFile = CreateFile(szFileName, GENERIC_WRITE, 0, NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL |
FILE_FLAG_SEQUENTIAL_SCAN, NULL);
if (pSpool->hFile == INVALID_HANDLE_VALUE) {
EnterSplSem();
DeleteEntryfromLMCache(pSpool->pServer, pSpool->pShare);
LeaveSplSem();
DBGMSG( DBG_WARNING, ("Failed to open %ws\n", szFileName));
pSpool->Status &= ~WSPOOL_STATUS_STARTDOC;
SetLastError(ERROR_INVALID_NAME);
return FALSE;
}
if (pDocInfo1 && pDocInfo1->pDocName && (wcslen(pDocInfo1->pDocName) < MAX_PATH)) {
if (NtFsControlFile(pSpool->hFile,
NULL,
NULL,
NULL,
&Iosb,
FSCTL_GET_PRINT_ID,
NULL, 0,
&JobInfo, sizeof(JobInfo)) == ERROR_SUCCESS){
RxPrintJobSetInfo(pSpool->pServer,
JobInfo.JobId,
3,
(LPBYTE)pDocInfo1->pDocName,
wcslen(pDocInfo1->pDocName)*sizeof(WCHAR) + sizeof(WCHAR),
PRJ_COMMENT_PARMNUM);
}
else
{
DBGMSG( DBG_WARN, ("NtFsControlFile failed %ws\n", szFileName));
}
}
return TRUE;
}
BOOL
LMStartPagePrinter(
HANDLE hPrinter
)
{
PWSPOOL pSpool = (PWSPOOL)hPrinter;
VALIDATEW32HANDLE( pSpool );
return FALSE;
}
BOOL
LMWritePrinter(
HANDLE hPrinter,
LPVOID pBuf,
DWORD cbBuf,
LPDWORD pcWritten
)
{
PWSPOOL pSpool=(PWSPOOL)hPrinter;
DWORD cWritten, cTotal;
DWORD rc;
LPBYTE pByte=pBuf;
VALIDATEW32HANDLE( pSpool );
if (!(pSpool->Status & WSPOOL_STATUS_STARTDOC)) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
if (pSpool->hFile == INVALID_HANDLE_VALUE) {
*pcWritten = 0;
SetLastError(ERROR_INVALID_HANDLE);
return FALSE;
}
cWritten = cTotal = 0;
while (cbBuf) {
rc = WriteFile(pSpool->hFile, pByte, cbBuf, &cWritten, NULL);
if (!rc) {
rc = GetLastError();
DBGMSG(DBG_WARNING, ("Win32 Spooler: Error writing to server, Error %d\n", rc));
cTotal+=cWritten;
*pcWritten=cTotal;
return FALSE;
} else if (!cWritten) {
DBGMSG(DBG_ERROR, ("Spooler: Amount written is zero !!!\n"));
}
cTotal+=cWritten;
cbBuf-=cWritten;
pByte+=cWritten;
}
*pcWritten = cTotal;
return TRUE;
}
BOOL
LMEndPagePrinter(
HANDLE hPrinter
)
{
PWSPOOL pSpool = (PWSPOOL)hPrinter;
VALIDATEW32HANDLE( pSpool );
return FALSE;
}
BOOL
LMAbortPrinter(
HANDLE hPrinter
)
{
PWSPOOL pSpool=(PWSPOOL)hPrinter;
VALIDATEW32HANDLE( pSpool );
return TRUE;
}
BOOL
LMReadPrinter(
HANDLE hPrinter,
LPVOID pBuf,
DWORD cbBuf,
LPDWORD pNoBytesRead
)
{
PWSPOOL pSpool=(PWSPOOL)hPrinter;
VALIDATEW32HANDLE( pSpool );
return 0;
UNREFERENCED_PARAMETER(pBuf);
UNREFERENCED_PARAMETER(pNoBytesRead);
}
BOOL
LMEndDocPrinter(
HANDLE hPrinter
)
{
PWSPOOL pSpool=(PWSPOOL)hPrinter;
VALIDATEW32HANDLE( pSpool );
if (!(pSpool->Status & WSPOOL_STATUS_STARTDOC)) {
SetLastError(ERROR_INVALID_HANDLE);
return FALSE;
}
pSpool->Status &= ~WSPOOL_STATUS_STARTDOC;
if (pSpool->hFile != INVALID_HANDLE_VALUE) {
CloseHandle(pSpool->hFile);
pSpool->hFile = INVALID_HANDLE_VALUE;
}
return TRUE;
}
BOOL
LMAddJob(
HANDLE hPrinter,
DWORD Level,
LPBYTE pData,
DWORD cbBuf,
LPDWORD pcbNeeded
)
{
PWSPOOL pSpool=(PWSPOOL)hPrinter;
DWORD cb;
WCHAR szFileName[MAX_PATH];
LPBYTE pEnd;
LPADDJOB_INFO_1 pAddJob=(LPADDJOB_INFO_1)pData;
VALIDATEW32HANDLE( pSpool );
if(StrNCatBuff(szFileName,
COUNTOF(szFileName),
pSpool->pServer,
L"\\",
pSpool->pShare,
NULL) != ERROR_SUCCESS)
{
return(FALSE);
}
cb = wcslen(szFileName)*sizeof(WCHAR) + sizeof(WCHAR) + sizeof(ADDJOB_INFO_1);
if (cb > cbBuf) {
*pcbNeeded=cb;
SetLastError(ERROR_INSUFFICIENT_BUFFER);
return(FALSE);
}
pEnd = (LPBYTE)pAddJob+cbBuf;
cb = wcslen(szFileName)*sizeof(WCHAR)+sizeof(WCHAR);
pEnd -= cb;
StringCbCopy((LPWSTR)pEnd, cb, szFileName);
pAddJob->Path = (LPWSTR)pEnd;
pAddJob->JobId = (DWORD)-1;
return TRUE;
}
BOOL
LMScheduleJob(
HANDLE hPrinter,
DWORD JobId
)
{
PWSPOOL pSpool=(PWSPOOL)hPrinter;
VALIDATEW32HANDLE( pSpool );
JobId = JobId;
return TRUE;
}
DWORD
LMGetPrinterData(
HANDLE hPrinter,
LPTSTR pValueName,
LPDWORD pType,
LPBYTE pData,
DWORD nSize,
LPDWORD pcbNeeded
)
{
PWSPOOL pSpool=(PWSPOOL)hPrinter;
VALIDATEW32HANDLE( pSpool );
return FALSE;
}
DWORD
LMSetPrinterData(
HANDLE hPrinter,
LPTSTR pValueName,
DWORD Type,
LPBYTE pData,
DWORD cbData
)
{
PWSPOOL pSpool=(PWSPOOL)hPrinter;
VALIDATEW32HANDLE( pSpool );
return FALSE;
}
BOOL
LMClosePrinter(
HANDLE hPrinter
)
{
PWSPOOL pSpool=(PWSPOOL)hPrinter;
PLMNOTIFY pLMNotify = &pSpool->LMNotify;
BOOL bReturnValue = FALSE;
VALIDATEW32HANDLE( pSpool );
EnterSplSem();
if (pSpool->Status & WSPOOL_STATUS_STARTDOC)
EndDocPrinter(hPrinter);
if (pLMNotify->ChangeEvent) {
if (pLMNotify->ChangeEvent != INVALID_HANDLE_VALUE) {
CloseHandle(pLMNotify->ChangeEvent);
} else {
LMFindClosePrinterChangeNotification(hPrinter);
}
}
bReturnValue = TRUE;
LeaveSplSem();
return bReturnValue;
}
DWORD
LMWaitForPrinterChange(
HANDLE hPrinter,
DWORD Flags
)
{
PWSPOOL pSpool = (PWSPOOL)hPrinter;
PLMNOTIFY pLMNotify = &pSpool->LMNotify;
HANDLE ChangeEvent;
DWORD bReturnValue = FALSE;
EnterSplSem();
if (pLMNotify->ChangeEvent) {
SetLastError(ERROR_ALREADY_WAITING);
goto Error;
}
// Allocate memory for ChangeEvent for LanMan Printers
// This event is pulsed by LMSetJob and any othe LM
// function that modifies the printer/job status
// LMWaitForPrinterChange waits on this event
// being pulsed.
ChangeEvent = CreateEvent(NULL,
FALSE,
FALSE,
NULL);
if (!ChangeEvent) {
DBGMSG(DBG_WARNING, ("CreateEvent( ChangeEvent ) failed: Error %d\n",
GetLastError()));
goto Error;
}
pLMNotify->ChangeEvent = ChangeEvent;
LeaveSplSem();
WaitForSingleObject(pLMNotify->ChangeEvent, NOTIFY_TIMEOUT);
CloseHandle(ChangeEvent);
//
// We shouldn't return that everything changed; we should
// return what did.
//
return Flags;
Error:
LeaveSplSem();
return 0;
}
BOOL
LMFindFirstPrinterChangeNotification(
HANDLE hPrinter,
DWORD fdwFlags,
DWORD fdwOptions,
HANDLE hNotify,
PDWORD pfdwStatus)
{
PWSPOOL pSpool = (PWSPOOL)hPrinter;
PLMNOTIFY pLMNotify = &pSpool->LMNotify;
EnterSplSem();
pLMNotify->hNotify = hNotify;
pLMNotify->fdwChangeFlags = fdwFlags;
pLMNotify->ChangeEvent = INVALID_HANDLE_VALUE;
*pfdwStatus = PRINTER_NOTIFY_STATUS_ENDPOINT | PRINTER_NOTIFY_STATUS_POLL;
LeaveSplSem();
return TRUE;
}
BOOL
LMFindClosePrinterChangeNotification(
HANDLE hPrinter)
{
PWSPOOL pSpool = (PWSPOOL)hPrinter;
PLMNOTIFY pLMNotify = &pSpool->LMNotify;
SplInSem();
if (pLMNotify->ChangeEvent != INVALID_HANDLE_VALUE) {
SetLastError(ERROR_INVALID_HANDLE);
return FALSE;
}
pLMNotify->hNotify = NULL;
pLMNotify->ChangeEvent = NULL;
return TRUE;
}
VOID
LMSetSpoolChange(
PWSPOOL pSpool)
{
PLMNOTIFY pLMNotify;
pLMNotify = &pSpool->LMNotify;
EnterSplSem();
if (pLMNotify->ChangeEvent) {
if (pLMNotify->ChangeEvent == INVALID_HANDLE_VALUE) {
//
// FindFirstPrinterChangeNotification used.
//
ReplyPrinterChangeNotification(pLMNotify->hNotify,
pLMNotify->fdwChangeFlags,
NULL,
NULL);
} else {
SetEvent(pLMNotify->ChangeEvent);
}
}
LeaveSplSem();
}
|
947769.c | /*
* Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
* From ASN.1 module "X2AP-IEs"
* found in "/home/user/openairinterface5g/openair2/X2AP/MESSAGES/ASN1/R14/x2ap-14.6.0.asn1"
* `asn1c -pdu=all -fcompound-names -fno-include-deps -gen-PER -no-gen-OER -no-gen-example -D /home/user/openairinterface5g/cmake_targets/basic_simulator/ue/CMakeFiles/X2AP_R14`
*/
#include "X2AP_UL-InterferenceOverloadIndication.h"
asn_per_constraints_t asn_PER_type_X2AP_UL_InterferenceOverloadIndication_constr_1 CC_NOTUSED = {
{ APC_UNCONSTRAINED, -1, -1, 0, 0 },
{ APC_CONSTRAINED, 7, 7, 1, 110 } /* (SIZE(1..110)) */,
0, 0 /* No PER value map */
};
asn_TYPE_member_t asn_MBR_X2AP_UL_InterferenceOverloadIndication_1[] = {
{ ATF_POINTER, 0, 0,
(ASN_TAG_CLASS_UNIVERSAL | (10 << 2)),
0,
&asn_DEF_X2AP_UL_InterferenceOverloadIndication_Item,
0,
{ 0, 0, 0 },
0, 0, /* No default value */
""
},
};
static const ber_tlv_tag_t asn_DEF_X2AP_UL_InterferenceOverloadIndication_tags_1[] = {
(ASN_TAG_CLASS_UNIVERSAL | (16 << 2))
};
asn_SET_OF_specifics_t asn_SPC_X2AP_UL_InterferenceOverloadIndication_specs_1 = {
sizeof(struct X2AP_UL_InterferenceOverloadIndication),
offsetof(struct X2AP_UL_InterferenceOverloadIndication, _asn_ctx),
1, /* XER encoding is XMLValueList */
};
asn_TYPE_descriptor_t asn_DEF_X2AP_UL_InterferenceOverloadIndication = {
"UL-InterferenceOverloadIndication",
"UL-InterferenceOverloadIndication",
&asn_OP_SEQUENCE_OF,
asn_DEF_X2AP_UL_InterferenceOverloadIndication_tags_1,
sizeof(asn_DEF_X2AP_UL_InterferenceOverloadIndication_tags_1)
/sizeof(asn_DEF_X2AP_UL_InterferenceOverloadIndication_tags_1[0]), /* 1 */
asn_DEF_X2AP_UL_InterferenceOverloadIndication_tags_1, /* Same as above */
sizeof(asn_DEF_X2AP_UL_InterferenceOverloadIndication_tags_1)
/sizeof(asn_DEF_X2AP_UL_InterferenceOverloadIndication_tags_1[0]), /* 1 */
{ 0, &asn_PER_type_X2AP_UL_InterferenceOverloadIndication_constr_1, SEQUENCE_OF_constraint },
asn_MBR_X2AP_UL_InterferenceOverloadIndication_1,
1, /* Single element */
&asn_SPC_X2AP_UL_InterferenceOverloadIndication_specs_1 /* Additional specs */
};
|
888694.c | /* -*- Mode: C; tab-width: 4 -*-
*
* Copyright (c) 2002-2015 Apple Inc. All rights reserved.
*
* 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 "mDNSEmbeddedAPI.h" // Defines the interface provided to the client layer above
#include "DNSCommon.h"
#include "mDNSPosix.h" // Defines the specific types needed to run mDNS on this platform
#include "dns_sd.h"
#include "dnssec.h"
#include "nsec.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <syslog.h>
#include <stdarg.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/uio.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h> // platform support for UTC time
#if USES_NETLINK
#include <asm/types.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#else // USES_NETLINK
#include <net/route.h>
#include <net/if.h>
#endif // USES_NETLINK
#include "mDNSUNP.h"
#include "GenLinkedList.h"
// ***************************************************************************
// Structures
// We keep a list of client-supplied event sources in PosixEventSource records
struct PosixEventSource
{
mDNSPosixEventCallback Callback;
void *Context;
int fd;
struct PosixEventSource *Next;
};
typedef struct PosixEventSource PosixEventSource;
// Context record for interface change callback
struct IfChangeRec
{
int NotifySD;
mDNS *mDNS;
};
typedef struct IfChangeRec IfChangeRec;
// Note that static data is initialized to zero in (modern) C.
static fd_set gEventFDs;
static int gMaxFD; // largest fd in gEventFDs
static GenLinkedList gEventSources; // linked list of PosixEventSource's
static sigset_t gEventSignalSet; // Signals which event loop listens for
static sigset_t gEventSignals; // Signals which were received while inside loop
static PosixNetworkInterface *gRecentInterfaces;
// ***************************************************************************
// Globals (for debugging)
static int num_registered_interfaces = 0;
static int num_pkts_accepted = 0;
static int num_pkts_rejected = 0;
// ***************************************************************************
// Functions
int gMDNSPlatformPosixVerboseLevel = 0;
#define PosixErrorToStatus(errNum) ((errNum) == 0 ? mStatus_NoError : mStatus_UnknownErr)
mDNSlocal void SockAddrTomDNSAddr(const struct sockaddr *const sa, mDNSAddr *ipAddr, mDNSIPPort *ipPort)
{
switch (sa->sa_family)
{
case AF_INET:
{
struct sockaddr_in *sin = (struct sockaddr_in*)sa;
ipAddr->type = mDNSAddrType_IPv4;
ipAddr->ip.v4.NotAnInteger = sin->sin_addr.s_addr;
if (ipPort) ipPort->NotAnInteger = sin->sin_port;
break;
}
#if HAVE_IPV6
case AF_INET6:
{
struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)sa;
#ifndef NOT_HAVE_SA_LEN
assert(sin6->sin6_len == sizeof(*sin6));
#endif
ipAddr->type = mDNSAddrType_IPv6;
ipAddr->ip.v6 = *(mDNSv6Addr*)&sin6->sin6_addr;
if (ipPort) ipPort->NotAnInteger = sin6->sin6_port;
break;
}
#endif
default:
verbosedebugf("SockAddrTomDNSAddr: Uknown address family %d\n", sa->sa_family);
ipAddr->type = mDNSAddrType_None;
if (ipPort) ipPort->NotAnInteger = 0;
break;
}
}
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark ***** Send and Receive
#endif
// mDNS core calls this routine when it needs to send a packet.
mDNSexport mStatus mDNSPlatformSendUDP(const mDNS *const m, const void *const msg, const mDNSu8 *const end,
mDNSInterfaceID InterfaceID, UDPSocket *src, const mDNSAddr *dst,
mDNSIPPort dstPort, mDNSBool useBackgroundTrafficClass)
{
int err = 0;
struct sockaddr_storage to;
PosixNetworkInterface * thisIntf = (PosixNetworkInterface *)(InterfaceID);
int sendingsocket = -1;
(void)src; // Will need to use this parameter once we implement mDNSPlatformUDPSocket/mDNSPlatformUDPClose
(void) useBackgroundTrafficClass;
assert(m != NULL);
assert(msg != NULL);
assert(end != NULL);
assert((((char *) end) - ((char *) msg)) > 0);
if (dstPort.NotAnInteger == 0)
{
LogMsg("mDNSPlatformSendUDP: Invalid argument -dstPort is set to 0");
return PosixErrorToStatus(EINVAL);
}
if (dst->type == mDNSAddrType_IPv4)
{
struct sockaddr_in *sin = (struct sockaddr_in*)&to;
#ifndef NOT_HAVE_SA_LEN
sin->sin_len = sizeof(*sin);
#endif
sin->sin_family = AF_INET;
sin->sin_port = dstPort.NotAnInteger;
sin->sin_addr.s_addr = dst->ip.v4.NotAnInteger;
sendingsocket = thisIntf ? thisIntf->multicastSocket4 : m->p->unicastSocket4;
}
#if HAVE_IPV6
else if (dst->type == mDNSAddrType_IPv6)
{
struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&to;
mDNSPlatformMemZero(sin6, sizeof(*sin6));
#ifndef NOT_HAVE_SA_LEN
sin6->sin6_len = sizeof(*sin6);
#endif
sin6->sin6_family = AF_INET6;
sin6->sin6_port = dstPort.NotAnInteger;
sin6->sin6_addr = *(struct in6_addr*)&dst->ip.v6;
sendingsocket = thisIntf ? thisIntf->multicastSocket6 : m->p->unicastSocket6;
}
#endif
if (sendingsocket >= 0)
err = sendto(sendingsocket, msg, (char*)end - (char*)msg, 0, (struct sockaddr *)&to, GET_SA_LEN(to));
if (err > 0) err = 0;
else if (err < 0)
{
static int MessageCount = 0;
// Don't report EHOSTDOWN (i.e. ARP failure), ENETDOWN, or no route to host for unicast destinations
if (!mDNSAddressIsAllDNSLinkGroup(dst))
if (errno == EHOSTDOWN || errno == ENETDOWN || errno == EHOSTUNREACH || errno == ENETUNREACH) return(mStatus_TransientErr);
if (MessageCount < 1000)
{
MessageCount++;
if (thisIntf)
LogMsg("mDNSPlatformSendUDP got error %d (%s) sending packet to %#a on interface %#a/%s/%d",
errno, strerror(errno), dst, &thisIntf->coreIntf.ip, thisIntf->intfName, thisIntf->index);
else
LogMsg("mDNSPlatformSendUDP got error %d (%s) sending packet to %#a", errno, strerror(errno), dst);
}
}
return PosixErrorToStatus(err);
}
// This routine is called when the main loop detects that data is available on a socket.
mDNSlocal void SocketDataReady(mDNS *const m, PosixNetworkInterface *intf, int skt)
{
mDNSAddr senderAddr, destAddr;
mDNSIPPort senderPort;
ssize_t packetLen;
DNSMessage packet;
struct my_in_pktinfo packetInfo;
struct sockaddr_storage from;
socklen_t fromLen;
int flags;
mDNSu8 ttl;
mDNSBool reject;
const mDNSInterfaceID InterfaceID = intf ? intf->coreIntf.InterfaceID : NULL;
assert(m != NULL);
assert(skt >= 0);
fromLen = sizeof(from);
flags = 0;
packetLen = recvfrom_flags(skt, &packet, sizeof(packet), &flags, (struct sockaddr *) &from, &fromLen, &packetInfo, &ttl);
if (packetLen >= 0)
{
SockAddrTomDNSAddr((struct sockaddr*)&from, &senderAddr, &senderPort);
SockAddrTomDNSAddr((struct sockaddr*)&packetInfo.ipi_addr, &destAddr, NULL);
// If we have broken IP_RECVDSTADDR functionality (so far
// I've only seen this on OpenBSD) then apply a hack to
// convince mDNS Core that this isn't a spoof packet.
// Basically what we do is check to see whether the
// packet arrived as a multicast and, if so, set its
// destAddr to the mDNS address.
//
// I must admit that I could just be doing something
// wrong on OpenBSD and hence triggering this problem
// but I'm at a loss as to how.
//
// If this platform doesn't have IP_PKTINFO or IP_RECVDSTADDR, then we have
// no way to tell the destination address or interface this packet arrived on,
// so all we can do is just assume it's a multicast
#if HAVE_BROKEN_RECVDSTADDR || (!defined(IP_PKTINFO) && !defined(IP_RECVDSTADDR))
if ((destAddr.NotAnInteger == 0) && (flags & MSG_MCAST))
{
destAddr.type = senderAddr.type;
if (senderAddr.type == mDNSAddrType_IPv4) destAddr.ip.v4 = AllDNSLinkGroup_v4.ip.v4;
else if (senderAddr.type == mDNSAddrType_IPv6) destAddr.ip.v6 = AllDNSLinkGroup_v6.ip.v6;
}
#endif
// We only accept the packet if the interface on which it came
// in matches the interface associated with this socket.
// We do this match by name or by index, depending on which
// information is available. recvfrom_flags sets the name
// to "" if the name isn't available, or the index to -1
// if the index is available. This accomodates the various
// different capabilities of our target platforms.
reject = mDNSfalse;
if (!intf)
{
// Ignore multicasts accidentally delivered to our unicast receiving socket
if (mDNSAddrIsDNSMulticast(&destAddr)) packetLen = -1;
}
else
{
if (packetInfo.ipi_ifname[0] != 0) reject = (strcmp(packetInfo.ipi_ifname, intf->intfName) != 0);
else if (packetInfo.ipi_ifindex != -1) reject = (packetInfo.ipi_ifindex != intf->index);
if (reject)
{
verbosedebugf("SocketDataReady ignored a packet from %#a to %#a on interface %s/%d expecting %#a/%s/%d/%d",
&senderAddr, &destAddr, packetInfo.ipi_ifname, packetInfo.ipi_ifindex,
&intf->coreIntf.ip, intf->intfName, intf->index, skt);
packetLen = -1;
num_pkts_rejected++;
if (num_pkts_rejected > (num_pkts_accepted + 1) * (num_registered_interfaces + 1) * 2)
{
fprintf(stderr,
"*** WARNING: Received %d packets; Accepted %d packets; Rejected %d packets because of interface mismatch\n",
num_pkts_accepted + num_pkts_rejected, num_pkts_accepted, num_pkts_rejected);
num_pkts_accepted = 0;
num_pkts_rejected = 0;
}
}
else
{
verbosedebugf("SocketDataReady got a packet from %#a to %#a on interface %#a/%s/%d/%d",
&senderAddr, &destAddr, &intf->coreIntf.ip, intf->intfName, intf->index, skt);
num_pkts_accepted++;
}
}
}
if (packetLen >= 0)
mDNSCoreReceive(m, &packet, (mDNSu8 *)&packet + packetLen,
&senderAddr, senderPort, &destAddr, MulticastDNSPort, InterfaceID);
}
mDNSexport TCPSocket *mDNSPlatformTCPSocket(mDNS * const m, TCPSocketFlags flags, mDNSIPPort * port, mDNSBool useBackgroundTrafficClass)
{
(void)m; // Unused
(void)flags; // Unused
(void)port; // Unused
(void)useBackgroundTrafficClass; // Unused
return NULL;
}
mDNSexport TCPSocket *mDNSPlatformTCPAccept(TCPSocketFlags flags, int sd)
{
(void)flags; // Unused
(void)sd; // Unused
return NULL;
}
mDNSexport int mDNSPlatformTCPGetFD(TCPSocket *sock)
{
(void)sock; // Unused
return -1;
}
mDNSexport mStatus mDNSPlatformTCPConnect(TCPSocket *sock, const mDNSAddr *dst, mDNSOpaque16 dstport, domainname *hostname, mDNSInterfaceID InterfaceID,
TCPConnectionCallback callback, void *context)
{
(void)sock; // Unused
(void)dst; // Unused
(void)dstport; // Unused
(void)hostname; // Unused
(void)InterfaceID; // Unused
(void)callback; // Unused
(void)context; // Unused
return(mStatus_UnsupportedErr);
}
mDNSexport void mDNSPlatformTCPCloseConnection(TCPSocket *sock)
{
(void)sock; // Unused
}
mDNSexport long mDNSPlatformReadTCP(TCPSocket *sock, void *buf, unsigned long buflen, mDNSBool * closed)
{
(void)sock; // Unused
(void)buf; // Unused
(void)buflen; // Unused
(void)closed; // Unused
return 0;
}
mDNSexport long mDNSPlatformWriteTCP(TCPSocket *sock, const char *msg, unsigned long len)
{
(void)sock; // Unused
(void)msg; // Unused
(void)len; // Unused
return 0;
}
mDNSexport UDPSocket *mDNSPlatformUDPSocket(mDNS * const m, mDNSIPPort port)
{
(void)m; // Unused
(void)port; // Unused
return NULL;
}
mDNSexport void mDNSPlatformUDPClose(UDPSocket *sock)
{
(void)sock; // Unused
}
mDNSexport void mDNSPlatformUpdateProxyList(mDNS *const m, const mDNSInterfaceID InterfaceID)
{
(void)m; // Unused
(void)InterfaceID; // Unused
}
mDNSexport void mDNSPlatformSendRawPacket(const void *const msg, const mDNSu8 *const end, mDNSInterfaceID InterfaceID)
{
(void)msg; // Unused
(void)end; // Unused
(void)InterfaceID; // Unused
}
mDNSexport void mDNSPlatformSetLocalAddressCacheEntry(mDNS *const m, const mDNSAddr *const tpa, const mDNSEthAddr *const tha, mDNSInterfaceID InterfaceID)
{
(void)m; // Unused
(void)tpa; // Unused
(void)tha; // Unused
(void)InterfaceID; // Unused
}
mDNSexport mStatus mDNSPlatformTLSSetupCerts(void)
{
return(mStatus_UnsupportedErr);
}
mDNSexport void mDNSPlatformTLSTearDownCerts(void)
{
}
mDNSexport void mDNSPlatformSetAllowSleep(mDNS *const m, mDNSBool allowSleep, const char *reason)
{
(void) m;
(void) allowSleep;
(void) reason;
}
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark -
#pragma mark - /etc/hosts support
#endif
mDNSexport void FreeEtcHosts(mDNS *const m, AuthRecord *const rr, mStatus result)
{
(void)m; // unused
(void)rr;
(void)result;
}
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark ***** DDNS Config Platform Functions
#endif
mDNSexport mDNSBool mDNSPlatformSetDNSConfig(mDNS *const m, mDNSBool setservers, mDNSBool setsearch, domainname *const fqdn, DNameListElem **RegDomains,
DNameListElem **BrowseDomains, mDNSBool ackConfig)
{
(void) m;
(void) setservers;
(void) fqdn;
(void) setsearch;
(void) RegDomains;
(void) BrowseDomains;
(void) ackConfig;
return mDNStrue;
}
mDNSexport mStatus mDNSPlatformGetPrimaryInterface(mDNS * const m, mDNSAddr * v4, mDNSAddr * v6, mDNSAddr * router)
{
(void) m;
(void) v4;
(void) v6;
(void) router;
return mStatus_UnsupportedErr;
}
mDNSexport void mDNSPlatformDynDNSHostNameStatusChanged(const domainname *const dname, const mStatus status)
{
(void) dname;
(void) status;
}
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark ***** Init and Term
#endif
// This gets the current hostname, truncating it at the first dot if necessary
mDNSlocal void GetUserSpecifiedRFC1034ComputerName(domainlabel *const namelabel)
{
int len = 0;
gethostname((char *)(&namelabel->c[1]), MAX_DOMAIN_LABEL);
while (len < MAX_DOMAIN_LABEL && namelabel->c[len+1] && namelabel->c[len+1] != '.') len++;
namelabel->c[0] = len;
}
// On OS X this gets the text of the field labelled "Computer Name" in the Sharing Prefs Control Panel
// Other platforms can either get the information from the appropriate place,
// or they can alternatively just require all registering services to provide an explicit name
mDNSlocal void GetUserSpecifiedFriendlyComputerName(domainlabel *const namelabel)
{
// On Unix we have no better name than the host name, so we just use that.
GetUserSpecifiedRFC1034ComputerName(namelabel);
}
mDNSexport int ParseDNSServers(mDNS *m, const char *filePath)
{
char line[256];
char nameserver[16];
char keyword[11];
int numOfServers = 0;
FILE *fp = fopen(filePath, "r");
if (fp == NULL) return -1;
while (fgets(line,sizeof(line),fp))
{
struct in_addr ina;
line[255]='\0'; // just to be safe
if (sscanf(line,"%10s %15s", keyword, nameserver) != 2) continue; // it will skip whitespaces
if (strncasecmp(keyword,"nameserver",10)) continue;
if (inet_aton(nameserver, (struct in_addr *)&ina) != 0)
{
mDNSAddr DNSAddr;
DNSAddr.type = mDNSAddrType_IPv4;
DNSAddr.ip.v4.NotAnInteger = ina.s_addr;
mDNS_AddDNSServer(m, NULL, mDNSInterface_Any, 0, &DNSAddr, UnicastDNSPort, kScopeNone, 0, mDNSfalse, 0, mDNStrue, mDNStrue, mDNSfalse);
numOfServers++;
}
}
fclose(fp);
return (numOfServers > 0) ? 0 : -1;
}
// Searches the interface list looking for the named interface.
// Returns a pointer to if it found, or NULL otherwise.
mDNSlocal PosixNetworkInterface *SearchForInterfaceByName(mDNS *const m, const char *intfName)
{
PosixNetworkInterface *intf;
assert(m != NULL);
assert(intfName != NULL);
intf = (PosixNetworkInterface*)(m->HostInterfaces);
while ((intf != NULL) && (strcmp(intf->intfName, intfName) != 0))
intf = (PosixNetworkInterface *)(intf->coreIntf.next);
return intf;
}
mDNSexport mDNSInterfaceID mDNSPlatformInterfaceIDfromInterfaceIndex(mDNS *const m, mDNSu32 index)
{
PosixNetworkInterface *intf;
assert(m != NULL);
if (index == kDNSServiceInterfaceIndexLocalOnly) return(mDNSInterface_LocalOnly);
if (index == kDNSServiceInterfaceIndexP2P ) return(mDNSInterface_P2P);
if (index == kDNSServiceInterfaceIndexAny ) return(mDNSInterface_Any);
intf = (PosixNetworkInterface*)(m->HostInterfaces);
while ((intf != NULL) && (mDNSu32) intf->index != index)
intf = (PosixNetworkInterface *)(intf->coreIntf.next);
return (mDNSInterfaceID) intf;
}
mDNSexport mDNSu32 mDNSPlatformInterfaceIndexfromInterfaceID(mDNS *const m, mDNSInterfaceID id, mDNSBool suppressNetworkChange)
{
PosixNetworkInterface *intf;
(void) suppressNetworkChange; // Unused
assert(m != NULL);
if (id == mDNSInterface_LocalOnly) return(kDNSServiceInterfaceIndexLocalOnly);
if (id == mDNSInterface_P2P ) return(kDNSServiceInterfaceIndexP2P);
if (id == mDNSInterface_Any ) return(kDNSServiceInterfaceIndexAny);
intf = (PosixNetworkInterface*)(m->HostInterfaces);
while ((intf != NULL) && (mDNSInterfaceID) intf != id)
intf = (PosixNetworkInterface *)(intf->coreIntf.next);
if (intf) return intf->index;
// If we didn't find the interface, check the RecentInterfaces list as well
intf = gRecentInterfaces;
while ((intf != NULL) && (mDNSInterfaceID) intf != id)
intf = (PosixNetworkInterface *)(intf->coreIntf.next);
return intf ? intf->index : 0;
}
// Frees the specified PosixNetworkInterface structure. The underlying
// interface must have already been deregistered with the mDNS core.
mDNSlocal void FreePosixNetworkInterface(PosixNetworkInterface *intf)
{
int rv;
assert(intf != NULL);
if (intf->intfName != NULL) free((void *)intf->intfName);
if (intf->multicastSocket4 != -1)
{
rv = close(intf->multicastSocket4);
assert(rv == 0);
}
#if HAVE_IPV6
if (intf->multicastSocket6 != -1)
{
rv = close(intf->multicastSocket6);
assert(rv == 0);
}
#endif
// Move interface to the RecentInterfaces list for a minute
intf->LastSeen = mDNSPlatformUTC();
intf->coreIntf.next = &gRecentInterfaces->coreIntf;
gRecentInterfaces = intf;
}
// Grab the first interface, deregister it, free it, and repeat until done.
mDNSlocal void ClearInterfaceList(mDNS *const m)
{
assert(m != NULL);
while (m->HostInterfaces)
{
PosixNetworkInterface *intf = (PosixNetworkInterface*)(m->HostInterfaces);
mDNS_DeregisterInterface(m, &intf->coreIntf, mDNSfalse);
if (gMDNSPlatformPosixVerboseLevel > 0) fprintf(stderr, "Deregistered interface %s\n", intf->intfName);
FreePosixNetworkInterface(intf);
}
num_registered_interfaces = 0;
num_pkts_accepted = 0;
num_pkts_rejected = 0;
}
// Sets up a send/receive socket.
// If mDNSIPPort port is non-zero, then it's a multicast socket on the specified interface
// If mDNSIPPort port is zero, then it's a randomly assigned port number, used for sending unicast queries
mDNSlocal int SetupSocket(struct sockaddr *intfAddr, mDNSIPPort port, int interfaceIndex, int *sktPtr)
{
int err = 0;
static const int kOn = 1;
static const int kIntTwoFiveFive = 255;
static const unsigned char kByteTwoFiveFive = 255;
const mDNSBool JoinMulticastGroup = (port.NotAnInteger != 0);
(void) interfaceIndex; // This parameter unused on plaforms that don't have IPv6
assert(intfAddr != NULL);
assert(sktPtr != NULL);
assert(*sktPtr == -1);
// Open the socket...
if (intfAddr->sa_family == AF_INET) *sktPtr = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
#if HAVE_IPV6
else if (intfAddr->sa_family == AF_INET6) *sktPtr = socket(PF_INET6, SOCK_DGRAM, IPPROTO_UDP);
#endif
else return EINVAL;
if (*sktPtr < 0) { err = errno; perror((intfAddr->sa_family == AF_INET) ? "socket AF_INET" : "socket AF_INET6"); }
// ... with a shared UDP port, if it's for multicast receiving
if (err == 0 && port.NotAnInteger)
{
// <rdar://problem/20946253>
// We test for SO_REUSEADDR first, as suggested by Jonny Törnbom from Axis Communications
// Linux kernel versions 3.9 introduces support for socket option
// SO_REUSEPORT, however this is not implemented the same as on *BSD
// systems. Linux version implements a "port hijacking" prevention
// mechanism, limiting processes wanting to bind to an already existing
// addr:port to have the same effective UID as the first who bound it. What
// this meant for us was that the daemon ran as one user and when for
// instance mDNSClientPosix was executed by another user, it wasn't allowed
// to bind to the socket. Our suggestion was to switch the order in which
// SO_REUSEPORT and SO_REUSEADDR was tested so that SO_REUSEADDR stays on
// top and SO_REUSEPORT to be used only if SO_REUSEADDR doesn't exist.
#if defined(SO_REUSEADDR) && !defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
err = setsockopt(*sktPtr, SOL_SOCKET, SO_REUSEADDR, &kOn, sizeof(kOn));
#elif defined(SO_REUSEPORT)
err = setsockopt(*sktPtr, SOL_SOCKET, SO_REUSEPORT, &kOn, sizeof(kOn));
#else
#error This platform has no way to avoid address busy errors on multicast.
#endif
if (err < 0) { err = errno; perror("setsockopt - SO_REUSExxxx"); }
// Enable inbound packets on IFEF_AWDL interface.
// Only done for multicast sockets, since we don't expect unicast socket operations
// on the IFEF_AWDL interface. Operation is a no-op for other interface types.
#ifndef SO_RECV_ANYIF
#define SO_RECV_ANYIF 0x1104 /* unrestricted inbound processing */
#endif
if (setsockopt(*sktPtr, SOL_SOCKET, SO_RECV_ANYIF, &kOn, sizeof(kOn)) < 0) perror("setsockopt - SO_RECV_ANYIF");
}
// We want to receive destination addresses and interface identifiers.
if (intfAddr->sa_family == AF_INET)
{
struct ip_mreq imr;
struct sockaddr_in bindAddr;
if (err == 0)
{
#if defined(IP_PKTINFO) // Linux
err = setsockopt(*sktPtr, IPPROTO_IP, IP_PKTINFO, &kOn, sizeof(kOn));
if (err < 0) { err = errno; perror("setsockopt - IP_PKTINFO"); }
#elif defined(IP_RECVDSTADDR) || defined(IP_RECVIF) // BSD and Solaris
#if defined(IP_RECVDSTADDR)
err = setsockopt(*sktPtr, IPPROTO_IP, IP_RECVDSTADDR, &kOn, sizeof(kOn));
if (err < 0) { err = errno; perror("setsockopt - IP_RECVDSTADDR"); }
#endif
#if defined(IP_RECVIF)
if (err == 0)
{
err = setsockopt(*sktPtr, IPPROTO_IP, IP_RECVIF, &kOn, sizeof(kOn));
if (err < 0) { err = errno; perror("setsockopt - IP_RECVIF"); }
}
#endif
#else
#warning This platform has no way to get the destination interface information -- will only work for single-homed hosts
#endif
}
#if defined(IP_RECVTTL) // Linux
if (err == 0)
{
setsockopt(*sktPtr, IPPROTO_IP, IP_RECVTTL, &kOn, sizeof(kOn));
// We no longer depend on being able to get the received TTL, so don't worry if the option fails
}
#endif
// Add multicast group membership on this interface
if (err == 0 && JoinMulticastGroup)
{
imr.imr_multiaddr.s_addr = AllDNSLinkGroup_v4.ip.v4.NotAnInteger;
imr.imr_interface = ((struct sockaddr_in*)intfAddr)->sin_addr;
err = setsockopt(*sktPtr, IPPROTO_IP, IP_ADD_MEMBERSHIP, &imr, sizeof(imr));
if (err < 0) { err = errno; perror("setsockopt - IP_ADD_MEMBERSHIP"); }
}
// Specify outgoing interface too
if (err == 0 && JoinMulticastGroup)
{
err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_IF, &((struct sockaddr_in*)intfAddr)->sin_addr, sizeof(struct in_addr));
if (err < 0) { err = errno; perror("setsockopt - IP_MULTICAST_IF"); }
}
// Per the mDNS spec, send unicast packets with TTL 255
if (err == 0)
{
err = setsockopt(*sktPtr, IPPROTO_IP, IP_TTL, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
if (err < 0) { err = errno; perror("setsockopt - IP_TTL"); }
}
// and multicast packets with TTL 255 too
// There's some debate as to whether IP_MULTICAST_TTL is an int or a byte so we just try both.
if (err == 0)
{
err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_TTL, &kByteTwoFiveFive, sizeof(kByteTwoFiveFive));
if (err < 0 && errno == EINVAL)
err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_TTL, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
if (err < 0) { err = errno; perror("setsockopt - IP_MULTICAST_TTL"); }
}
// And start listening for packets
if (err == 0)
{
bindAddr.sin_family = AF_INET;
bindAddr.sin_port = port.NotAnInteger;
bindAddr.sin_addr.s_addr = INADDR_ANY; // Want to receive multicasts AND unicasts on this socket
err = bind(*sktPtr, (struct sockaddr *) &bindAddr, sizeof(bindAddr));
if (err < 0) { err = errno; perror("bind"); fflush(stderr); }
}
} // endif (intfAddr->sa_family == AF_INET)
#if HAVE_IPV6
else if (intfAddr->sa_family == AF_INET6)
{
struct ipv6_mreq imr6;
struct sockaddr_in6 bindAddr6;
#if defined(IPV6_PKTINFO)
if (err == 0)
{
err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_2292_PKTINFO, &kOn, sizeof(kOn));
if (err < 0) { err = errno; perror("setsockopt - IPV6_PKTINFO"); }
}
#else
#warning This platform has no way to get the destination interface information for IPv6 -- will only work for single-homed hosts
#endif
#if defined(IPV6_HOPLIMIT)
if (err == 0)
{
err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_2292_HOPLIMIT, &kOn, sizeof(kOn));
if (err < 0) { err = errno; perror("setsockopt - IPV6_HOPLIMIT"); }
}
#endif
// Add multicast group membership on this interface
if (err == 0 && JoinMulticastGroup)
{
imr6.ipv6mr_multiaddr = *(const struct in6_addr*)&AllDNSLinkGroup_v6.ip.v6;
imr6.ipv6mr_interface = interfaceIndex;
//LogMsg("Joining %.16a on %d", &imr6.ipv6mr_multiaddr, imr6.ipv6mr_interface);
err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_JOIN_GROUP, &imr6, sizeof(imr6));
if (err < 0)
{
err = errno;
verbosedebugf("IPV6_JOIN_GROUP %.16a on %d failed.\n", &imr6.ipv6mr_multiaddr, imr6.ipv6mr_interface);
perror("setsockopt - IPV6_JOIN_GROUP");
}
}
// Specify outgoing interface too
if (err == 0 && JoinMulticastGroup)
{
u_int multicast_if = interfaceIndex;
err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_IF, &multicast_if, sizeof(multicast_if));
if (err < 0) { err = errno; perror("setsockopt - IPV6_MULTICAST_IF"); }
}
// We want to receive only IPv6 packets on this socket.
// Without this option, we may get IPv4 addresses as mapped addresses.
if (err == 0)
{
err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_V6ONLY, &kOn, sizeof(kOn));
if (err < 0) { err = errno; perror("setsockopt - IPV6_V6ONLY"); }
}
// Per the mDNS spec, send unicast packets with TTL 255
if (err == 0)
{
err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
if (err < 0) { err = errno; perror("setsockopt - IPV6_UNICAST_HOPS"); }
}
// and multicast packets with TTL 255 too
// There's some debate as to whether IPV6_MULTICAST_HOPS is an int or a byte so we just try both.
if (err == 0)
{
err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &kByteTwoFiveFive, sizeof(kByteTwoFiveFive));
if (err < 0 && errno == EINVAL)
err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
if (err < 0) { err = errno; perror("setsockopt - IPV6_MULTICAST_HOPS"); }
}
// And start listening for packets
if (err == 0)
{
mDNSPlatformMemZero(&bindAddr6, sizeof(bindAddr6));
#ifndef NOT_HAVE_SA_LEN
bindAddr6.sin6_len = sizeof(bindAddr6);
#endif
bindAddr6.sin6_family = AF_INET6;
bindAddr6.sin6_port = port.NotAnInteger;
bindAddr6.sin6_flowinfo = 0;
bindAddr6.sin6_addr = in6addr_any; // Want to receive multicasts AND unicasts on this socket
bindAddr6.sin6_scope_id = 0;
err = bind(*sktPtr, (struct sockaddr *) &bindAddr6, sizeof(bindAddr6));
if (err < 0) { err = errno; perror("bind"); fflush(stderr); }
}
} // endif (intfAddr->sa_family == AF_INET6)
#endif
// Set the socket to non-blocking.
if (err == 0)
{
err = fcntl(*sktPtr, F_GETFL, 0);
if (err < 0) err = errno;
else
{
err = fcntl(*sktPtr, F_SETFL, err | O_NONBLOCK);
if (err < 0) err = errno;
}
}
// Clean up
if (err != 0 && *sktPtr != -1)
{
int rv;
rv = close(*sktPtr);
assert(rv == 0);
*sktPtr = -1;
}
assert((err == 0) == (*sktPtr != -1));
return err;
}
// Creates a PosixNetworkInterface for the interface whose IP address is
// intfAddr and whose name is intfName and registers it with mDNS core.
mDNSlocal int SetupOneInterface(mDNS *const m, struct sockaddr *intfAddr, struct sockaddr *intfMask, const char *intfName, int intfIndex)
{
int err = 0;
PosixNetworkInterface *intf;
PosixNetworkInterface *alias = NULL;
assert(m != NULL);
assert(intfAddr != NULL);
assert(intfName != NULL);
assert(intfMask != NULL);
// Allocate the interface structure itself.
intf = (PosixNetworkInterface*)calloc(1, sizeof(*intf));
if (intf == NULL) { assert(0); err = ENOMEM; }
// And make a copy of the intfName.
if (err == 0)
{
intf->intfName = strdup(intfName);
if (intf->intfName == NULL) { assert(0); err = ENOMEM; }
}
if (err == 0)
{
// Set up the fields required by the mDNS core.
SockAddrTomDNSAddr(intfAddr, &intf->coreIntf.ip, NULL);
SockAddrTomDNSAddr(intfMask, &intf->coreIntf.mask, NULL);
//LogMsg("SetupOneInterface: %#a %#a", &intf->coreIntf.ip, &intf->coreIntf.mask);
strncpy(intf->coreIntf.ifname, intfName, sizeof(intf->coreIntf.ifname));
intf->coreIntf.ifname[sizeof(intf->coreIntf.ifname)-1] = 0;
intf->coreIntf.Advertise = m->AdvertiseLocalAddresses;
intf->coreIntf.McastTxRx = mDNStrue;
// Set up the extra fields in PosixNetworkInterface.
assert(intf->intfName != NULL); // intf->intfName already set up above
intf->index = intfIndex;
intf->multicastSocket4 = -1;
#if HAVE_IPV6
intf->multicastSocket6 = -1;
#endif
alias = SearchForInterfaceByName(m, intf->intfName);
if (alias == NULL) alias = intf;
intf->coreIntf.InterfaceID = (mDNSInterfaceID)alias;
if (alias != intf)
debugf("SetupOneInterface: %s %#a is an alias of %#a", intfName, &intf->coreIntf.ip, &alias->coreIntf.ip);
}
// Set up the multicast socket
if (err == 0)
{
if (alias->multicastSocket4 == -1 && intfAddr->sa_family == AF_INET)
err = SetupSocket(intfAddr, MulticastDNSPort, intf->index, &alias->multicastSocket4);
#if HAVE_IPV6
else if (alias->multicastSocket6 == -1 && intfAddr->sa_family == AF_INET6)
err = SetupSocket(intfAddr, MulticastDNSPort, intf->index, &alias->multicastSocket6);
#endif
}
// If interface is a direct link, address record will be marked as kDNSRecordTypeKnownUnique
// and skip the probe phase of the probe/announce packet sequence.
intf->coreIntf.DirectLink = mDNSfalse;
#ifdef DIRECTLINK_INTERFACE_NAME
if (strcmp(intfName, STRINGIFY(DIRECTLINK_INTERFACE_NAME)) == 0)
intf->coreIntf.DirectLink = mDNStrue;
#endif
intf->coreIntf.SupportsUnicastMDNSResponse = mDNStrue;
// The interface is all ready to go, let's register it with the mDNS core.
if (err == 0)
err = mDNS_RegisterInterface(m, &intf->coreIntf, mDNSfalse);
// Clean up.
if (err == 0)
{
num_registered_interfaces++;
debugf("SetupOneInterface: %s %#a Registered", intf->intfName, &intf->coreIntf.ip);
if (gMDNSPlatformPosixVerboseLevel > 0)
fprintf(stderr, "Registered interface %s\n", intf->intfName);
}
else
{
// Use intfName instead of intf->intfName in the next line to avoid dereferencing NULL.
debugf("SetupOneInterface: %s %#a failed to register %d", intfName, &intf->coreIntf.ip, err);
if (intf) { FreePosixNetworkInterface(intf); intf = NULL; }
}
assert((err == 0) == (intf != NULL));
return err;
}
// Call get_ifi_info() to obtain a list of active interfaces and call SetupOneInterface() on each one.
mDNSlocal int SetupInterfaceList(mDNS *const m)
{
mDNSBool foundav4 = mDNSfalse;
int err = 0;
struct ifi_info *intfList = get_ifi_info(AF_INET, mDNStrue);
struct ifi_info *firstLoopback = NULL;
assert(m != NULL);
debugf("SetupInterfaceList");
if (intfList == NULL) err = ENOENT;
#if HAVE_IPV6
if (err == 0) /* Link the IPv6 list to the end of the IPv4 list */
{
struct ifi_info **p = &intfList;
while (*p) p = &(*p)->ifi_next;
*p = get_ifi_info(AF_INET6, mDNStrue);
}
#endif
if (err == 0)
{
struct ifi_info *i = intfList;
while (i)
{
if ( ((i->ifi_addr->sa_family == AF_INET)
#if HAVE_IPV6
|| (i->ifi_addr->sa_family == AF_INET6)
#endif
) && (i->ifi_flags & IFF_UP) && !(i->ifi_flags & IFF_POINTOPOINT))
{
if (i->ifi_flags & IFF_LOOPBACK)
{
if (firstLoopback == NULL)
firstLoopback = i;
}
else
{
if (SetupOneInterface(m, i->ifi_addr, i->ifi_netmask, i->ifi_name, i->ifi_index) == 0)
if (i->ifi_addr->sa_family == AF_INET)
foundav4 = mDNStrue;
}
}
i = i->ifi_next;
}
// If we found no normal interfaces but we did find a loopback interface, register the
// loopback interface. This allows self-discovery if no interfaces are configured.
// Temporary workaround: Multicast loopback on IPv6 interfaces appears not to work.
// In the interim, we skip loopback interface only if we found at least one v4 interface to use
// if ((m->HostInterfaces == NULL) && (firstLoopback != NULL))
if (!foundav4 && firstLoopback)
(void) SetupOneInterface(m, firstLoopback->ifi_addr, firstLoopback->ifi_netmask, firstLoopback->ifi_name, firstLoopback->ifi_index);
}
// Clean up.
if (intfList != NULL) free_ifi_info(intfList);
// Clean up any interfaces that have been hanging around on the RecentInterfaces list for more than a minute
PosixNetworkInterface **ri = &gRecentInterfaces;
const mDNSs32 utc = mDNSPlatformUTC();
while (*ri)
{
PosixNetworkInterface *pi = *ri;
if (utc - pi->LastSeen < 60) ri = (PosixNetworkInterface **)&pi->coreIntf.next;
else { *ri = (PosixNetworkInterface *)pi->coreIntf.next; free(pi); }
}
return err;
}
#if USES_NETLINK
// See <http://www.faqs.org/rfcs/rfc3549.html> for a description of NetLink
// Open a socket that will receive interface change notifications
mDNSlocal mStatus OpenIfNotifySocket(int *pFD)
{
mStatus err = mStatus_NoError;
struct sockaddr_nl snl;
int sock;
int ret;
sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (sock < 0)
return errno;
// Configure read to be non-blocking because inbound msg size is not known in advance
(void) fcntl(sock, F_SETFL, O_NONBLOCK);
/* Subscribe the socket to Link & IP addr notifications. */
mDNSPlatformMemZero(&snl, sizeof snl);
snl.nl_family = AF_NETLINK;
snl.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR;
ret = bind(sock, (struct sockaddr *) &snl, sizeof snl);
if (0 == ret)
*pFD = sock;
else
err = errno;
return err;
}
#if MDNS_DEBUGMSGS
mDNSlocal void PrintNetLinkMsg(const struct nlmsghdr *pNLMsg)
{
const char *kNLMsgTypes[] = { "", "NLMSG_NOOP", "NLMSG_ERROR", "NLMSG_DONE", "NLMSG_OVERRUN" };
const char *kNLRtMsgTypes[] = { "RTM_NEWLINK", "RTM_DELLINK", "RTM_GETLINK", "RTM_NEWADDR", "RTM_DELADDR", "RTM_GETADDR" };
printf("nlmsghdr len=%d, type=%s, flags=0x%x\n", pNLMsg->nlmsg_len,
pNLMsg->nlmsg_type < RTM_BASE ? kNLMsgTypes[pNLMsg->nlmsg_type] : kNLRtMsgTypes[pNLMsg->nlmsg_type - RTM_BASE],
pNLMsg->nlmsg_flags);
if (RTM_NEWLINK <= pNLMsg->nlmsg_type && pNLMsg->nlmsg_type <= RTM_GETLINK)
{
struct ifinfomsg *pIfInfo = (struct ifinfomsg*) NLMSG_DATA(pNLMsg);
printf("ifinfomsg family=%d, type=%d, index=%d, flags=0x%x, change=0x%x\n", pIfInfo->ifi_family,
pIfInfo->ifi_type, pIfInfo->ifi_index, pIfInfo->ifi_flags, pIfInfo->ifi_change);
}
else if (RTM_NEWADDR <= pNLMsg->nlmsg_type && pNLMsg->nlmsg_type <= RTM_GETADDR)
{
struct ifaddrmsg *pIfAddr = (struct ifaddrmsg*) NLMSG_DATA(pNLMsg);
printf("ifaddrmsg family=%d, index=%d, flags=0x%x\n", pIfAddr->ifa_family,
pIfAddr->ifa_index, pIfAddr->ifa_flags);
}
printf("\n");
}
#endif
mDNSlocal mDNSu32 ProcessRoutingNotification(int sd)
// Read through the messages on sd and if any indicate that any interface records should
// be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
{
ssize_t readCount;
char buff[4096];
struct nlmsghdr *pNLMsg = (struct nlmsghdr*) buff;
mDNSu32 result = 0;
// The structure here is more complex than it really ought to be because,
// unfortunately, there's no good way to size a buffer in advance large
// enough to hold all pending data and so avoid message fragmentation.
// (Note that FIONREAD is not supported on AF_NETLINK.)
readCount = read(sd, buff, sizeof buff);
while (1)
{
// Make sure we've got an entire nlmsghdr in the buffer, and payload, too.
// If not, discard already-processed messages in buffer and read more data.
if (((char*) &pNLMsg[1] > (buff + readCount)) || // i.e. *pNLMsg extends off end of buffer
((char*) pNLMsg + pNLMsg->nlmsg_len > (buff + readCount)))
{
if (buff < (char*) pNLMsg) // we have space to shuffle
{
// discard processed data
readCount -= ((char*) pNLMsg - buff);
memmove(buff, pNLMsg, readCount);
pNLMsg = (struct nlmsghdr*) buff;
// read more data
readCount += read(sd, buff + readCount, sizeof buff - readCount);
continue; // spin around and revalidate with new readCount
}
else
break; // Otherwise message does not fit in buffer
}
#if MDNS_DEBUGMSGS
PrintNetLinkMsg(pNLMsg);
#endif
// Process the NetLink message
if (pNLMsg->nlmsg_type == RTM_GETLINK || pNLMsg->nlmsg_type == RTM_NEWLINK)
result |= 1 << ((struct ifinfomsg*) NLMSG_DATA(pNLMsg))->ifi_index;
else if (pNLMsg->nlmsg_type == RTM_DELADDR || pNLMsg->nlmsg_type == RTM_NEWADDR)
result |= 1 << ((struct ifaddrmsg*) NLMSG_DATA(pNLMsg))->ifa_index;
// Advance pNLMsg to the next message in the buffer
if ((pNLMsg->nlmsg_flags & NLM_F_MULTI) != 0 && pNLMsg->nlmsg_type != NLMSG_DONE)
{
ssize_t len = readCount - ((char*)pNLMsg - buff);
pNLMsg = NLMSG_NEXT(pNLMsg, len);
}
else
break; // all done!
}
return result;
}
#else // USES_NETLINK
// Open a socket that will receive interface change notifications
mDNSlocal mStatus OpenIfNotifySocket(int *pFD)
{
*pFD = socket(AF_ROUTE, SOCK_RAW, 0);
if (*pFD < 0)
return mStatus_UnknownErr;
// Configure read to be non-blocking because inbound msg size is not known in advance
(void) fcntl(*pFD, F_SETFL, O_NONBLOCK);
return mStatus_NoError;
}
#if MDNS_DEBUGMSGS
mDNSlocal void PrintRoutingSocketMsg(const struct ifa_msghdr *pRSMsg)
{
const char *kRSMsgTypes[] = { "", "RTM_ADD", "RTM_DELETE", "RTM_CHANGE", "RTM_GET", "RTM_LOSING",
"RTM_REDIRECT", "RTM_MISS", "RTM_LOCK", "RTM_OLDADD", "RTM_OLDDEL", "RTM_RESOLVE",
"RTM_NEWADDR", "RTM_DELADDR", "RTM_IFINFO", "RTM_NEWMADDR", "RTM_DELMADDR" };
int index = pRSMsg->ifam_type == RTM_IFINFO ? ((struct if_msghdr*) pRSMsg)->ifm_index : pRSMsg->ifam_index;
printf("ifa_msghdr len=%d, type=%s, index=%d\n", pRSMsg->ifam_msglen, kRSMsgTypes[pRSMsg->ifam_type], index);
}
#endif
mDNSlocal mDNSu32 ProcessRoutingNotification(int sd)
// Read through the messages on sd and if any indicate that any interface records should
// be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
{
ssize_t readCount;
char buff[4096];
struct ifa_msghdr *pRSMsg = (struct ifa_msghdr*) buff;
mDNSu32 result = 0;
readCount = read(sd, buff, sizeof buff);
if (readCount < (ssize_t) sizeof(struct ifa_msghdr))
return mStatus_UnsupportedErr; // cannot decipher message
#if MDNS_DEBUGMSGS
PrintRoutingSocketMsg(pRSMsg);
#endif
// Process the message
if (pRSMsg->ifam_type == RTM_NEWADDR || pRSMsg->ifam_type == RTM_DELADDR ||
pRSMsg->ifam_type == RTM_IFINFO)
{
if (pRSMsg->ifam_type == RTM_IFINFO)
result |= 1 << ((struct if_msghdr*) pRSMsg)->ifm_index;
else
result |= 1 << pRSMsg->ifam_index;
}
return result;
}
#endif // USES_NETLINK
// Called when data appears on interface change notification socket
mDNSlocal void InterfaceChangeCallback(int fd, short filter, void *context)
{
IfChangeRec *pChgRec = (IfChangeRec*) context;
fd_set readFDs;
mDNSu32 changedInterfaces = 0;
struct timeval zeroTimeout = { 0, 0 };
(void)fd; // Unused
(void)filter; // Unused
FD_ZERO(&readFDs);
FD_SET(pChgRec->NotifySD, &readFDs);
do
{
changedInterfaces |= ProcessRoutingNotification(pChgRec->NotifySD);
}
while (0 < select(pChgRec->NotifySD + 1, &readFDs, (fd_set*) NULL, (fd_set*) NULL, &zeroTimeout));
// Currently we rebuild the entire interface list whenever any interface change is
// detected. If this ever proves to be a performance issue in a multi-homed
// configuration, more care should be paid to changedInterfaces.
if (changedInterfaces)
mDNSPlatformPosixRefreshInterfaceList(pChgRec->mDNS);
}
// Register with either a Routing Socket or RtNetLink to listen for interface changes.
mDNSlocal mStatus WatchForInterfaceChange(mDNS *const m)
{
mStatus err;
IfChangeRec *pChgRec;
pChgRec = (IfChangeRec*) mDNSPlatformMemAllocate(sizeof *pChgRec);
if (pChgRec == NULL)
return mStatus_NoMemoryErr;
pChgRec->mDNS = m;
err = OpenIfNotifySocket(&pChgRec->NotifySD);
if (err == 0)
err = mDNSPosixAddFDToEventLoop(pChgRec->NotifySD, InterfaceChangeCallback, pChgRec);
return err;
}
// Test to see if we're the first client running on UDP port 5353, by trying to bind to 5353 without using SO_REUSEPORT.
// If we fail, someone else got here first. That's not a big problem; we can share the port for multicast responses --
// we just need to be aware that we shouldn't expect to successfully receive unicast UDP responses.
mDNSlocal mDNSBool mDNSPlatformInit_CanReceiveUnicast(void)
{
int err;
int s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
struct sockaddr_in s5353;
s5353.sin_family = AF_INET;
s5353.sin_port = MulticastDNSPort.NotAnInteger;
s5353.sin_addr.s_addr = 0;
err = bind(s, (struct sockaddr *)&s5353, sizeof(s5353));
close(s);
if (err) debugf("No unicast UDP responses");
else debugf("Unicast UDP responses okay");
return(err == 0);
}
// mDNS core calls this routine to initialise the platform-specific data.
mDNSexport mStatus mDNSPlatformInit(mDNS *const m)
{
int err = 0;
struct sockaddr sa;
assert(m != NULL);
if (mDNSPlatformInit_CanReceiveUnicast()) m->CanReceiveUnicastOn5353 = mDNStrue;
// Tell mDNS core the names of this machine.
// Set up the nice label
m->nicelabel.c[0] = 0;
GetUserSpecifiedFriendlyComputerName(&m->nicelabel);
if (m->nicelabel.c[0] == 0) MakeDomainLabelFromLiteralString(&m->nicelabel, "Computer");
// Set up the RFC 1034-compliant label
m->hostlabel.c[0] = 0;
GetUserSpecifiedRFC1034ComputerName(&m->hostlabel);
if (m->hostlabel.c[0] == 0) MakeDomainLabelFromLiteralString(&m->hostlabel, "Computer");
mDNS_SetFQDN(m);
sa.sa_family = AF_INET;
m->p->unicastSocket4 = -1;
if (err == mStatus_NoError) err = SetupSocket(&sa, zeroIPPort, 0, &m->p->unicastSocket4);
#if HAVE_IPV6
sa.sa_family = AF_INET6;
m->p->unicastSocket6 = -1;
if (err == mStatus_NoError) err = SetupSocket(&sa, zeroIPPort, 0, &m->p->unicastSocket6);
#endif
// Tell mDNS core about the network interfaces on this machine.
if (err == mStatus_NoError) err = SetupInterfaceList(m);
// Tell mDNS core about DNS Servers
mDNS_Lock(m);
if (err == mStatus_NoError) ParseDNSServers(m, uDNS_SERVERS_FILE);
mDNS_Unlock(m);
if (err == mStatus_NoError)
{
err = WatchForInterfaceChange(m);
// Failure to observe interface changes is non-fatal.
if (err != mStatus_NoError)
{
fprintf(stderr, "mDNS(%d) WARNING: Unable to detect interface changes (%d).\n", getpid(), err);
err = mStatus_NoError;
}
}
// We don't do asynchronous initialization on the Posix platform, so by the time
// we get here the setup will already have succeeded or failed. If it succeeded,
// we should just call mDNSCoreInitComplete() immediately.
if (err == mStatus_NoError)
mDNSCoreInitComplete(m, mStatus_NoError);
return PosixErrorToStatus(err);
}
// mDNS core calls this routine to clean up the platform-specific data.
// In our case all we need to do is to tear down every network interface.
mDNSexport void mDNSPlatformClose(mDNS *const m)
{
int rv;
assert(m != NULL);
ClearInterfaceList(m);
if (m->p->unicastSocket4 != -1)
{
rv = close(m->p->unicastSocket4);
assert(rv == 0);
}
#if HAVE_IPV6
if (m->p->unicastSocket6 != -1)
{
rv = close(m->p->unicastSocket6);
assert(rv == 0);
}
#endif
}
// This is used internally by InterfaceChangeCallback.
// It's also exported so that the Standalone Responder (mDNSResponderPosix)
// can call it in response to a SIGHUP (mainly for debugging purposes).
mDNSexport mStatus mDNSPlatformPosixRefreshInterfaceList(mDNS *const m)
{
int err;
// This is a pretty heavyweight way to process interface changes --
// destroying the entire interface list and then making fresh one from scratch.
// We should make it like the OS X version, which leaves unchanged interfaces alone.
ClearInterfaceList(m);
err = SetupInterfaceList(m);
return PosixErrorToStatus(err);
}
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark ***** Locking
#endif
// On the Posix platform, locking is a no-op because we only ever enter
// mDNS core on the main thread.
// mDNS core calls this routine when it wants to prevent
// the platform from reentering mDNS core code.
mDNSexport void mDNSPlatformLock (const mDNS *const m)
{
(void) m; // Unused
}
// mDNS core calls this routine when it release the lock taken by
// mDNSPlatformLock and allow the platform to reenter mDNS core code.
mDNSexport void mDNSPlatformUnlock (const mDNS *const m)
{
(void) m; // Unused
}
#if COMPILER_LIKES_PRAGMA_MARK
#pragma mark ***** Strings
#endif
// mDNS core calls this routine to copy C strings.
// On the Posix platform this maps directly to the ANSI C strcpy.
mDNSexport void mDNSPlatformStrCopy(void *dst, const void *src)
{
strcpy((char *)dst, (const char *)src);
}
mDNSexport mDNSu32 mDNSPlatformStrLCopy(void *dst, const void *src, mDNSu32 len)
{
#if HAVE_STRLCPY
return ((mDNSu32)strlcpy((char *)dst, (const char *)src, len));
#else
size_t srcLen;
srcLen = strlen((const char *)src);
if (srcLen < len)
{
memcpy(dst, src, srcLen + 1);
}
else if (len > 0)
{
memcpy(dst, src, len - 1);
((char *)dst)[len - 1] = '\0';
}
return ((mDNSu32)srcLen);
#endif
}
// mDNS core calls this routine to get the length of a C string.
// On the Posix platform this maps directly to the ANSI C strlen.
mDNSexport mDNSu32 mDNSPlatformStrLen (const void *src)
{
return strlen((const char*)src);
}
// mDNS core calls this routine to copy memory.
// On the Posix platform this maps directly to the ANSI C memcpy.
mDNSexport void mDNSPlatformMemCopy(void *dst, const void *src, mDNSu32 len)
{
memcpy(dst, src, len);
}
// mDNS core calls this routine to test whether blocks of memory are byte-for-byte
// identical. On the Posix platform this is a simple wrapper around ANSI C memcmp.
mDNSexport mDNSBool mDNSPlatformMemSame(const void *dst, const void *src, mDNSu32 len)
{
return memcmp(dst, src, len) == 0;
}
// If the caller wants to know the exact return of memcmp, then use this instead
// of mDNSPlatformMemSame
mDNSexport int mDNSPlatformMemCmp(const void *dst, const void *src, mDNSu32 len)
{
return (memcmp(dst, src, len));
}
mDNSexport void mDNSPlatformQsort(void *base, int nel, int width, int (*compar)(const void *, const void *))
{
return (qsort(base, nel, width, compar));
}
// DNSSEC stub functions
mDNSexport void VerifySignature(mDNS *const m, DNSSECVerifier *dv, DNSQuestion *q)
{
(void)m;
(void)dv;
(void)q;
}
mDNSexport mDNSBool AddNSECSForCacheRecord(mDNS *const m, CacheRecord *crlist, CacheRecord *negcr, mDNSu8 rcode)
{
(void)m;
(void)crlist;
(void)negcr;
(void)rcode;
return mDNSfalse;
}
mDNSexport void BumpDNSSECStats(mDNS *const m, DNSSECStatsAction action, DNSSECStatsType type, mDNSu32 value)
{
(void)m;
(void)action;
(void)type;
(void)value;
}
// Proxy stub functions
mDNSexport mDNSu8 *DNSProxySetAttributes(DNSQuestion *q, DNSMessageHeader *h, DNSMessage *msg, mDNSu8 *ptr, mDNSu8 *limit)
{
(void) q;
(void) h;
(void) msg;
(void) ptr;
(void) limit;
return ptr;
}
mDNSexport void DNSProxyInit(mDNS *const m, mDNSu32 IpIfArr[], mDNSu32 OpIf)
{
(void) m;
(void) IpIfArr;
(void) OpIf;
}
mDNSexport void DNSProxyTerminate(mDNS *const m)
{
(void) m;
}
// mDNS core calls this routine to clear blocks of memory.
// On the Posix platform this is a simple wrapper around ANSI C memset.
mDNSexport void mDNSPlatformMemZero(void *dst, mDNSu32 len)
{
memset(dst, 0, len);
}
mDNSexport void * mDNSPlatformMemAllocate(mDNSu32 len) { return(malloc(len)); }
mDNSexport void mDNSPlatformMemFree (void *mem) { free(mem); }
mDNSexport mDNSu32 mDNSPlatformRandomSeed(void)
{
struct timeval tv;
gettimeofday(&tv, NULL);
return(tv.tv_usec);
}
mDNSexport mDNSs32 mDNSPlatformOneSecond = 1024;
mDNSexport mStatus mDNSPlatformTimeInit(void)
{
// No special setup is required on Posix -- we just use gettimeofday();
// This is not really safe, because gettimeofday can go backwards if the user manually changes the date or time
// We should find a better way to do this
return(mStatus_NoError);
}
mDNSexport mDNSs32 mDNSPlatformRawTime()
{
struct timeval tv;
gettimeofday(&tv, NULL);
// tv.tv_sec is seconds since 1st January 1970 (GMT, with no adjustment for daylight savings time)
// tv.tv_usec is microseconds since the start of this second (i.e. values 0 to 999999)
// We use the lower 22 bits of tv.tv_sec for the top 22 bits of our result
// and we multiply tv.tv_usec by 16 / 15625 to get a value in the range 0-1023 to go in the bottom 10 bits.
// This gives us a proper modular (cyclic) counter that has a resolution of roughly 1ms (actually 1/1024 second)
// and correctly cycles every 2^22 seconds (4194304 seconds = approx 48 days).
return((tv.tv_sec << 10) | (tv.tv_usec * 16 / 15625));
}
mDNSexport mDNSs32 mDNSPlatformUTC(void)
{
return time(NULL);
}
mDNSexport void mDNSPlatformSendWakeupPacket(mDNS *const m, mDNSInterfaceID InterfaceID, char *EthAddr, char *IPAddr, int iteration)
{
(void) m;
(void) InterfaceID;
(void) EthAddr;
(void) IPAddr;
(void) iteration;
}
mDNSexport mDNSBool mDNSPlatformValidRecordForInterface(const AuthRecord *rr, mDNSInterfaceID InterfaceID)
{
(void) rr;
(void) InterfaceID;
return 1;
}
mDNSexport mDNSBool mDNSPlatformValidQuestionForInterface(DNSQuestion *q, const NetworkInterfaceInfo *intf)
{
(void) q;
(void) intf;
return 1;
}
// Used for debugging purposes. For now, just set the buffer to zero
mDNSexport void mDNSPlatformFormatTime(unsigned long te, mDNSu8 *buf, int bufsize)
{
(void) te;
if (bufsize) buf[0] = 0;
}
mDNSexport void mDNSPlatformSendKeepalive(mDNSAddr *sadd, mDNSAddr *dadd, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu32 seq, mDNSu32 ack, mDNSu16 win)
{
(void) sadd; // Unused
(void) dadd; // Unused
(void) lport; // Unused
(void) rport; // Unused
(void) seq; // Unused
(void) ack; // Unused
(void) win; // Unused
}
mDNSexport mStatus mDNSPlatformRetrieveTCPInfo(mDNS *const m, mDNSAddr *laddr, mDNSIPPort *lport, mDNSAddr *raddr, mDNSIPPort *rport, mDNSTCPInfo *mti)
{
(void) m; // Unused
(void) laddr; // Unused
(void) raddr; // Unused
(void) lport; // Unused
(void) rport; // Unused
(void) mti; // Unused
return mStatus_NoError;
}
mDNSexport mStatus mDNSPlatformGetRemoteMacAddr(mDNS *const m, mDNSAddr *raddr)
{
(void) raddr; // Unused
(void) m; // Unused
return mStatus_NoError;
}
mDNSexport mStatus mDNSPlatformStoreSPSMACAddr(mDNSAddr *spsaddr, char *ifname)
{
(void) spsaddr; // Unused
(void) ifname; // Unused
return mStatus_NoError;
}
mDNSexport mStatus mDNSPlatformClearSPSData(void)
{
return mStatus_NoError;
}
mDNSexport mStatus mDNSPlatformStoreOwnerOptRecord(char *ifname, DNSMessage *msg, int length)
{
(void) ifname; // Unused
(void) msg; // Unused
(void) length; // Unused
return mStatus_UnsupportedErr;
}
mDNSexport mDNSu16 mDNSPlatformGetUDPPort(UDPSocket *sock)
{
(void) sock; // unused
return (mDNSu16)-1;
}
mDNSexport mDNSBool mDNSPlatformInterfaceIsD2D(mDNSInterfaceID InterfaceID)
{
(void) InterfaceID; // unused
return mDNSfalse;
}
mDNSexport void mDNSPlatformSetSocktOpt(void *sock, mDNSTransport_Type transType, mDNSAddr_Type addrType, const DNSQuestion *q)
{
(void) sock;
(void) transType;
(void) addrType;
(void) q;
}
mDNSexport mDNSs32 mDNSPlatformGetPID()
{
return 0;
}
mDNSlocal void mDNSPosixAddToFDSet(int *nfds, fd_set *readfds, int s)
{
if (*nfds < s + 1) *nfds = s + 1;
FD_SET(s, readfds);
}
mDNSexport void mDNSPosixGetFDSet(mDNS *m, int *nfds, fd_set *readfds, struct timeval *timeout)
{
mDNSs32 ticks;
struct timeval interval;
// 1. Call mDNS_Execute() to let mDNSCore do what it needs to do
mDNSs32 nextevent = mDNS_Execute(m);
// 2. Build our list of active file descriptors
PosixNetworkInterface *info = (PosixNetworkInterface *)(m->HostInterfaces);
if (m->p->unicastSocket4 != -1) mDNSPosixAddToFDSet(nfds, readfds, m->p->unicastSocket4);
#if HAVE_IPV6
if (m->p->unicastSocket6 != -1) mDNSPosixAddToFDSet(nfds, readfds, m->p->unicastSocket6);
#endif
while (info)
{
if (info->multicastSocket4 != -1) mDNSPosixAddToFDSet(nfds, readfds, info->multicastSocket4);
#if HAVE_IPV6
if (info->multicastSocket6 != -1) mDNSPosixAddToFDSet(nfds, readfds, info->multicastSocket6);
#endif
info = (PosixNetworkInterface *)(info->coreIntf.next);
}
// 3. Calculate the time remaining to the next scheduled event (in struct timeval format)
ticks = nextevent - mDNS_TimeNow(m);
if (ticks < 1) ticks = 1;
interval.tv_sec = ticks >> 10; // The high 22 bits are seconds
interval.tv_usec = ((ticks & 0x3FF) * 15625) / 16; // The low 10 bits are 1024ths
// 4. If client's proposed timeout is more than what we want, then reduce it
if (timeout->tv_sec > interval.tv_sec ||
(timeout->tv_sec == interval.tv_sec && timeout->tv_usec > interval.tv_usec))
*timeout = interval;
}
mDNSexport void mDNSPosixProcessFDSet(mDNS *const m, fd_set *readfds)
{
PosixNetworkInterface *info;
assert(m != NULL);
assert(readfds != NULL);
info = (PosixNetworkInterface *)(m->HostInterfaces);
if (m->p->unicastSocket4 != -1 && FD_ISSET(m->p->unicastSocket4, readfds))
{
FD_CLR(m->p->unicastSocket4, readfds);
SocketDataReady(m, NULL, m->p->unicastSocket4);
}
#if HAVE_IPV6
if (m->p->unicastSocket6 != -1 && FD_ISSET(m->p->unicastSocket6, readfds))
{
FD_CLR(m->p->unicastSocket6, readfds);
SocketDataReady(m, NULL, m->p->unicastSocket6);
}
#endif
while (info)
{
if (info->multicastSocket4 != -1 && FD_ISSET(info->multicastSocket4, readfds))
{
FD_CLR(info->multicastSocket4, readfds);
SocketDataReady(m, info, info->multicastSocket4);
}
#if HAVE_IPV6
if (info->multicastSocket6 != -1 && FD_ISSET(info->multicastSocket6, readfds))
{
FD_CLR(info->multicastSocket6, readfds);
SocketDataReady(m, info, info->multicastSocket6);
}
#endif
info = (PosixNetworkInterface *)(info->coreIntf.next);
}
}
// update gMaxFD
mDNSlocal void DetermineMaxEventFD(void)
{
PosixEventSource *iSource;
gMaxFD = 0;
for (iSource=(PosixEventSource*)gEventSources.Head; iSource; iSource = iSource->Next)
if (gMaxFD < iSource->fd)
gMaxFD = iSource->fd;
}
// Add a file descriptor to the set that mDNSPosixRunEventLoopOnce() listens to.
mStatus mDNSPosixAddFDToEventLoop(int fd, mDNSPosixEventCallback callback, void *context)
{
PosixEventSource *newSource;
if (gEventSources.LinkOffset == 0)
InitLinkedList(&gEventSources, offsetof(PosixEventSource, Next));
if (fd >= (int) FD_SETSIZE || fd < 0)
return mStatus_UnsupportedErr;
if (callback == NULL)
return mStatus_BadParamErr;
newSource = (PosixEventSource*) malloc(sizeof *newSource);
if (NULL == newSource)
return mStatus_NoMemoryErr;
newSource->Callback = callback;
newSource->Context = context;
newSource->fd = fd;
AddToTail(&gEventSources, newSource);
FD_SET(fd, &gEventFDs);
DetermineMaxEventFD();
return mStatus_NoError;
}
// Remove a file descriptor from the set that mDNSPosixRunEventLoopOnce() listens to.
mStatus mDNSPosixRemoveFDFromEventLoop(int fd)
{
PosixEventSource *iSource;
for (iSource=(PosixEventSource*)gEventSources.Head; iSource; iSource = iSource->Next)
{
if (fd == iSource->fd)
{
FD_CLR(fd, &gEventFDs);
RemoveFromList(&gEventSources, iSource);
free(iSource);
DetermineMaxEventFD();
return mStatus_NoError;
}
}
return mStatus_NoSuchNameErr;
}
// Simply note the received signal in gEventSignals.
mDNSlocal void NoteSignal(int signum)
{
sigaddset(&gEventSignals, signum);
}
// Tell the event package to listen for signal and report it in mDNSPosixRunEventLoopOnce().
mStatus mDNSPosixListenForSignalInEventLoop(int signum)
{
struct sigaction action;
mStatus err;
mDNSPlatformMemZero(&action, sizeof action); // more portable than member-wise assignment
action.sa_handler = NoteSignal;
err = sigaction(signum, &action, (struct sigaction*) NULL);
sigaddset(&gEventSignalSet, signum);
return err;
}
// Tell the event package to stop listening for signal in mDNSPosixRunEventLoopOnce().
mStatus mDNSPosixIgnoreSignalInEventLoop(int signum)
{
struct sigaction action;
mStatus err;
mDNSPlatformMemZero(&action, sizeof action); // more portable than member-wise assignment
action.sa_handler = SIG_DFL;
err = sigaction(signum, &action, (struct sigaction*) NULL);
sigdelset(&gEventSignalSet, signum);
return err;
}
// Do a single pass through the attendent event sources and dispatch any found to their callbacks.
// Return as soon as internal timeout expires, or a signal we're listening for is received.
mStatus mDNSPosixRunEventLoopOnce(mDNS *m, const struct timeval *pTimeout,
sigset_t *pSignalsReceived, mDNSBool *pDataDispatched)
{
fd_set listenFDs = gEventFDs;
int fdMax = 0, numReady;
struct timeval timeout = *pTimeout;
// Include the sockets that are listening to the wire in our select() set
mDNSPosixGetFDSet(m, &fdMax, &listenFDs, &timeout); // timeout may get modified
if (fdMax < gMaxFD)
fdMax = gMaxFD;
numReady = select(fdMax + 1, &listenFDs, (fd_set*) NULL, (fd_set*) NULL, &timeout);
// If any data appeared, invoke its callback
if (numReady > 0)
{
PosixEventSource *iSource;
(void) mDNSPosixProcessFDSet(m, &listenFDs); // call this first to process wire data for clients
for (iSource=(PosixEventSource*)gEventSources.Head; iSource; iSource = iSource->Next)
{
if (FD_ISSET(iSource->fd, &listenFDs))
{
iSource->Callback(iSource->fd, 0, iSource->Context);
break; // in case callback removed elements from gEventSources
}
}
*pDataDispatched = mDNStrue;
}
else
*pDataDispatched = mDNSfalse;
(void) sigprocmask(SIG_BLOCK, &gEventSignalSet, (sigset_t*) NULL);
*pSignalsReceived = gEventSignals;
sigemptyset(&gEventSignals);
(void) sigprocmask(SIG_UNBLOCK, &gEventSignalSet, (sigset_t*) NULL);
return mStatus_NoError;
}
|
800990.c | /*
Copyright (c) 2008-2010
Lars-Dominik Braun <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#define _BSD_SOURCE /* required by strdup() */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ezxml.h>
#include "piano.h"
#include "crypt.h"
#include "config.h"
#include "piano_private.h"
static void PianoXmlStructParser (const ezxml_t,
void (*callback) (const char *, const ezxml_t, void *), void *);
static char *PianoXmlGetNodeText (const ezxml_t);
/* parse fault and get fault type
* @param xml <name> content
* @param xml <value> node
* @param return error string
* @return nothing
*/
static void PianoXmlIsFaultCb (const char *key, const ezxml_t value,
void *data) {
PianoReturn_t *ret = data;
char *valueStr = PianoXmlGetNodeText (value);
char *matchStart, *matchEnd;
if (strcmp ("faultString", key) == 0) {
*ret = PIANO_RET_ERR;
/* find fault identifier in a string like this:
* com.savagebeast.radio.api.protocol.xmlrpc.RadioXmlRpcException:
* 192.168.160.78|1213101717317|AUTH_INVALID_TOKEN|
* Invalid auth token */
if ((matchStart = strchr (valueStr, '|')) != NULL) {
if ((matchStart = strchr (matchStart+1, '|')) != NULL) {
if ((matchEnd = strchr (matchStart+1, '|')) != NULL) {
/* changes text in xml node, but we don't care... */
*matchEnd = '\0';
++matchStart;
/* translate to our error message system */
if (strcmp ("AUTH_INVALID_TOKEN", matchStart) == 0) {
*ret = PIANO_RET_AUTH_TOKEN_INVALID;
} else if (strcmp ("AUTH_INVALID_USERNAME_PASSWORD",
matchStart) == 0) {
*ret = PIANO_RET_AUTH_USER_PASSWORD_INVALID;
} else if (strcmp ("LISTENER_NOT_AUTHORIZED",
matchStart) == 0) {
*ret = PIANO_RET_NOT_AUTHORIZED;
} else if (strcmp ("INCOMPATIBLE_VERSION",
matchStart) == 0) {
*ret = PIANO_RET_PROTOCOL_INCOMPATIBLE;
} else if (strcmp ("READONLY_MODE", matchStart) == 0) {
*ret = PIANO_RET_READONLY_MODE;
} else if (strcmp ("STATION_CODE_INVALID",
matchStart) == 0) {
*ret = PIANO_RET_STATION_CODE_INVALID;
} else if (strcmp ("STATION_DOES_NOT_EXIST",
matchStart) == 0) {
*ret = PIANO_RET_STATION_NONEXISTENT;
} else if (strcmp ("OUT_OF_SYNC", matchStart) == 0) {
*ret = PIANO_RET_OUT_OF_SYNC;
} else if (strcmp ("PLAYLIST_END", matchStart) == 0) {
*ret = PIANO_RET_PLAYLIST_END;
} else if (strcmp ("QUICKMIX_NOT_PLAYABLE", matchStart) == 0) {
*ret = PIANO_RET_QUICKMIX_NOT_PLAYABLE;
} else {
*ret = PIANO_RET_ERR;
printf (PACKAGE ": Unknown error %s in %s\n",
matchStart, valueStr);
}
}
}
}
} else if (strcmp ("faultCode", key) == 0) {
/* some errors can only be identified by looking at their id */
/* detect pandora's ip restriction */
if (strcmp ("12", valueStr) == 0) {
*ret = PIANO_RET_IP_REJECTED;
}
}
}
/* check whether pandora returned an error or not
* @param document root of xml doc
* @return _RET_OK or fault code (_RET_*)
*/
static PianoReturn_t PianoXmlIsFault (ezxml_t xmlDoc) {
PianoReturn_t ret;
if ((xmlDoc = ezxml_child (xmlDoc, "fault")) != NULL) {
xmlDoc = ezxml_get (xmlDoc, "value", 0, "struct", -1);
PianoXmlStructParser (xmlDoc, PianoXmlIsFaultCb, &ret);
return ret;
}
return PIANO_RET_OK;
}
/* parses things like this:
* <struct>
* <member>
* <name />
* <value />
* </member>
* <!-- ... -->
* </struct>
* @param xml node named "struct" (or containing a similar structure)
* @param who wants to use this data? callback: content of <name> as
* string, content of <value> as xmlNode (may contain other nodes
* or text), additional data used by callback(); don't forget
* to *copy* data taken from <name> or <value> as they will be
* freed soon
* @param extra data for callback
*/
static void PianoXmlStructParser (const ezxml_t structRoot,
void (*callback) (const char *, const ezxml_t, void *), void *data) {
ezxml_t curNode, keyNode, valueNode;
char *key;
/* get all <member> nodes */
for (curNode = ezxml_child (structRoot, "member"); curNode; curNode = curNode->next) {
/* reset variables */
key = NULL;
valueNode = keyNode = NULL;
keyNode = ezxml_child (curNode, "name");
if (keyNode != NULL) {
key = ezxml_txt (keyNode);
}
valueNode = ezxml_child (curNode, "value");
/* this will ignore empty <value /> nodes, but well... */
if (*key != '\0' && valueNode != NULL) {
(*callback) ((char *) key, valueNode, data);
}
}
}
/* create xml parser from string
* @param xml document
* @param returns document pointer (needed to free memory later)
* @param returns document root
* @return _OK or error
*/
static PianoReturn_t PianoXmlInitDoc (char *xmlStr, ezxml_t *xmlDoc) {
PianoReturn_t ret;
if ((*xmlDoc = ezxml_parse_str (xmlStr, strlen (xmlStr))) == NULL) {
return PIANO_RET_XML_INVALID;
}
if ((ret = PianoXmlIsFault (*xmlDoc)) != PIANO_RET_OK) {
ezxml_free (*xmlDoc);
return ret;
}
return PIANO_RET_OK;
}
/* get text from <value> nodes; some of them have <boolean>, <string>
* or <int> subnodes, just ignore them
* @param xml node <value>
*/
static char *PianoXmlGetNodeText (const ezxml_t node) {
char *retTxt = NULL;
retTxt = ezxml_txt (node);
/* no text => empty string */
if (*retTxt == '\0') {
retTxt = ezxml_txt (node->child);
}
return retTxt;
}
/* structParser callback; writes userinfo to PianoUserInfo structure
* @param value identifier
* @param value node
* @param pointer to userinfo structure
* @return nothing
*/
static void PianoXmlParseUserinfoCb (const char *key, const ezxml_t value,
void *data) {
PianoUserInfo_t *user = data;
char *valueStr = PianoXmlGetNodeText (value);
if (strcmp ("webAuthToken", key) == 0) {
user->webAuthToken = strdup (valueStr);
} else if (strcmp ("authToken", key) == 0) {
user->authToken = strdup (valueStr);
} else if (strcmp ("listenerId", key) == 0) {
user->listenerId = strdup (valueStr);
}
}
static void PianoXmlParseStationsCb (const char *key, const ezxml_t value,
void *data) {
PianoStation_t *station = data;
char *valueStr = PianoXmlGetNodeText (value);
if (strcmp ("stationName", key) == 0) {
station->name = strdup (valueStr);
} else if (strcmp ("stationId", key) == 0) {
station->id = strdup (valueStr);
} else if (strcmp ("isQuickMix", key) == 0) {
station->isQuickMix = (strcmp (valueStr, "1") == 0);
} else if (strcmp ("isCreator", key) == 0) {
station->isCreator = (strcmp (valueStr, "1") == 0);
}
}
static void PianoXmlParsePlaylistCb (const char *key, const ezxml_t value,
void *data) {
PianoSong_t *song = data;
char *valueStr = PianoXmlGetNodeText (value);
if (strcmp ("audioURL", key) == 0) {
/* last 48 chars of audioUrl are encrypted, but they put the key
* into the door's lock... */
const char urlTailN = 48;
const size_t valueStrN = strlen (valueStr);
char *urlTail = NULL,
*urlTailCrypted = &valueStr[valueStrN - urlTailN];
/* don't try to decrypt if string is too short (=> invalid memory
* reads/writes) */
if (valueStrN > urlTailN &&
(urlTail = PianoDecryptString (urlTailCrypted)) != NULL) {
if ((song->audioUrl = calloc (valueStrN + 1,
sizeof (*song->audioUrl))) != NULL) {
memcpy (song->audioUrl, valueStr, valueStrN - urlTailN);
/* FIXME: the key seems to be broken... so ignore 8 x 0x08
* postfix; urlTailN/2 because the encrypted hex string is now
* decoded */
memcpy (&song->audioUrl[valueStrN - urlTailN], urlTail,
urlTailN/2 - 8);
}
free (urlTail);
}
} else if (strcmp ("artRadio", key) == 0) {
song->coverArt = strdup (valueStr);
} else if (strcmp ("artistSummary", key) == 0) {
song->artist = strdup (valueStr);
} else if (strcmp ("musicId", key) == 0) {
song->musicId = strdup (valueStr);
} else if (strcmp ("userSeed", key) == 0) {
song->userSeed = strdup (valueStr);
} else if (strcmp ("songTitle", key) == 0) {
song->title = strdup (valueStr);
} else if (strcmp ("rating", key) == 0) {
if (strcmp (valueStr, "1") == 0) {
song->rating = PIANO_RATE_LOVE;
} else {
song->rating = PIANO_RATE_NONE;
}
} else if (strcmp ("stationId", key) == 0) {
song->stationId = strdup (valueStr);
} else if (strcmp ("albumTitle", key) == 0) {
song->album = strdup (valueStr);
} else if (strcmp ("fileGain", key) == 0) {
song->fileGain = atof (valueStr);
} else if (strcmp ("audioEncoding", key) == 0) {
if (strcmp (valueStr, "aacplus") == 0) {
song->audioFormat = PIANO_AF_AACPLUS;
} else if (strcmp (valueStr, "mp3") == 0) {
song->audioFormat = PIANO_AF_MP3;
} else if (strcmp (valueStr, "mp3-hifi") == 0) {
song->audioFormat = PIANO_AF_MP3_HI;
}
} else if (strcmp ("artistMusicId", key) == 0) {
song->artistMusicId = strdup (valueStr);
} else if (strcmp ("testStrategy", key) == 0) {
song->testStrategy = atoi (valueStr);
} else if (strcmp ("songType", key) == 0) {
song->songType = atoi (valueStr);
}
}
/* parses userinfos sent by pandora as login response
* @param piano handle
* @param utf-8 string
* @return _RET_OK or error
*/
PianoReturn_t PianoXmlParseUserinfo (PianoHandle_t *ph, char *xml) {
ezxml_t xmlDoc, structNode;
PianoReturn_t ret;
if ((ret = PianoXmlInitDoc (xml, &xmlDoc)) != PIANO_RET_OK) {
return ret;
}
/* <methodResponse> <params> <param> <value> <struct> */
structNode = ezxml_get (xmlDoc, "params", 0, "param", 0, "value", 0, "struct", -1);
PianoXmlStructParser (structNode, PianoXmlParseUserinfoCb, &ph->user);
ezxml_free (xmlDoc);
return PIANO_RET_OK;
}
static void PianoXmlParseQuickMixStationsCb (const char *key, const ezxml_t value,
void *data) {
char ***retIds = data;
char **ids = NULL;
size_t idsN = 0;
ezxml_t curNode;
if (strcmp ("quickMixStationIds", key) == 0) {
for (curNode = ezxml_child (ezxml_get (value, "array", 0, "data", -1), "value");
curNode; curNode = curNode->next) {
idsN++;
if (ids == NULL) {
if ((ids = calloc (idsN, sizeof (*ids))) == NULL) {
*retIds = NULL;
return;
}
} else {
/* FIXME: memory leak (on failure) */
if ((ids = realloc (ids, idsN * sizeof (*ids))) == NULL) {
*retIds = NULL;
return;
}
}
ids[idsN-1] = strdup (PianoXmlGetNodeText (curNode));
}
/* append NULL: list ends here */
idsN++;
/* FIXME: copy&waste */
if (ids == NULL) {
if ((ids = calloc (idsN, sizeof (*ids))) == NULL) {
*retIds = NULL;
return;
}
} else {
if ((ids = realloc (ids, idsN * sizeof (*ids))) == NULL) {
*retIds = NULL;
return;
}
}
ids[idsN-1] = NULL;
}
*retIds = ids;
}
/* parse stations returned by pandora
* @param piano handle
* @param xml returned by pandora
* @return _RET_OK or error
*/
PianoReturn_t PianoXmlParseStations (PianoHandle_t *ph, char *xml) {
ezxml_t xmlDoc, dataNode;
PianoReturn_t ret;
char **quickMixIds = NULL, **curQuickMixId = NULL;
if ((ret = PianoXmlInitDoc (xml, &xmlDoc)) != PIANO_RET_OK) {
return ret;
}
dataNode = ezxml_get (xmlDoc, "params", 0, "param", 0, "value", 0, "array",
0, "data", -1);
for (dataNode = ezxml_child (dataNode, "value"); dataNode;
dataNode = dataNode->next) {
PianoStation_t *tmpStation;
if ((tmpStation = calloc (1, sizeof (*tmpStation))) == NULL) {
ezxml_free (xmlDoc);
return PIANO_RET_OUT_OF_MEMORY;
}
PianoXmlStructParser (ezxml_child (dataNode, "struct"),
PianoXmlParseStationsCb, tmpStation);
/* get stations selected for quickmix */
if (tmpStation->isQuickMix) {
PianoXmlStructParser (ezxml_child (dataNode, "struct"),
PianoXmlParseQuickMixStationsCb, &quickMixIds);
}
/* start new linked list or append */
if (ph->stations == NULL) {
ph->stations = tmpStation;
} else {
PianoStation_t *curStation = ph->stations;
while (curStation->next != NULL) {
curStation = curStation->next;
}
curStation->next = tmpStation;
}
}
/* set quickmix flags after all stations are read */
if (quickMixIds != NULL) {
curQuickMixId = quickMixIds;
while (*curQuickMixId != NULL) {
PianoStation_t *curStation = PianoFindStationById (ph->stations,
*curQuickMixId);
if (curStation != NULL) {
curStation->useQuickMix = 1;
}
free (*curQuickMixId);
curQuickMixId++;
}
free (quickMixIds);
}
ezxml_free (xmlDoc);
return PIANO_RET_OK;
}
/* parse "create station" answer (it returns a new station structure)
* @param piano handle
* @param xml document
* @return nothing yet
*/
PianoReturn_t PianoXmlParseCreateStation (PianoHandle_t *ph, char *xml) {
ezxml_t xmlDoc, dataNode;
PianoStation_t *tmpStation;
PianoReturn_t ret;
if ((ret = PianoXmlInitDoc (xml, &xmlDoc)) != PIANO_RET_OK) {
return ret;
}
dataNode = ezxml_get (xmlDoc, "params", 0, "param", 0, "value", 0, "struct", -1);
if ((tmpStation = calloc (1, sizeof (*tmpStation))) == NULL) {
ezxml_free (xmlDoc);
return PIANO_RET_OUT_OF_MEMORY;
}
PianoXmlStructParser (dataNode, PianoXmlParseStationsCb, tmpStation);
/* FIXME: copy & waste */
/* start new linked list or append */
if (ph->stations == NULL) {
ph->stations = tmpStation;
} else {
PianoStation_t *curStation = ph->stations;
while (curStation->next != NULL) {
curStation = curStation->next;
}
curStation->next = tmpStation;
}
ezxml_free (xmlDoc);
return PIANO_RET_OK;
}
/* parse "add seed" answer, nearly the same as ParseCreateStation
* @param piano handle
* @param xml document
* @param update this station
*/
PianoReturn_t PianoXmlParseAddSeed (PianoHandle_t *ph, char *xml,
PianoStation_t *station) {
ezxml_t xmlDoc, dataNode;
PianoReturn_t ret;
if ((ret = PianoXmlInitDoc (xml, &xmlDoc)) != PIANO_RET_OK) {
return ret;
}
dataNode = ezxml_get (xmlDoc, "params", 0, "param", 0, "value", 0, "struct", -1);
PianoDestroyStation (station);
PianoXmlStructParser (dataNode, PianoXmlParseStationsCb, station);
ezxml_free (xmlDoc);
return PIANO_RET_OK;
}
/* parses playlist; used when searching too
* @param piano handle
* @param xml document
* @param return: playlist
*/
PianoReturn_t PianoXmlParsePlaylist (PianoHandle_t *ph, char *xml,
PianoSong_t **retPlaylist) {
ezxml_t xmlDoc, dataNode;
PianoReturn_t ret;
if ((ret = PianoXmlInitDoc (xml, &xmlDoc)) != PIANO_RET_OK) {
return ret;
}
dataNode = ezxml_get (xmlDoc, "params", 0, "param", 0, "value", 0, "array",
0, "data", -1);
for (dataNode = ezxml_child (dataNode, "value"); dataNode;
dataNode = dataNode->next) {
PianoSong_t *tmpSong;
if ((tmpSong = calloc (1, sizeof (*tmpSong))) == NULL) {
ezxml_free (xmlDoc);
return PIANO_RET_OUT_OF_MEMORY;
}
PianoXmlStructParser (ezxml_child (dataNode, "struct"),
PianoXmlParsePlaylistCb, tmpSong);
/* begin linked list or append */
if (*retPlaylist == NULL) {
*retPlaylist = tmpSong;
} else {
PianoSong_t *curSong = *retPlaylist;
while (curSong->next != NULL) {
curSong = curSong->next;
}
curSong->next = tmpSong;
}
}
ezxml_free (xmlDoc);
return PIANO_RET_OK;
}
/* parse simple answers like this: <?xml version="1.0" encoding="UTF-8"?>
* <methodResponse><params><param><value>1</value></param></params>
* </methodResponse>
* @param xml string
* @return
*/
PianoReturn_t PianoXmlParseSimple (char *xml) {
ezxml_t xmlDoc, dataNode;
PianoReturn_t ret;
if ((ret = PianoXmlInitDoc (xml, &xmlDoc)) != PIANO_RET_OK) {
return ret;
}
dataNode = ezxml_get (xmlDoc, "params", 0, "param", 0, "value", -1);
if (strcmp (ezxml_txt (dataNode), "1") == 0) {
ret = PIANO_RET_OK;
} else {
ret = PIANO_RET_ERR;
}
ezxml_free (xmlDoc);
return ret;
}
/* xml struct parser callback, used in PianoXmlParseSearchCb
*/
static void PianoXmlParseSearchArtistCb (const char *key, const ezxml_t value,
void *data) {
PianoArtist_t *artist = data;
char *valueStr = PianoXmlGetNodeText (value);
if (strcmp ("artistName", key) == 0) {
artist->name = strdup (valueStr);
} else if (strcmp ("musicId", key) == 0) {
artist->musicId = strdup (valueStr);
}
}
/* callback for xml struct parser used in PianoXmlParseSearch, "switch" for
* PianoXmlParseSearchArtistCb and PianoXmlParsePlaylistCb
*/
static void PianoXmlParseSearchCb (const char *key, const ezxml_t value,
void *data) {
PianoSearchResult_t *searchResult = data;
ezxml_t curNode;
if (strcmp ("artists", key) == 0) {
/* skip <value><array><data> */
for (curNode = ezxml_child (ezxml_get (value, "array", 0, "data", -1), "value");
curNode; curNode = curNode->next) {
PianoArtist_t *artist;
if ((artist = calloc (1, sizeof (*artist))) == NULL) {
/* fail silently */
break;
}
memset (artist, 0, sizeof (*artist));
PianoXmlStructParser (ezxml_child (curNode, "struct"),
PianoXmlParseSearchArtistCb, artist);
/* add result to linked list */
if (searchResult->artists == NULL) {
searchResult->artists = artist;
} else {
PianoArtist_t *curArtist = searchResult->artists;
while (curArtist->next != NULL) {
curArtist = curArtist->next;
}
curArtist->next = artist;
}
}
} else if (strcmp ("songs", key) == 0) {
for (curNode = ezxml_child (ezxml_get (value, "array", 0, "data", -1), "value");
curNode; curNode = curNode->next) {
/* FIXME: copy & waste */
PianoSong_t *tmpSong;
if ((tmpSong = calloc (1, sizeof (*tmpSong))) == NULL) {
/* fail silently */
break;
}
PianoXmlStructParser (ezxml_child (curNode, "struct"),
PianoXmlParsePlaylistCb, tmpSong);
/* begin linked list or append */
if (searchResult->songs == NULL) {
searchResult->songs = tmpSong;
} else {
PianoSong_t *curSong = searchResult->songs;
while (curSong->next != NULL) {
curSong = curSong->next;
}
curSong->next = tmpSong;
}
}
}
}
/* parse search result; searchResult is nulled before use
* @param xml document
* @param returns search result
* @return nothing yet
*/
PianoReturn_t PianoXmlParseSearch (char *xml,
PianoSearchResult_t *searchResult) {
ezxml_t xmlDoc, dataNode;
PianoReturn_t ret;
if ((ret = PianoXmlInitDoc (xml, &xmlDoc)) != PIANO_RET_OK) {
return ret;
}
dataNode = ezxml_get (xmlDoc, "params", 0, "param", 0, "value", 0, "struct", -1);
/* we need a "clean" search result (with null pointers) */
memset (searchResult, 0, sizeof (*searchResult));
PianoXmlStructParser (dataNode, PianoXmlParseSearchCb, searchResult);
ezxml_free (xmlDoc);
return PIANO_RET_OK;
}
/* FIXME: copy&waste (PianoXmlParseSearch)
*/
PianoReturn_t PianoXmlParseSeedSuggestions (char *xml,
PianoSearchResult_t *searchResult) {
ezxml_t xmlDoc, dataNode;
PianoReturn_t ret;
if ((ret = PianoXmlInitDoc (xml, &xmlDoc)) != PIANO_RET_OK) {
return ret;
}
dataNode = ezxml_get (xmlDoc, "params", 0, "param", 0, "value", -1);
/* we need a "clean" search result (with null pointers) */
memset (searchResult, 0, sizeof (*searchResult));
/* reuse seach result parser; structure is nearly the same */
PianoXmlParseSearchCb ("artists", dataNode, searchResult);
ezxml_free (xmlDoc);
return PIANO_RET_OK;
}
/* encode reserved xml chars
* TODO: remove and use ezxml_ampencode
* @param encode this
* @return encoded string or NULL
*/
char *PianoXmlEncodeString (const char *s) {
char *replacements[] = {"&&", "''", "\""", "<<",
">>", NULL};
char **r, *sOut, *sOutCurr, found;
if ((sOut = calloc (strlen (s) * 5 + 1, sizeof (*sOut))) == NULL) {
return NULL;
}
sOutCurr = sOut;
while (*s != '\0') {
r = replacements;
found = 0;
while (*r != NULL) {
if (*s == *r[0]) {
found = 1;
strcat (sOutCurr, (*r) + 1);
sOutCurr += strlen ((*r) + 1);
break;
}
r++;
}
if (!found) {
*sOutCurr = *s;
sOutCurr++;
}
s++;
}
return sOut;
}
PianoReturn_t PianoXmlParseGenreExplorer (PianoHandle_t *ph, char *xml) {
ezxml_t xmlDoc, catNode;
PianoReturn_t ret;
if ((ret = PianoXmlInitDoc (xml, &xmlDoc)) != PIANO_RET_OK) {
return ret;
}
/* get all <member> nodes */
for (catNode = ezxml_child (xmlDoc, "category"); catNode;
catNode = catNode->next) {
PianoGenreCategory_t *tmpGenreCategory;
ezxml_t genreNode;
if ((tmpGenreCategory = calloc (1, sizeof (*tmpGenreCategory))) == NULL) {
ezxml_free (xmlDoc);
return PIANO_RET_OUT_OF_MEMORY;
}
tmpGenreCategory->name = strdup (ezxml_attr (catNode, "categoryName"));
/* get genre subnodes */
for (genreNode = ezxml_child (catNode, "genre"); genreNode;
genreNode = genreNode->next) {
PianoGenre_t *tmpGenre;
if ((tmpGenre = calloc (1, sizeof (*tmpGenre))) == NULL) {
ezxml_free (xmlDoc);
return PIANO_RET_OUT_OF_MEMORY;
}
/* get genre attributes */
tmpGenre->name = strdup (ezxml_attr (genreNode, "name"));
tmpGenre->musicId = strdup (ezxml_attr (genreNode, "musicId"));
/* append station */
if (tmpGenreCategory->genres == NULL) {
tmpGenreCategory->genres = tmpGenre;
} else {
PianoGenre_t *curGenre =
tmpGenreCategory->genres;
while (curGenre->next != NULL) {
curGenre = curGenre->next;
}
curGenre->next = tmpGenre;
}
}
/* append category */
if (ph->genreStations == NULL) {
ph->genreStations = tmpGenreCategory;
} else {
PianoGenreCategory_t *curCat = ph->genreStations;
while (curCat->next != NULL) {
curCat = curCat->next;
}
curCat->next = tmpGenreCategory;
}
}
ezxml_free (xmlDoc);
return PIANO_RET_OK;
}
/* dummy function, only checks for errors
* @param xml doc
* @return _OK or error
*/
PianoReturn_t PianoXmlParseTranformStation (char *xml) {
ezxml_t xmlDoc;
PianoReturn_t ret;
if ((ret = PianoXmlInitDoc (xml, &xmlDoc)) != PIANO_RET_OK) {
return ret;
}
ezxml_free (xmlDoc);
return PIANO_RET_OK;
}
/* parses "why did you play ...?" answer
* @param xml
* @param returns the answer
* @return _OK or error
*/
PianoReturn_t PianoXmlParseNarrative (char *xml, char **retNarrative) {
ezxml_t xmlDoc, dataNode;
PianoReturn_t ret;
if ((ret = PianoXmlInitDoc (xml, &xmlDoc)) != PIANO_RET_OK) {
return ret;
}
/* <methodResponse> <params> <param> <value> $textnode */
dataNode = ezxml_get (xmlDoc, "params", 0, "param", 0, "value", -1);
*retNarrative = strdup (ezxml_txt (dataNode));
ezxml_free (xmlDoc);
return ret;
}
|
734974.c | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2015, Daniel Stenberg, <[email protected]>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#include <curl/curl.h>
#include "urldata.h"
#include "transfer.h"
#include "url.h"
#include "connect.h"
#include "progress.h"
#include "easyif.h"
#include "share.h"
#include "multiif.h"
#include "sendf.h"
#include "timeval.h"
#include "http.h"
#include "select.h"
#include "warnless.h"
#include "speedcheck.h"
#include "conncache.h"
#include "bundles.h"
#include "multihandle.h"
#include "pipeline.h"
#include "sigpipe.h"
#define _MPRINTF_REPLACE /* use our functions only */
#include <curl/mprintf.h>
#include "curl_memory.h"
/* The last #include file should be: */
#include "memdebug.h"
/*
CURL_SOCKET_HASH_TABLE_SIZE should be a prime number. Increasing it from 97
to 911 takes on a 32-bit machine 4 x 804 = 3211 more bytes. Still, every
CURL handle takes 45-50 K memory, therefore this 3K are not significant.
*/
#ifndef CURL_SOCKET_HASH_TABLE_SIZE
#define CURL_SOCKET_HASH_TABLE_SIZE 911
#endif
#define CURL_CONNECTION_HASH_SIZE 97
#define CURL_MULTI_HANDLE 0x000bab1e
#define GOOD_MULTI_HANDLE(x) \
((x) && (((struct Curl_multi *)(x))->type == CURL_MULTI_HANDLE))
#define GOOD_EASY_HANDLE(x) \
((x) && (((struct SessionHandle *)(x))->magic == CURLEASY_MAGIC_NUMBER))
static void singlesocket(struct Curl_multi *multi,
struct SessionHandle *data);
static int update_timer(struct Curl_multi *multi);
static bool isHandleAtHead(struct SessionHandle *handle,
struct curl_llist *pipeline);
static CURLMcode add_next_timeout(struct timeval now,
struct Curl_multi *multi,
struct SessionHandle *d);
static CURLMcode multi_timeout(struct Curl_multi *multi,
long *timeout_ms);
#ifdef DEBUGBUILD
static const char * const statename[]={
"INIT",
"CONNECT_PEND",
"CONNECT",
"WAITRESOLVE",
"WAITCONNECT",
"WAITPROXYCONNECT",
"PROTOCONNECT",
"WAITDO",
"DO",
"DOING",
"DO_MORE",
"DO_DONE",
"WAITPERFORM",
"PERFORM",
"TOOFAST",
"DONE",
"COMPLETED",
"MSGSENT",
};
#endif
static void multi_freetimeout(void *a, void *b);
/* always use this function to change state, to make debugging easier */
static void mstate(struct SessionHandle *data, CURLMstate state
#ifdef DEBUGBUILD
, int lineno
#endif
)
{
CURLMstate oldstate = data->mstate;
#if defined(DEBUGBUILD) && defined(CURL_DISABLE_VERBOSE_STRINGS)
(void) lineno;
#endif
if(oldstate == state)
/* don't bother when the new state is the same as the old state */
return;
data->mstate = state;
#if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
if(data->mstate >= CURLM_STATE_CONNECT_PEND &&
data->mstate < CURLM_STATE_COMPLETED) {
long connection_id = -5000;
if(data->easy_conn)
connection_id = data->easy_conn->connection_id;
infof(data,
"STATE: %s => %s handle %p; line %d (connection #%ld) \n",
statename[oldstate], statename[data->mstate],
(void *)data, lineno, connection_id);
}
#endif
if(state == CURLM_STATE_COMPLETED)
/* changing to COMPLETED means there's one less easy handle 'alive' */
data->multi->num_alive--;
}
#ifndef DEBUGBUILD
#define multistate(x,y) mstate(x,y)
#else
#define multistate(x,y) mstate(x,y, __LINE__)
#endif
/*
* We add one of these structs to the sockhash for a particular socket
*/
struct Curl_sh_entry {
struct SessionHandle *easy;
time_t timestamp;
int action; /* what action READ/WRITE this socket waits for */
curl_socket_t socket; /* mainly to ease debugging */
void *socketp; /* settable by users with curl_multi_assign() */
};
/* bits for 'action' having no bits means this socket is not expecting any
action */
#define SH_READ 1
#define SH_WRITE 2
/* make sure this socket is present in the hash for this handle */
static struct Curl_sh_entry *sh_addentry(struct curl_hash *sh,
curl_socket_t s,
struct SessionHandle *data)
{
struct Curl_sh_entry *there =
Curl_hash_pick(sh, (char *)&s, sizeof(curl_socket_t));
struct Curl_sh_entry *check;
if(there)
/* it is present, return fine */
return there;
/* not present, add it */
check = calloc(1, sizeof(struct Curl_sh_entry));
if(!check)
return NULL; /* major failure */
check->easy = data;
check->socket = s;
/* make/add new hash entry */
if(!Curl_hash_add(sh, (char *)&s, sizeof(curl_socket_t), check)) {
free(check);
return NULL; /* major failure */
}
return check; /* things are good in sockhash land */
}
/* delete the given socket + handle from the hash */
static void sh_delentry(struct curl_hash *sh, curl_socket_t s)
{
struct Curl_sh_entry *there =
Curl_hash_pick(sh, (char *)&s, sizeof(curl_socket_t));
if(there) {
/* this socket is in the hash */
/* We remove the hash entry. (This'll end up in a call to
sh_freeentry().) */
Curl_hash_delete(sh, (char *)&s, sizeof(curl_socket_t));
}
}
/*
* free a sockhash entry
*/
static void sh_freeentry(void *freethis)
{
struct Curl_sh_entry *p = (struct Curl_sh_entry *) freethis;
if(p)
free(p);
}
static size_t fd_key_compare(void *k1, size_t k1_len, void *k2, size_t k2_len)
{
(void) k1_len; (void) k2_len;
return (*((int *) k1)) == (*((int *) k2));
}
static size_t hash_fd(void *key, size_t key_length, size_t slots_num)
{
int fd = *((int *) key);
(void) key_length;
return (fd % (int)slots_num);
}
/*
* sh_init() creates a new socket hash and returns the handle for it.
*
* Quote from README.multi_socket:
*
* "Some tests at 7000 and 9000 connections showed that the socket hash lookup
* is somewhat of a bottle neck. Its current implementation may be a bit too
* limiting. It simply has a fixed-size array, and on each entry in the array
* it has a linked list with entries. So the hash only checks which list to
* scan through. The code I had used so for used a list with merely 7 slots
* (as that is what the DNS hash uses) but with 7000 connections that would
* make an average of 1000 nodes in each list to run through. I upped that to
* 97 slots (I believe a prime is suitable) and noticed a significant speed
* increase. I need to reconsider the hash implementation or use a rather
* large default value like this. At 9000 connections I was still below 10us
* per call."
*
*/
static struct curl_hash *sh_init(int hashsize)
{
return Curl_hash_alloc(hashsize, hash_fd, fd_key_compare,
sh_freeentry);
}
/*
* multi_addmsg()
*
* Called when a transfer is completed. Adds the given msg pointer to
* the list kept in the multi handle.
*/
static CURLMcode multi_addmsg(struct Curl_multi *multi,
struct Curl_message *msg)
{
if(!Curl_llist_insert_next(multi->msglist, multi->msglist->tail, msg))
return CURLM_OUT_OF_MEMORY;
return CURLM_OK;
}
/*
* multi_freeamsg()
*
* Callback used by the llist system when a single list entry is destroyed.
*/
static void multi_freeamsg(void *a, void *b)
{
(void)a;
(void)b;
}
struct Curl_multi *Curl_multi_handle(int hashsize, /* socket hash */
int chashsize) /* connection hash */
{
struct Curl_multi *multi = calloc(1, sizeof(struct Curl_multi));
if(!multi)
return NULL;
multi->type = CURL_MULTI_HANDLE;
multi->hostcache = Curl_mk_dnscache();
if(!multi->hostcache)
goto error;
multi->sockhash = sh_init(hashsize);
if(!multi->sockhash)
goto error;
multi->conn_cache = Curl_conncache_init(chashsize);
if(!multi->conn_cache)
goto error;
multi->msglist = Curl_llist_alloc(multi_freeamsg);
if(!multi->msglist)
goto error;
multi->pending = Curl_llist_alloc(multi_freeamsg);
if(!multi->pending)
goto error;
/* allocate a new easy handle to use when closing cached connections */
multi->closure_handle = curl_easy_init();
if(!multi->closure_handle)
goto error;
multi->closure_handle->multi = multi;
multi->closure_handle->state.conn_cache = multi->conn_cache;
multi->max_pipeline_length = 5;
/* -1 means it not set by user, use the default value */
multi->maxconnects = -1;
return (CURLM *) multi;
error:
Curl_hash_destroy(multi->sockhash);
multi->sockhash = NULL;
Curl_hash_destroy(multi->hostcache);
multi->hostcache = NULL;
Curl_conncache_destroy(multi->conn_cache);
multi->conn_cache = NULL;
Curl_close(multi->closure_handle);
multi->closure_handle = NULL;
Curl_llist_destroy(multi->msglist, NULL);
Curl_llist_destroy(multi->pending, NULL);
free(multi);
return NULL;
}
CURLM *curl_multi_init(void)
{
return Curl_multi_handle(CURL_SOCKET_HASH_TABLE_SIZE,
CURL_CONNECTION_HASH_SIZE);
}
CURLMcode curl_multi_add_handle(CURLM *multi_handle,
CURL *easy_handle)
{
struct curl_llist *timeoutlist;
struct Curl_multi *multi = (struct Curl_multi *)multi_handle;
struct SessionHandle *data = (struct SessionHandle *)easy_handle;
/* First, make some basic checks that the CURLM handle is a good handle */
if(!GOOD_MULTI_HANDLE(multi))
return CURLM_BAD_HANDLE;
/* Verify that we got a somewhat good easy handle too */
if(!GOOD_EASY_HANDLE(easy_handle))
return CURLM_BAD_EASY_HANDLE;
/* Prevent users from adding same easy handle more than once and prevent
adding to more than one multi stack */
if(data->multi)
return CURLM_ADDED_ALREADY;
/* Allocate and initialize timeout list for easy handle */
timeoutlist = Curl_llist_alloc(multi_freetimeout);
if(!timeoutlist)
return CURLM_OUT_OF_MEMORY;
/*
* No failure allowed in this function beyond this point. And no
* modification of easy nor multi handle allowed before this except for
* potential multi's connection cache growing which won't be undone in this
* function no matter what.
*/
/* Make easy handle use timeout list initialized above */
data->state.timeoutlist = timeoutlist;
timeoutlist = NULL;
/* set the easy handle */
multistate(data, CURLM_STATE_INIT);
if((data->set.global_dns_cache) &&
(data->dns.hostcachetype != HCACHE_GLOBAL)) {
/* global dns cache was requested but still isn't */
struct curl_hash *global = Curl_global_host_cache_init();
if(global) {
/* only do this if the global cache init works */
data->dns.hostcache = global;
data->dns.hostcachetype = HCACHE_GLOBAL;
}
}
/* for multi interface connections, we share DNS cache automatically if the
easy handle's one is currently not set. */
else if(!data->dns.hostcache ||
(data->dns.hostcachetype == HCACHE_NONE)) {
data->dns.hostcache = multi->hostcache;
data->dns.hostcachetype = HCACHE_MULTI;
}
/* Point to the multi's connection cache */
data->state.conn_cache = multi->conn_cache;
data->state.infilesize = data->set.filesize;
/* This adds the new entry at the 'end' of the doubly-linked circular
list of SessionHandle structs to try and maintain a FIFO queue so
the pipelined requests are in order. */
/* We add this new entry last in the list. */
data->next = NULL; /* end of the line */
if(multi->easyp) {
struct SessionHandle *last = multi->easylp;
last->next = data;
data->prev = last;
multi->easylp = data; /* the new last node */
}
else {
/* first node, make both prev and next be NULL! */
data->next = NULL;
data->prev = NULL;
multi->easylp = multi->easyp = data; /* both first and last */
}
/* make the SessionHandle refer back to this multi handle */
data->multi = multi_handle;
/* Set the timeout for this handle to expire really soon so that it will
be taken care of even when this handle is added in the midst of operation
when only the curl_multi_socket() API is used. During that flow, only
sockets that time-out or have actions will be dealt with. Since this
handle has no action yet, we make sure it times out to get things to
happen. */
Curl_expire(data, 1);
/* increase the node-counter */
multi->num_easy++;
/* increase the alive-counter */
multi->num_alive++;
/* A somewhat crude work-around for a little glitch in update_timer() that
happens if the lastcall time is set to the same time when the handle is
removed as when the next handle is added, as then the check in
update_timer() that prevents calling the application multiple times with
the same timer infor will not trigger and then the new handle's timeout
will not be notified to the app.
The work-around is thus simply to clear the 'lastcall' variable to force
update_timer() to always trigger a callback to the app when a new easy
handle is added */
memset(&multi->timer_lastcall, 0, sizeof(multi->timer_lastcall));
update_timer(multi);
return CURLM_OK;
}
#if 0
/* Debug-function, used like this:
*
* Curl_hash_print(multi->sockhash, debug_print_sock_hash);
*
* Enable the hash print function first by editing hash.c
*/
static void debug_print_sock_hash(void *p)
{
struct Curl_sh_entry *sh = (struct Curl_sh_entry *)p;
fprintf(stderr, " [easy %p/magic %x/socket %d]",
(void *)sh->data, sh->data->magic, (int)sh->socket);
}
#endif
CURLMcode curl_multi_remove_handle(CURLM *multi_handle,
CURL *curl_handle)
{
struct Curl_multi *multi=(struct Curl_multi *)multi_handle;
struct SessionHandle *easy = curl_handle;
struct SessionHandle *data = easy;
bool premature;
bool easy_owns_conn;
struct curl_llist_element *e;
/* First, make some basic checks that the CURLM handle is a good handle */
if(!GOOD_MULTI_HANDLE(multi))
return CURLM_BAD_HANDLE;
/* Verify that we got a somewhat good easy handle too */
if(!GOOD_EASY_HANDLE(curl_handle))
return CURLM_BAD_EASY_HANDLE;
/* Prevent users from trying to remove same easy handle more than once */
if(!data->multi)
return CURLM_OK; /* it is already removed so let's say it is fine! */
premature = (data->mstate < CURLM_STATE_COMPLETED) ? TRUE : FALSE;
easy_owns_conn = (data->easy_conn && (data->easy_conn->data == easy)) ?
TRUE : FALSE;
/* If the 'state' is not INIT or COMPLETED, we might need to do something
nice to put the easy_handle in a good known state when this returns. */
if(premature)
/* this handle is "alive" so we need to count down the total number of
alive connections when this is removed */
multi->num_alive--;
if(data->easy_conn &&
data->mstate > CURLM_STATE_DO &&
data->mstate < CURLM_STATE_COMPLETED) {
/* If the handle is in a pipeline and has started sending off its
request but not received its response yet, we need to close
connection. */
connclose(data->easy_conn, "Removed with partial response");
/* Set connection owner so that Curl_done() closes it.
We can safely do this here since connection is killed. */
data->easy_conn->data = easy;
easy_owns_conn = TRUE;
}
/* The timer must be shut down before data->multi is set to NULL,
else the timenode will remain in the splay tree after
curl_easy_cleanup is called. */
Curl_expire(data, 0);
/* destroy the timeout list that is held in the easy handle */
if(data->state.timeoutlist) {
Curl_llist_destroy(data->state.timeoutlist, NULL);
data->state.timeoutlist = NULL;
}
if(data->dns.hostcachetype == HCACHE_MULTI) {
/* stop using the multi handle's DNS cache */
data->dns.hostcache = NULL;
data->dns.hostcachetype = HCACHE_NONE;
}
if(data->easy_conn) {
/* we must call Curl_done() here (if we still "own it") so that we don't
leave a half-baked one around */
if(easy_owns_conn) {
/* Curl_done() clears the conn->data field to lose the association
between the easy handle and the connection
Note that this ignores the return code simply because there's
nothing really useful to do with it anyway! */
(void)Curl_done(&data->easy_conn, data->result, premature);
}
else
/* Clear connection pipelines, if Curl_done above was not called */
Curl_getoff_all_pipelines(data, data->easy_conn);
}
Curl_wildcard_dtor(&data->wildcard);
/* as this was using a shared connection cache we clear the pointer to that
since we're not part of that multi handle anymore */
data->state.conn_cache = NULL;
/* change state without using multistate(), only to make singlesocket() do
what we want */
data->mstate = CURLM_STATE_COMPLETED;
singlesocket(multi, easy); /* to let the application know what sockets that
vanish with this handle */
/* Remove the association between the connection and the handle */
if(data->easy_conn) {
data->easy_conn->data = NULL;
data->easy_conn = NULL;
}
data->multi = NULL; /* clear the association to this multi handle */
/* make sure there's no pending message in the queue sent from this easy
handle */
for(e = multi->msglist->head; e; e = e->next) {
struct Curl_message *msg = e->ptr;
if(msg->extmsg.easy_handle == easy) {
Curl_llist_remove(multi->msglist, e, NULL);
/* there can only be one from this specific handle */
break;
}
}
/* make the previous node point to our next */
if(data->prev)
data->prev->next = data->next;
else
multi->easyp = data->next; /* point to first node */
/* make our next point to our previous node */
if(data->next)
data->next->prev = data->prev;
else
multi->easylp = data->prev; /* point to last node */
/* NOTE NOTE NOTE
We do not touch the easy handle here! */
multi->num_easy--; /* one less to care about now */
update_timer(multi);
return CURLM_OK;
}
bool Curl_multi_pipeline_enabled(const struct Curl_multi *multi)
{
return (multi && multi->pipelining_enabled) ? TRUE : FALSE;
}
void Curl_multi_handlePipeBreak(struct SessionHandle *data)
{
data->easy_conn = NULL;
}
static int waitconnect_getsock(struct connectdata *conn,
curl_socket_t *sock,
int numsocks)
{
int i;
int s=0;
int rc=0;
if(!numsocks)
return GETSOCK_BLANK;
for(i=0; i<2; i++) {
if(conn->tempsock[i] != CURL_SOCKET_BAD) {
sock[s] = conn->tempsock[i];
rc |= GETSOCK_WRITESOCK(s++);
}
}
/* when we've sent a CONNECT to a proxy, we should rather wait for the
socket to become readable to be able to get the response headers */
if(conn->tunnel_state[FIRSTSOCKET] == TUNNEL_CONNECT) {
sock[0] = conn->sock[FIRSTSOCKET];
rc = GETSOCK_READSOCK(0);
}
return rc;
}
static int domore_getsock(struct connectdata *conn,
curl_socket_t *socks,
int numsocks)
{
if(conn && conn->handler->domore_getsock)
return conn->handler->domore_getsock(conn, socks, numsocks);
return GETSOCK_BLANK;
}
/* returns bitmapped flags for this handle and its sockets */
static int multi_getsock(struct SessionHandle *data,
curl_socket_t *socks, /* points to numsocks number
of sockets */
int numsocks)
{
/* If the pipe broke, or if there's no connection left for this easy handle,
then we MUST bail out now with no bitmask set. The no connection case can
happen when this is called from curl_multi_remove_handle() =>
singlesocket() => multi_getsock().
*/
if(data->state.pipe_broke || !data->easy_conn)
return 0;
if(data->mstate > CURLM_STATE_CONNECT &&
data->mstate < CURLM_STATE_COMPLETED) {
/* Set up ownership correctly */
data->easy_conn->data = data;
}
switch(data->mstate) {
default:
#if 0 /* switch back on these cases to get the compiler to check for all enums
to be present */
case CURLM_STATE_TOOFAST: /* returns 0, so will not select. */
case CURLM_STATE_COMPLETED:
case CURLM_STATE_MSGSENT:
case CURLM_STATE_INIT:
case CURLM_STATE_CONNECT:
case CURLM_STATE_WAITDO:
case CURLM_STATE_DONE:
case CURLM_STATE_LAST:
/* this will get called with CURLM_STATE_COMPLETED when a handle is
removed */
#endif
return 0;
case CURLM_STATE_WAITRESOLVE:
return Curl_resolver_getsock(data->easy_conn, socks, numsocks);
case CURLM_STATE_PROTOCONNECT:
return Curl_protocol_getsock(data->easy_conn, socks, numsocks);
case CURLM_STATE_DO:
case CURLM_STATE_DOING:
return Curl_doing_getsock(data->easy_conn, socks, numsocks);
case CURLM_STATE_WAITPROXYCONNECT:
case CURLM_STATE_WAITCONNECT:
return waitconnect_getsock(data->easy_conn, socks, numsocks);
case CURLM_STATE_DO_MORE:
return domore_getsock(data->easy_conn, socks, numsocks);
case CURLM_STATE_DO_DONE: /* since is set after DO is completed, we switch
to waiting for the same as the *PERFORM
states */
case CURLM_STATE_PERFORM:
case CURLM_STATE_WAITPERFORM:
return Curl_single_getsock(data->easy_conn, socks, numsocks);
}
}
CURLMcode curl_multi_fdset(CURLM *multi_handle,
fd_set *read_fd_set, fd_set *write_fd_set,
fd_set *exc_fd_set, int *max_fd)
{
/* Scan through all the easy handles to get the file descriptors set.
Some easy handles may not have connected to the remote host yet,
and then we must make sure that is done. */
struct Curl_multi *multi=(struct Curl_multi *)multi_handle;
struct SessionHandle *data;
int this_max_fd=-1;
curl_socket_t sockbunch[MAX_SOCKSPEREASYHANDLE];
int bitmap;
int i;
(void)exc_fd_set; /* not used */
if(!GOOD_MULTI_HANDLE(multi))
return CURLM_BAD_HANDLE;
data=multi->easyp;
while(data) {
bitmap = multi_getsock(data, sockbunch, MAX_SOCKSPEREASYHANDLE);
for(i=0; i< MAX_SOCKSPEREASYHANDLE; i++) {
curl_socket_t s = CURL_SOCKET_BAD;
if((bitmap & GETSOCK_READSOCK(i)) && VALID_SOCK((sockbunch[i]))) {
FD_SET(sockbunch[i], read_fd_set);
s = sockbunch[i];
}
if((bitmap & GETSOCK_WRITESOCK(i)) && VALID_SOCK((sockbunch[i]))) {
FD_SET(sockbunch[i], write_fd_set);
s = sockbunch[i];
}
if(s == CURL_SOCKET_BAD)
/* this socket is unused, break out of loop */
break;
else {
if((int)s > this_max_fd)
this_max_fd = (int)s;
}
}
data = data->next; /* check next handle */
}
*max_fd = this_max_fd;
return CURLM_OK;
}
CURLMcode curl_multi_wait(CURLM *multi_handle,
struct curl_waitfd extra_fds[],
unsigned int extra_nfds,
int timeout_ms,
int *ret)
{
struct Curl_multi *multi=(struct Curl_multi *)multi_handle;
struct SessionHandle *data;
curl_socket_t sockbunch[MAX_SOCKSPEREASYHANDLE];
int bitmap;
unsigned int i;
unsigned int nfds = 0;
unsigned int curlfds;
struct pollfd *ufds = NULL;
long timeout_internal;
if(!GOOD_MULTI_HANDLE(multi))
return CURLM_BAD_HANDLE;
/* If the internally desired timeout is actually shorter than requested from
the outside, then use the shorter time! But only if the internal timer
is actually larger than -1! */
(void)multi_timeout(multi, &timeout_internal);
if((timeout_internal >= 0) && (timeout_internal < (long)timeout_ms))
timeout_ms = (int)timeout_internal;
/* Count up how many fds we have from the multi handle */
data=multi->easyp;
while(data) {
bitmap = multi_getsock(data, sockbunch, MAX_SOCKSPEREASYHANDLE);
for(i=0; i< MAX_SOCKSPEREASYHANDLE; i++) {
curl_socket_t s = CURL_SOCKET_BAD;
if(bitmap & GETSOCK_READSOCK(i)) {
++nfds;
s = sockbunch[i];
}
if(bitmap & GETSOCK_WRITESOCK(i)) {
++nfds;
s = sockbunch[i];
}
if(s == CURL_SOCKET_BAD) {
break;
}
}
data = data->next; /* check next handle */
}
curlfds = nfds; /* number of internal file descriptors */
nfds += extra_nfds; /* add the externally provided ones */
if(nfds || extra_nfds) {
ufds = malloc(nfds * sizeof(struct pollfd));
if(!ufds)
return CURLM_OUT_OF_MEMORY;
}
nfds = 0;
/* only do the second loop if we found descriptors in the first stage run
above */
if(curlfds) {
/* Add the curl handles to our pollfds first */
data=multi->easyp;
while(data) {
bitmap = multi_getsock(data, sockbunch, MAX_SOCKSPEREASYHANDLE);
for(i=0; i< MAX_SOCKSPEREASYHANDLE; i++) {
curl_socket_t s = CURL_SOCKET_BAD;
if(bitmap & GETSOCK_READSOCK(i)) {
ufds[nfds].fd = sockbunch[i];
ufds[nfds].events = POLLIN;
++nfds;
s = sockbunch[i];
}
if(bitmap & GETSOCK_WRITESOCK(i)) {
ufds[nfds].fd = sockbunch[i];
ufds[nfds].events = POLLOUT;
++nfds;
s = sockbunch[i];
}
if(s == CURL_SOCKET_BAD) {
break;
}
}
data = data->next; /* check next handle */
}
}
/* Add external file descriptions from poll-like struct curl_waitfd */
for(i = 0; i < extra_nfds; i++) {
ufds[nfds].fd = extra_fds[i].fd;
ufds[nfds].events = 0;
if(extra_fds[i].events & CURL_WAIT_POLLIN)
ufds[nfds].events |= POLLIN;
if(extra_fds[i].events & CURL_WAIT_POLLPRI)
ufds[nfds].events |= POLLPRI;
if(extra_fds[i].events & CURL_WAIT_POLLOUT)
ufds[nfds].events |= POLLOUT;
++nfds;
}
if(nfds) {
/* wait... */
infof(data, "Curl_poll(%d ds, %d ms)\n", nfds, timeout_ms);
i = Curl_poll(ufds, nfds, timeout_ms);
if(i) {
unsigned int j;
/* copy revents results from the poll to the curl_multi_wait poll
struct, the bit values of the actual underlying poll() implementation
may not be the same as the ones in the public libcurl API! */
for(j = 0; j < extra_nfds; j++) {
unsigned short mask = 0;
unsigned r = ufds[curlfds + j].revents;
if(r & POLLIN)
mask |= CURL_WAIT_POLLIN;
if(r & POLLOUT)
mask |= CURL_WAIT_POLLOUT;
if(r & POLLPRI)
mask |= CURL_WAIT_POLLPRI;
extra_fds[j].revents = mask;
}
}
}
else
i = 0;
Curl_safefree(ufds);
if(ret)
*ret = i;
return CURLM_OK;
}
static CURLMcode multi_runsingle(struct Curl_multi *multi,
struct timeval now,
struct SessionHandle *data)
{
struct Curl_message *msg = NULL;
bool connected;
bool async;
bool protocol_connect = FALSE;
bool dophase_done = FALSE;
bool done = FALSE;
CURLMcode rc;
CURLcode result = CURLE_OK;
struct SingleRequest *k;
long timeout_ms;
int control;
if(!GOOD_EASY_HANDLE(data))
return CURLM_BAD_EASY_HANDLE;
do {
bool disconnect_conn = FALSE;
rc = CURLM_OK;
/* Handle the case when the pipe breaks, i.e., the connection
we're using gets cleaned up and we're left with nothing. */
if(data->state.pipe_broke) {
infof(data, "Pipe broke: handle %p, url = %s\n",
(void *)data, data->state.path);
if(data->mstate < CURLM_STATE_COMPLETED) {
/* Head back to the CONNECT state */
multistate(data, CURLM_STATE_CONNECT);
rc = CURLM_CALL_MULTI_PERFORM;
result = CURLE_OK;
}
data->state.pipe_broke = FALSE;
data->easy_conn = NULL;
continue;
}
if(!data->easy_conn &&
data->mstate > CURLM_STATE_CONNECT &&
data->mstate < CURLM_STATE_DONE) {
/* In all these states, the code will blindly access 'data->easy_conn'
so this is precaution that it isn't NULL. And it silences static
analyzers. */
failf(data, "In state %d with no easy_conn, bail out!\n", data->mstate);
return CURLM_INTERNAL_ERROR;
}
if(data->easy_conn && data->mstate > CURLM_STATE_CONNECT &&
data->mstate < CURLM_STATE_COMPLETED)
/* Make sure we set the connection's current owner */
data->easy_conn->data = data;
if(data->easy_conn &&
(data->mstate >= CURLM_STATE_CONNECT) &&
(data->mstate < CURLM_STATE_COMPLETED)) {
/* we need to wait for the connect state as only then is the start time
stored, but we must not check already completed handles */
timeout_ms = Curl_timeleft(data, &now,
(data->mstate <= CURLM_STATE_WAITDO)?
TRUE:FALSE);
if(timeout_ms < 0) {
/* Handle timed out */
if(data->mstate == CURLM_STATE_WAITRESOLVE)
failf(data, "Resolving timed out after %ld milliseconds",
Curl_tvdiff(now, data->progress.t_startsingle));
else if(data->mstate == CURLM_STATE_WAITCONNECT)
failf(data, "Connection timed out after %ld milliseconds",
Curl_tvdiff(now, data->progress.t_startsingle));
else {
k = &data->req;
if(k->size != -1) {
failf(data, "Operation timed out after %ld milliseconds with %"
CURL_FORMAT_CURL_OFF_T " out of %"
CURL_FORMAT_CURL_OFF_T " bytes received",
Curl_tvdiff(k->now, data->progress.t_startsingle),
k->bytecount, k->size);
}
else {
failf(data, "Operation timed out after %ld milliseconds with %"
CURL_FORMAT_CURL_OFF_T " bytes received",
Curl_tvdiff(now, data->progress.t_startsingle),
k->bytecount);
}
}
/* Force connection closed if the connection has indeed been used */
if(data->mstate > CURLM_STATE_DO) {
connclose(data->easy_conn, "Disconnected with pending data");
disconnect_conn = TRUE;
}
result = CURLE_OPERATION_TIMEDOUT;
/* Skip the statemachine and go directly to error handling section. */
goto statemachine_end;
}
}
switch(data->mstate) {
case CURLM_STATE_INIT:
/* init this transfer. */
result=Curl_pretransfer(data);
if(!result) {
/* after init, go CONNECT */
multistate(data, CURLM_STATE_CONNECT);
Curl_pgrsTime(data, TIMER_STARTOP);
rc = CURLM_CALL_MULTI_PERFORM;
}
break;
case CURLM_STATE_CONNECT_PEND:
/* We will stay here until there is a connection available. Then
we try again in the CURLM_STATE_CONNECT state. */
break;
case CURLM_STATE_CONNECT:
/* Connect. We want to get a connection identifier filled in. */
Curl_pgrsTime(data, TIMER_STARTSINGLE);
result = Curl_connect(data, &data->easy_conn,
&async, &protocol_connect);
if(CURLE_NO_CONNECTION_AVAILABLE == result) {
/* There was no connection available. We will go to the pending
state and wait for an available connection. */
multistate(data, CURLM_STATE_CONNECT_PEND);
/* add this handle to the list of connect-pending handles */
if(!Curl_llist_insert_next(multi->pending, multi->pending->tail, data))
result = CURLE_OUT_OF_MEMORY;
else
result = CURLE_OK;
break;
}
if(!result) {
/* Add this handle to the send or pend pipeline */
result = Curl_add_handle_to_pipeline(data, data->easy_conn);
if(result)
disconnect_conn = TRUE;
else {
if(async)
/* We're now waiting for an asynchronous name lookup */
multistate(data, CURLM_STATE_WAITRESOLVE);
else {
/* after the connect has been sent off, go WAITCONNECT unless the
protocol connect is already done and we can go directly to
WAITDO or DO! */
rc = CURLM_CALL_MULTI_PERFORM;
if(protocol_connect)
multistate(data, multi->pipelining_enabled?
CURLM_STATE_WAITDO:CURLM_STATE_DO);
else {
#ifndef CURL_DISABLE_HTTP
if(data->easy_conn->tunnel_state[FIRSTSOCKET] == TUNNEL_CONNECT)
multistate(data, CURLM_STATE_WAITPROXYCONNECT);
else
#endif
multistate(data, CURLM_STATE_WAITCONNECT);
}
}
}
}
break;
case CURLM_STATE_WAITRESOLVE:
/* awaiting an asynch name resolve to complete */
{
struct Curl_dns_entry *dns = NULL;
struct connectdata *conn = data->easy_conn;
/* check if we have the name resolved by now */
if(data->share)
Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
dns = Curl_fetch_addr(conn, conn->host.name, (int)conn->port);
if(dns) {
dns->inuse++; /* we use it! */
#ifdef CURLRES_ASYNCH
conn->async.dns = dns;
conn->async.done = TRUE;
#endif
result = CURLE_OK;
infof(data, "Hostname was found in DNS cache\n");
}
if(data->share)
Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
if(!dns)
result = Curl_resolver_is_resolved(data->easy_conn, &dns);
/* Update sockets here, because the socket(s) may have been
closed and the application thus needs to be told, even if it
is likely that the same socket(s) will again be used further
down. If the name has not yet been resolved, it is likely
that new sockets have been opened in an attempt to contact
another resolver. */
singlesocket(multi, data);
if(dns) {
/* Perform the next step in the connection phase, and then move on
to the WAITCONNECT state */
result = Curl_async_resolved(data->easy_conn, &protocol_connect);
if(result)
/* if Curl_async_resolved() returns failure, the connection struct
is already freed and gone */
data->easy_conn = NULL; /* no more connection */
else {
/* call again please so that we get the next socket setup */
rc = CURLM_CALL_MULTI_PERFORM;
if(protocol_connect)
multistate(data, multi->pipelining_enabled?
CURLM_STATE_WAITDO:CURLM_STATE_DO);
else {
#ifndef CURL_DISABLE_HTTP
if(data->easy_conn->tunnel_state[FIRSTSOCKET] == TUNNEL_CONNECT)
multistate(data, CURLM_STATE_WAITPROXYCONNECT);
else
#endif
multistate(data, CURLM_STATE_WAITCONNECT);
}
}
}
if(result) {
/* failure detected */
disconnect_conn = TRUE;
break;
}
}
break;
#ifndef CURL_DISABLE_HTTP
case CURLM_STATE_WAITPROXYCONNECT:
/* this is HTTP-specific, but sending CONNECT to a proxy is HTTP... */
result = Curl_http_connect(data->easy_conn, &protocol_connect);
if(data->easy_conn->bits.proxy_connect_closed) {
/* connect back to proxy again */
result = CURLE_OK;
rc = CURLM_CALL_MULTI_PERFORM;
multistate(data, CURLM_STATE_CONNECT);
}
else if(!result) {
if(data->easy_conn->tunnel_state[FIRSTSOCKET] == TUNNEL_COMPLETE)
multistate(data, CURLM_STATE_WAITCONNECT);
}
break;
#endif
case CURLM_STATE_WAITCONNECT:
/* awaiting a completion of an asynch connect */
result = Curl_is_connected(data->easy_conn,
FIRSTSOCKET,
&connected);
if(connected) {
if(!result)
/* if everything is still fine we do the protocol-specific connect
setup */
result = Curl_protocol_connect(data->easy_conn,
&protocol_connect);
}
if(data->easy_conn->bits.proxy_connect_closed) {
/* connect back to proxy again since it was closed in a proxy CONNECT
setup */
result = CURLE_OK;
rc = CURLM_CALL_MULTI_PERFORM;
multistate(data, CURLM_STATE_CONNECT);
break;
}
else if(result) {
/* failure detected */
/* Just break, the cleaning up is handled all in one place */
disconnect_conn = TRUE;
break;
}
if(connected) {
if(!protocol_connect) {
/* We have a TCP connection, but 'protocol_connect' may be false
and then we continue to 'STATE_PROTOCONNECT'. If protocol
connect is TRUE, we move on to STATE_DO.
BUT if we are using a proxy we must change to WAITPROXYCONNECT
*/
#ifndef CURL_DISABLE_HTTP
if(data->easy_conn->tunnel_state[FIRSTSOCKET] == TUNNEL_CONNECT)
multistate(data, CURLM_STATE_WAITPROXYCONNECT);
else
#endif
multistate(data, CURLM_STATE_PROTOCONNECT);
}
else
/* after the connect has completed, go WAITDO or DO */
multistate(data, multi->pipelining_enabled?
CURLM_STATE_WAITDO:CURLM_STATE_DO);
rc = CURLM_CALL_MULTI_PERFORM;
}
break;
case CURLM_STATE_PROTOCONNECT:
/* protocol-specific connect phase */
result = Curl_protocol_connecting(data->easy_conn, &protocol_connect);
if(!result && protocol_connect) {
/* after the connect has completed, go WAITDO or DO */
multistate(data, multi->pipelining_enabled?
CURLM_STATE_WAITDO:CURLM_STATE_DO);
rc = CURLM_CALL_MULTI_PERFORM;
}
else if(result) {
/* failure detected */
Curl_posttransfer(data);
Curl_done(&data->easy_conn, result, TRUE);
disconnect_conn = TRUE;
}
break;
case CURLM_STATE_WAITDO:
/* Wait for our turn to DO when we're pipelining requests */
#ifdef DEBUGBUILD
infof(data, "WAITDO: Conn %ld send pipe %zu inuse %s athead %s\n",
data->easy_conn->connection_id,
data->easy_conn->send_pipe->size,
data->easy_conn->writechannel_inuse?"TRUE":"FALSE",
isHandleAtHead(data,
data->easy_conn->send_pipe)?"TRUE":"FALSE");
#endif
if(!data->easy_conn->writechannel_inuse &&
isHandleAtHead(data,
data->easy_conn->send_pipe)) {
/* Grab the channel */
data->easy_conn->writechannel_inuse = TRUE;
multistate(data, CURLM_STATE_DO);
rc = CURLM_CALL_MULTI_PERFORM;
}
break;
case CURLM_STATE_DO:
if(data->set.connect_only) {
/* keep connection open for application to use the socket */
connkeep(data->easy_conn, "CONNECT_ONLY");
multistate(data, CURLM_STATE_DONE);
result = CURLE_OK;
rc = CURLM_CALL_MULTI_PERFORM;
}
else {
/* Perform the protocol's DO action */
result = Curl_do(&data->easy_conn, &dophase_done);
/* When Curl_do() returns failure, data->easy_conn might be NULL! */
if(!result) {
if(!dophase_done) {
/* some steps needed for wildcard matching */
if(data->set.wildcardmatch) {
struct WildcardData *wc = &data->wildcard;
if(wc->state == CURLWC_DONE || wc->state == CURLWC_SKIP) {
/* skip some states if it is important */
Curl_done(&data->easy_conn, CURLE_OK, FALSE);
multistate(data, CURLM_STATE_DONE);
rc = CURLM_CALL_MULTI_PERFORM;
break;
}
}
/* DO was not completed in one function call, we must continue
DOING... */
multistate(data, CURLM_STATE_DOING);
rc = CURLM_OK;
}
/* after DO, go DO_DONE... or DO_MORE */
else if(data->easy_conn->bits.do_more) {
/* we're supposed to do more, but we need to sit down, relax
and wait a little while first */
multistate(data, CURLM_STATE_DO_MORE);
rc = CURLM_OK;
}
else {
/* we're done with the DO, now DO_DONE */
multistate(data, CURLM_STATE_DO_DONE);
rc = CURLM_CALL_MULTI_PERFORM;
}
}
else if((CURLE_SEND_ERROR == result) &&
data->easy_conn->bits.reuse) {
/*
* In this situation, a connection that we were trying to use
* may have unexpectedly died. If possible, send the connection
* back to the CONNECT phase so we can try again.
*/
char *newurl = NULL;
followtype follow=FOLLOW_NONE;
CURLcode drc;
bool retry = FALSE;
drc = Curl_retry_request(data->easy_conn, &newurl);
if(drc) {
/* a failure here pretty much implies an out of memory */
result = drc;
disconnect_conn = TRUE;
}
else
retry = (newurl)?TRUE:FALSE;
Curl_posttransfer(data);
drc = Curl_done(&data->easy_conn, result, FALSE);
/* When set to retry the connection, we must to go back to
* the CONNECT state */
if(retry) {
if(!drc || (drc == CURLE_SEND_ERROR)) {
follow = FOLLOW_RETRY;
drc = Curl_follow(data, newurl, follow);
if(!drc) {
multistate(data, CURLM_STATE_CONNECT);
rc = CURLM_CALL_MULTI_PERFORM;
result = CURLE_OK;
}
else {
/* Follow failed */
result = drc;
free(newurl);
}
}
else {
/* done didn't return OK or SEND_ERROR */
result = drc;
free(newurl);
}
}
else {
/* Have error handler disconnect conn if we can't retry */
disconnect_conn = TRUE;
free(newurl);
}
}
else {
/* failure detected */
Curl_posttransfer(data);
if(data->easy_conn)
Curl_done(&data->easy_conn, result, FALSE);
disconnect_conn = TRUE;
}
}
break;
case CURLM_STATE_DOING:
/* we continue DOING until the DO phase is complete */
result = Curl_protocol_doing(data->easy_conn,
&dophase_done);
if(!result) {
if(dophase_done) {
/* after DO, go DO_DONE or DO_MORE */
multistate(data, data->easy_conn->bits.do_more?
CURLM_STATE_DO_MORE:
CURLM_STATE_DO_DONE);
rc = CURLM_CALL_MULTI_PERFORM;
} /* dophase_done */
}
else {
/* failure detected */
Curl_posttransfer(data);
Curl_done(&data->easy_conn, result, FALSE);
disconnect_conn = TRUE;
}
break;
case CURLM_STATE_DO_MORE:
/*
* When we are connected, DO MORE and then go DO_DONE
*/
result = Curl_do_more(data->easy_conn, &control);
/* No need to remove this handle from the send pipeline here since that
is done in Curl_done() */
if(!result) {
if(control) {
/* if positive, advance to DO_DONE
if negative, go back to DOING */
multistate(data, control==1?
CURLM_STATE_DO_DONE:
CURLM_STATE_DOING);
rc = CURLM_CALL_MULTI_PERFORM;
}
else
/* stay in DO_MORE */
rc = CURLM_OK;
}
else {
/* failure detected */
Curl_posttransfer(data);
Curl_done(&data->easy_conn, result, FALSE);
disconnect_conn = TRUE;
}
break;
case CURLM_STATE_DO_DONE:
/* Move ourselves from the send to recv pipeline */
Curl_move_handle_from_send_to_recv_pipe(data, data->easy_conn);
/* Check if we can move pending requests to send pipe */
Curl_multi_process_pending_handles(multi);
/* Only perform the transfer if there's a good socket to work with.
Having both BAD is a signal to skip immediately to DONE */
if((data->easy_conn->sockfd != CURL_SOCKET_BAD) ||
(data->easy_conn->writesockfd != CURL_SOCKET_BAD))
multistate(data, CURLM_STATE_WAITPERFORM);
else
multistate(data, CURLM_STATE_DONE);
rc = CURLM_CALL_MULTI_PERFORM;
break;
case CURLM_STATE_WAITPERFORM:
/* Wait for our turn to PERFORM */
if(!data->easy_conn->readchannel_inuse &&
isHandleAtHead(data,
data->easy_conn->recv_pipe)) {
/* Grab the channel */
data->easy_conn->readchannel_inuse = TRUE;
multistate(data, CURLM_STATE_PERFORM);
rc = CURLM_CALL_MULTI_PERFORM;
}
#ifdef DEBUGBUILD
else {
infof(data, "WAITPERFORM: Conn %ld recv pipe %zu inuse %s athead %s\n",
data->easy_conn->connection_id,
data->easy_conn->recv_pipe->size,
data->easy_conn->readchannel_inuse?"TRUE":"FALSE",
isHandleAtHead(data,
data->easy_conn->recv_pipe)?"TRUE":"FALSE");
}
#endif
break;
case CURLM_STATE_TOOFAST: /* limit-rate exceeded in either direction */
/* if both rates are within spec, resume transfer */
if(Curl_pgrsUpdate(data->easy_conn))
result = CURLE_ABORTED_BY_CALLBACK;
else
result = Curl_speedcheck(data, now);
if(( (data->set.max_send_speed == 0) ||
(data->progress.ulspeed < data->set.max_send_speed )) &&
( (data->set.max_recv_speed == 0) ||
(data->progress.dlspeed < data->set.max_recv_speed)))
multistate(data, CURLM_STATE_PERFORM);
break;
case CURLM_STATE_PERFORM:
{
char *newurl = NULL;
bool retry = FALSE;
/* check if over send speed */
if((data->set.max_send_speed > 0) &&
(data->progress.ulspeed > data->set.max_send_speed)) {
int buffersize;
multistate(data, CURLM_STATE_TOOFAST);
/* calculate upload rate-limitation timeout. */
buffersize = (int)(data->set.buffer_size ?
data->set.buffer_size : BUFSIZE);
timeout_ms = Curl_sleep_time(data->set.max_send_speed,
data->progress.ulspeed, buffersize);
Curl_expire_latest(data, timeout_ms);
break;
}
/* check if over recv speed */
if((data->set.max_recv_speed > 0) &&
(data->progress.dlspeed > data->set.max_recv_speed)) {
int buffersize;
multistate(data, CURLM_STATE_TOOFAST);
/* Calculate download rate-limitation timeout. */
buffersize = (int)(data->set.buffer_size ?
data->set.buffer_size : BUFSIZE);
timeout_ms = Curl_sleep_time(data->set.max_recv_speed,
data->progress.dlspeed, buffersize);
Curl_expire_latest(data, timeout_ms);
break;
}
/* read/write data if it is ready to do so */
result = Curl_readwrite(data->easy_conn, &done);
k = &data->req;
if(!(k->keepon & KEEP_RECV)) {
/* We're done receiving */
data->easy_conn->readchannel_inuse = FALSE;
}
if(!(k->keepon & KEEP_SEND)) {
/* We're done sending */
data->easy_conn->writechannel_inuse = FALSE;
}
if(done || (result == CURLE_RECV_ERROR)) {
/* If CURLE_RECV_ERROR happens early enough, we assume it was a race
* condition and the server closed the re-used connection exactly when
* we wanted to use it, so figure out if that is indeed the case.
*/
CURLcode ret = Curl_retry_request(data->easy_conn, &newurl);
if(!ret)
retry = (newurl)?TRUE:FALSE;
if(retry) {
/* if we are to retry, set the result to OK and consider the
request as done */
result = CURLE_OK;
done = TRUE;
}
}
if(result) {
/*
* The transfer phase returned error, we mark the connection to get
* closed to prevent being re-used. This is because we can't possibly
* know if the connection is in a good shape or not now. Unless it is
* a protocol which uses two "channels" like FTP, as then the error
* happened in the data connection.
*/
if(!(data->easy_conn->handler->flags & PROTOPT_DUAL))
connclose(data->easy_conn, "Transfer returned error");
Curl_posttransfer(data);
Curl_done(&data->easy_conn, result, FALSE);
}
else if(done) {
followtype follow=FOLLOW_NONE;
/* call this even if the readwrite function returned error */
Curl_posttransfer(data);
/* we're no longer receiving */
Curl_removeHandleFromPipeline(data, data->easy_conn->recv_pipe);
/* expire the new receiving pipeline head */
if(data->easy_conn->recv_pipe->head)
Curl_expire_latest(data->easy_conn->recv_pipe->head->ptr, 1);
/* Check if we can move pending requests to send pipe */
Curl_multi_process_pending_handles(multi);
/* When we follow redirects or is set to retry the connection, we must
to go back to the CONNECT state */
if(data->req.newurl || retry) {
if(!retry) {
/* if the URL is a follow-location and not just a retried request
then figure out the URL here */
if(newurl)
free(newurl);
newurl = data->req.newurl;
data->req.newurl = NULL;
follow = FOLLOW_REDIR;
}
else
follow = FOLLOW_RETRY;
result = Curl_done(&data->easy_conn, CURLE_OK, FALSE);
if(!result) {
result = Curl_follow(data, newurl, follow);
if(!result) {
multistate(data, CURLM_STATE_CONNECT);
rc = CURLM_CALL_MULTI_PERFORM;
newurl = NULL; /* handed over the memory ownership to
Curl_follow(), make sure we don't free() it
here */
}
}
}
else {
/* after the transfer is done, go DONE */
/* but first check to see if we got a location info even though we're
not following redirects */
if(data->req.location) {
if(newurl)
free(newurl);
newurl = data->req.location;
data->req.location = NULL;
result = Curl_follow(data, newurl, FOLLOW_FAKE);
if(!result)
newurl = NULL; /* allocation was handed over Curl_follow() */
else
disconnect_conn = TRUE;
}
multistate(data, CURLM_STATE_DONE);
rc = CURLM_CALL_MULTI_PERFORM;
}
}
if(newurl)
free(newurl);
break;
}
case CURLM_STATE_DONE:
/* this state is highly transient, so run another loop after this */
rc = CURLM_CALL_MULTI_PERFORM;
if(data->easy_conn) {
CURLcode res;
/* Remove ourselves from the receive pipeline, if we are there. */
Curl_removeHandleFromPipeline(data, data->easy_conn->recv_pipe);
/* Check if we can move pending requests to send pipe */
Curl_multi_process_pending_handles(multi);
/* post-transfer command */
res = Curl_done(&data->easy_conn, result, FALSE);
/* allow a previously set error code take precedence */
if(!result)
result = res;
/*
* If there are other handles on the pipeline, Curl_done won't set
* easy_conn to NULL. In such a case, curl_multi_remove_handle() can
* access free'd data, if the connection is free'd and the handle
* removed before we perform the processing in CURLM_STATE_COMPLETED
*/
if(data->easy_conn)
data->easy_conn = NULL;
}
if(data->set.wildcardmatch) {
if(data->wildcard.state != CURLWC_DONE) {
/* if a wildcard is set and we are not ending -> lets start again
with CURLM_STATE_INIT */
multistate(data, CURLM_STATE_INIT);
break;
}
}
/* after we have DONE what we're supposed to do, go COMPLETED, and
it doesn't matter what the Curl_done() returned! */
multistate(data, CURLM_STATE_COMPLETED);
break;
case CURLM_STATE_COMPLETED:
/* this is a completed transfer, it is likely to still be connected */
/* This node should be delinked from the list now and we should post
an information message that we are complete. */
/* Important: reset the conn pointer so that we don't point to memory
that could be freed anytime */
data->easy_conn = NULL;
Curl_expire(data, 0); /* stop all timers */
break;
case CURLM_STATE_MSGSENT:
data->result = result;
return CURLM_OK; /* do nothing */
default:
return CURLM_INTERNAL_ERROR;
}
statemachine_end:
if(data->mstate < CURLM_STATE_COMPLETED) {
if(result) {
/*
* If an error was returned, and we aren't in completed state now,
* then we go to completed and consider this transfer aborted.
*/
/* NOTE: no attempt to disconnect connections must be made
in the case blocks above - cleanup happens only here */
data->state.pipe_broke = FALSE;
if(data->easy_conn) {
/* if this has a connection, unsubscribe from the pipelines */
data->easy_conn->writechannel_inuse = FALSE;
data->easy_conn->readchannel_inuse = FALSE;
Curl_removeHandleFromPipeline(data, data->easy_conn->send_pipe);
Curl_removeHandleFromPipeline(data, data->easy_conn->recv_pipe);
/* Check if we can move pending requests to send pipe */
Curl_multi_process_pending_handles(multi);
if(disconnect_conn) {
/* Don't attempt to send data over a connection that timed out */
bool dead_connection = result == CURLE_OPERATION_TIMEDOUT;
/* disconnect properly */
Curl_disconnect(data->easy_conn, dead_connection);
/* This is where we make sure that the easy_conn pointer is reset.
We don't have to do this in every case block above where a
failure is detected */
data->easy_conn = NULL;
}
}
else if(data->mstate == CURLM_STATE_CONNECT) {
/* Curl_connect() failed */
(void)Curl_posttransfer(data);
}
multistate(data, CURLM_STATE_COMPLETED);
}
/* if there's still a connection to use, call the progress function */
else if(data->easy_conn && Curl_pgrsUpdate(data->easy_conn)) {
/* aborted due to progress callback return code must close the
connection */
result = CURLE_ABORTED_BY_CALLBACK;
connclose(data->easy_conn, "Aborted by callback");
/* if not yet in DONE state, go there, otherwise COMPLETED */
multistate(data, (data->mstate < CURLM_STATE_DONE)?
CURLM_STATE_DONE: CURLM_STATE_COMPLETED);
rc = CURLM_CALL_MULTI_PERFORM;
}
}
if(CURLM_STATE_COMPLETED == data->mstate) {
/* now fill in the Curl_message with this info */
msg = &data->msg;
msg->extmsg.msg = CURLMSG_DONE;
msg->extmsg.easy_handle = data;
msg->extmsg.data.result = result;
rc = multi_addmsg(multi, msg);
multistate(data, CURLM_STATE_MSGSENT);
}
} while(rc == CURLM_CALL_MULTI_PERFORM);
data->result = result;
return rc;
}
CURLMcode curl_multi_perform(CURLM *multi_handle, int *running_handles)
{
struct Curl_multi *multi=(struct Curl_multi *)multi_handle;
struct SessionHandle *data;
CURLMcode returncode=CURLM_OK;
struct Curl_tree *t;
struct timeval now = Curl_tvnow();
if(!GOOD_MULTI_HANDLE(multi))
return CURLM_BAD_HANDLE;
data=multi->easyp;
while(data) {
CURLMcode result;
struct WildcardData *wc = &data->wildcard;
SIGPIPE_VARIABLE(pipe_st);
if(data->set.wildcardmatch) {
if(!wc->filelist) {
CURLcode ret = Curl_wildcard_init(wc); /* init wildcard structures */
if(ret)
return CURLM_OUT_OF_MEMORY;
}
}
sigpipe_ignore(data, &pipe_st);
result = multi_runsingle(multi, now, data);
sigpipe_restore(&pipe_st);
if(data->set.wildcardmatch) {
/* destruct wildcard structures if it is needed */
if(wc->state == CURLWC_DONE || result)
Curl_wildcard_dtor(wc);
}
if(result)
returncode = result;
data = data->next; /* operate on next handle */
}
/*
* Simply remove all expired timers from the splay since handles are dealt
* with unconditionally by this function and curl_multi_timeout() requires
* that already passed/handled expire times are removed from the splay.
*
* It is important that the 'now' value is set at the entry of this function
* and not for the current time as it may have ticked a little while since
* then and then we risk this loop to remove timers that actually have not
* been handled!
*/
do {
multi->timetree = Curl_splaygetbest(now, multi->timetree, &t);
if(t)
/* the removed may have another timeout in queue */
(void)add_next_timeout(now, multi, t->payload);
} while(t);
*running_handles = multi->num_alive;
if(CURLM_OK >= returncode)
update_timer(multi);
return returncode;
}
static void close_all_connections(struct Curl_multi *multi)
{
struct connectdata *conn;
conn = Curl_conncache_find_first_connection(multi->conn_cache);
while(conn) {
SIGPIPE_VARIABLE(pipe_st);
conn->data = multi->closure_handle;
sigpipe_ignore(conn->data, &pipe_st);
/* This will remove the connection from the cache */
(void)Curl_disconnect(conn, FALSE);
sigpipe_restore(&pipe_st);
conn = Curl_conncache_find_first_connection(multi->conn_cache);
}
}
CURLMcode curl_multi_cleanup(CURLM *multi_handle)
{
struct Curl_multi *multi=(struct Curl_multi *)multi_handle;
struct SessionHandle *data;
struct SessionHandle *nextdata;
if(GOOD_MULTI_HANDLE(multi)) {
bool restore_pipe = FALSE;
SIGPIPE_VARIABLE(pipe_st);
multi->type = 0; /* not good anymore */
/* Close all the connections in the connection cache */
close_all_connections(multi);
if(multi->closure_handle) {
sigpipe_ignore(multi->closure_handle, &pipe_st);
restore_pipe = TRUE;
multi->closure_handle->dns.hostcache = multi->hostcache;
Curl_hostcache_clean(multi->closure_handle,
multi->closure_handle->dns.hostcache);
Curl_close(multi->closure_handle);
}
Curl_hash_destroy(multi->sockhash);
Curl_conncache_destroy(multi->conn_cache);
Curl_llist_destroy(multi->msglist, NULL);
Curl_llist_destroy(multi->pending, NULL);
/* remove all easy handles */
data = multi->easyp;
while(data) {
nextdata=data->next;
if(data->dns.hostcachetype == HCACHE_MULTI) {
/* clear out the usage of the shared DNS cache */
Curl_hostcache_clean(data, data->dns.hostcache);
data->dns.hostcache = NULL;
data->dns.hostcachetype = HCACHE_NONE;
}
/* Clear the pointer to the connection cache */
data->state.conn_cache = NULL;
data->multi = NULL; /* clear the association */
data = nextdata;
}
Curl_hash_destroy(multi->hostcache);
/* Free the blacklists by setting them to NULL */
Curl_pipeline_set_site_blacklist(NULL, &multi->pipelining_site_bl);
Curl_pipeline_set_server_blacklist(NULL, &multi->pipelining_server_bl);
free(multi);
if(restore_pipe)
sigpipe_restore(&pipe_st);
return CURLM_OK;
}
else
return CURLM_BAD_HANDLE;
}
/*
* curl_multi_info_read()
*
* This function is the primary way for a multi/multi_socket application to
* figure out if a transfer has ended. We MUST make this function as fast as
* possible as it will be polled frequently and we MUST NOT scan any lists in
* here to figure out things. We must scale fine to thousands of handles and
* beyond. The current design is fully O(1).
*/
CURLMsg *curl_multi_info_read(CURLM *multi_handle, int *msgs_in_queue)
{
struct Curl_multi *multi=(struct Curl_multi *)multi_handle;
struct Curl_message *msg;
*msgs_in_queue = 0; /* default to none */
if(GOOD_MULTI_HANDLE(multi) && Curl_llist_count(multi->msglist)) {
/* there is one or more messages in the list */
struct curl_llist_element *e;
/* extract the head of the list to return */
e = multi->msglist->head;
msg = e->ptr;
/* remove the extracted entry */
Curl_llist_remove(multi->msglist, e, NULL);
*msgs_in_queue = curlx_uztosi(Curl_llist_count(multi->msglist));
return &msg->extmsg;
}
else
return NULL;
}
/*
* singlesocket() checks what sockets we deal with and their "action state"
* and if we have a different state in any of those sockets from last time we
* call the callback accordingly.
*/
static void singlesocket(struct Curl_multi *multi,
struct SessionHandle *data)
{
curl_socket_t socks[MAX_SOCKSPEREASYHANDLE];
int i;
struct Curl_sh_entry *entry;
curl_socket_t s;
int num;
unsigned int curraction;
bool remove_sock_from_hash;
for(i=0; i< MAX_SOCKSPEREASYHANDLE; i++)
socks[i] = CURL_SOCKET_BAD;
/* Fill in the 'current' struct with the state as it is now: what sockets to
supervise and for what actions */
curraction = multi_getsock(data, socks, MAX_SOCKSPEREASYHANDLE);
/* We have 0 .. N sockets already and we get to know about the 0 .. M
sockets we should have from now on. Detect the differences, remove no
longer supervised ones and add new ones */
/* walk over the sockets we got right now */
for(i=0; (i< MAX_SOCKSPEREASYHANDLE) &&
(curraction & (GETSOCK_READSOCK(i) | GETSOCK_WRITESOCK(i)));
i++) {
int action = CURL_POLL_NONE;
s = socks[i];
/* get it from the hash */
entry = Curl_hash_pick(multi->sockhash, (char *)&s, sizeof(s));
if(curraction & GETSOCK_READSOCK(i))
action |= CURL_POLL_IN;
if(curraction & GETSOCK_WRITESOCK(i))
action |= CURL_POLL_OUT;
if(entry) {
/* yeps, already present so check if it has the same action set */
if(entry->action == action)
/* same, continue */
continue;
}
else {
/* this is a socket we didn't have before, add it! */
entry = sh_addentry(multi->sockhash, s, data);
if(!entry)
/* fatal */
return;
}
/* we know (entry != NULL) at this point, see the logic above */
if(multi->socket_cb)
multi->socket_cb(data,
s,
action,
multi->socket_userp,
entry->socketp);
entry->action = action; /* store the current action state */
}
num = i; /* number of sockets */
/* when we've walked over all the sockets we should have right now, we must
make sure to detect sockets that are removed */
for(i=0; i< data->numsocks; i++) {
int j;
s = data->sockets[i];
for(j=0; j<num; j++) {
if(s == socks[j]) {
/* this is still supervised */
s = CURL_SOCKET_BAD;
break;
}
}
if(s != CURL_SOCKET_BAD) {
/* this socket has been removed. Tell the app to remove it */
remove_sock_from_hash = TRUE;
entry = Curl_hash_pick(multi->sockhash, (char *)&s, sizeof(s));
if(entry) {
/* check if the socket to be removed serves a connection which has
other easy-s in a pipeline. In this case the socket should not be
removed. */
struct connectdata *easy_conn = data->easy_conn;
if(easy_conn) {
if(easy_conn->recv_pipe && easy_conn->recv_pipe->size > 1) {
/* the handle should not be removed from the pipe yet */
remove_sock_from_hash = FALSE;
/* Update the sockhash entry to instead point to the next in line
for the recv_pipe, or the first (in case this particular easy
isn't already) */
if(entry->easy == data) {
if(isHandleAtHead(data, easy_conn->recv_pipe))
entry->easy = easy_conn->recv_pipe->head->next->ptr;
else
entry->easy = easy_conn->recv_pipe->head->ptr;
}
}
if(easy_conn->send_pipe && easy_conn->send_pipe->size > 1) {
/* the handle should not be removed from the pipe yet */
remove_sock_from_hash = FALSE;
/* Update the sockhash entry to instead point to the next in line
for the send_pipe, or the first (in case this particular easy
isn't already) */
if(entry->easy == data) {
if(isHandleAtHead(data, easy_conn->send_pipe))
entry->easy = easy_conn->send_pipe->head->next->ptr;
else
entry->easy = easy_conn->send_pipe->head->ptr;
}
}
/* Don't worry about overwriting recv_pipe head with send_pipe_head,
when action will be asked on the socket (see multi_socket()), the
head of the correct pipe will be taken according to the
action. */
}
}
else
/* just a precaution, this socket really SHOULD be in the hash already
but in case it isn't, we don't have to tell the app to remove it
either since it never got to know about it */
remove_sock_from_hash = FALSE;
if(remove_sock_from_hash) {
/* in this case 'entry' is always non-NULL */
if(multi->socket_cb)
multi->socket_cb(data,
s,
CURL_POLL_REMOVE,
multi->socket_userp,
entry->socketp);
sh_delentry(multi->sockhash, s);
}
}
}
memcpy(data->sockets, socks, num*sizeof(curl_socket_t));
data->numsocks = num;
}
/*
* Curl_multi_closed()
*
* Used by the connect code to tell the multi_socket code that one of the
* sockets we were using is about to be closed. This function will then
* remove it from the sockethash for this handle to make the multi_socket API
* behave properly, especially for the case when libcurl will create another
* socket again and it gets the same file descriptor number.
*/
void Curl_multi_closed(struct connectdata *conn, curl_socket_t s)
{
struct Curl_multi *multi = conn->data->multi;
if(multi) {
/* this is set if this connection is part of a handle that is added to
a multi handle, and only then this is necessary */
struct Curl_sh_entry *entry =
Curl_hash_pick(multi->sockhash, (char *)&s, sizeof(s));
if(entry) {
if(multi->socket_cb)
multi->socket_cb(conn->data, s, CURL_POLL_REMOVE,
multi->socket_userp,
entry->socketp);
/* now remove it from the socket hash */
sh_delentry(multi->sockhash, s);
}
}
}
/*
* add_next_timeout()
*
* Each SessionHandle has a list of timeouts. The add_next_timeout() is called
* when it has just been removed from the splay tree because the timeout has
* expired. This function is then to advance in the list to pick the next
* timeout to use (skip the already expired ones) and add this node back to
* the splay tree again.
*
* The splay tree only has each sessionhandle as a single node and the nearest
* timeout is used to sort it on.
*/
static CURLMcode add_next_timeout(struct timeval now,
struct Curl_multi *multi,
struct SessionHandle *d)
{
struct timeval *tv = &d->state.expiretime;
struct curl_llist *list = d->state.timeoutlist;
struct curl_llist_element *e;
/* move over the timeout list for this specific handle and remove all
timeouts that are now passed tense and store the next pending
timeout in *tv */
for(e = list->head; e; ) {
struct curl_llist_element *n = e->next;
long diff = curlx_tvdiff(*(struct timeval *)e->ptr, now);
if(diff <= 0)
/* remove outdated entry */
Curl_llist_remove(list, e, NULL);
else
/* the list is sorted so get out on the first mismatch */
break;
e = n;
}
e = list->head;
if(!e) {
/* clear the expire times within the handles that we remove from the
splay tree */
tv->tv_sec = 0;
tv->tv_usec = 0;
}
else {
/* copy the first entry to 'tv' */
memcpy(tv, e->ptr, sizeof(*tv));
/* remove first entry from list */
Curl_llist_remove(list, e, NULL);
/* insert this node again into the splay */
multi->timetree = Curl_splayinsert(*tv, multi->timetree,
&d->state.timenode);
}
return CURLM_OK;
}
static CURLMcode multi_socket(struct Curl_multi *multi,
bool checkall,
curl_socket_t s,
int ev_bitmask,
int *running_handles)
{
CURLMcode result = CURLM_OK;
struct SessionHandle *data = NULL;
struct Curl_tree *t;
struct timeval now = Curl_tvnow();
if(checkall) {
/* *perform() deals with running_handles on its own */
result = curl_multi_perform(multi, running_handles);
/* walk through each easy handle and do the socket state change magic
and callbacks */
if(result != CURLM_BAD_HANDLE) {
data=multi->easyp;
while(data) {
singlesocket(multi, data);
data = data->next;
}
}
/* or should we fall-through and do the timer-based stuff? */
return result;
}
else if(s != CURL_SOCKET_TIMEOUT) {
struct Curl_sh_entry *entry =
Curl_hash_pick(multi->sockhash, (char *)&s, sizeof(s));
if(!entry)
/* Unmatched socket, we can't act on it but we ignore this fact. In
real-world tests it has been proved that libevent can in fact give
the application actions even though the socket was just previously
asked to get removed, so thus we better survive stray socket actions
and just move on. */
;
else {
SIGPIPE_VARIABLE(pipe_st);
data = entry->easy;
if(data->magic != CURLEASY_MAGIC_NUMBER)
/* bad bad bad bad bad bad bad */
return CURLM_INTERNAL_ERROR;
/* If the pipeline is enabled, take the handle which is in the head of
the pipeline. If we should write into the socket, take the send_pipe
head. If we should read from the socket, take the recv_pipe head. */
if(data->easy_conn) {
if((ev_bitmask & CURL_POLL_OUT) &&
data->easy_conn->send_pipe &&
data->easy_conn->send_pipe->head)
data = data->easy_conn->send_pipe->head->ptr;
else if((ev_bitmask & CURL_POLL_IN) &&
data->easy_conn->recv_pipe &&
data->easy_conn->recv_pipe->head)
data = data->easy_conn->recv_pipe->head->ptr;
}
if(data->easy_conn &&
!(data->easy_conn->handler->flags & PROTOPT_DIRLOCK))
/* set socket event bitmask if they're not locked */
data->easy_conn->cselect_bits = ev_bitmask;
sigpipe_ignore(data, &pipe_st);
result = multi_runsingle(multi, now, data);
sigpipe_restore(&pipe_st);
if(data->easy_conn &&
!(data->easy_conn->handler->flags & PROTOPT_DIRLOCK))
/* clear the bitmask only if not locked */
data->easy_conn->cselect_bits = 0;
if(CURLM_OK >= result)
/* get the socket(s) and check if the state has been changed since
last */
singlesocket(multi, data);
/* Now we fall-through and do the timer-based stuff, since we don't want
to force the user to have to deal with timeouts as long as at least
one connection in fact has traffic. */
data = NULL; /* set data to NULL again to avoid calling
multi_runsingle() in case there's no need to */
now = Curl_tvnow(); /* get a newer time since the multi_runsingle() loop
may have taken some time */
}
}
else {
/* Asked to run due to time-out. Clear the 'lastcall' variable to force
update_timer() to trigger a callback to the app again even if the same
timeout is still the one to run after this call. That handles the case
when the application asks libcurl to run the timeout prematurely. */
memset(&multi->timer_lastcall, 0, sizeof(multi->timer_lastcall));
}
/*
* The loop following here will go on as long as there are expire-times left
* to process in the splay and 'data' will be re-assigned for every expired
* handle we deal with.
*/
do {
/* the first loop lap 'data' can be NULL */
if(data) {
SIGPIPE_VARIABLE(pipe_st);
sigpipe_ignore(data, &pipe_st);
result = multi_runsingle(multi, now, data);
sigpipe_restore(&pipe_st);
if(CURLM_OK >= result)
/* get the socket(s) and check if the state has been changed since
last */
singlesocket(multi, data);
}
/* Check if there's one (more) expired timer to deal with! This function
extracts a matching node if there is one */
multi->timetree = Curl_splaygetbest(now, multi->timetree, &t);
if(t) {
data = t->payload; /* assign this for next loop */
(void)add_next_timeout(now, multi, t->payload);
}
} while(t);
*running_handles = multi->num_alive;
return result;
}
#undef curl_multi_setopt
CURLMcode curl_multi_setopt(CURLM *multi_handle,
CURLMoption option, ...)
{
struct Curl_multi *multi=(struct Curl_multi *)multi_handle;
CURLMcode res = CURLM_OK;
va_list param;
if(!GOOD_MULTI_HANDLE(multi))
return CURLM_BAD_HANDLE;
va_start(param, option);
switch(option) {
case CURLMOPT_SOCKETFUNCTION:
multi->socket_cb = va_arg(param, curl_socket_callback);
break;
case CURLMOPT_SOCKETDATA:
multi->socket_userp = va_arg(param, void *);
break;
case CURLMOPT_PIPELINING:
multi->pipelining_enabled = (0 != va_arg(param, long)) ? TRUE : FALSE;
break;
case CURLMOPT_TIMERFUNCTION:
multi->timer_cb = va_arg(param, curl_multi_timer_callback);
break;
case CURLMOPT_TIMERDATA:
multi->timer_userp = va_arg(param, void *);
break;
case CURLMOPT_MAXCONNECTS:
multi->maxconnects = va_arg(param, long);
break;
case CURLMOPT_MAX_HOST_CONNECTIONS:
multi->max_host_connections = va_arg(param, long);
break;
case CURLMOPT_MAX_PIPELINE_LENGTH:
multi->max_pipeline_length = va_arg(param, long);
break;
case CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE:
multi->content_length_penalty_size = va_arg(param, long);
break;
case CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE:
multi->chunk_length_penalty_size = va_arg(param, long);
break;
case CURLMOPT_PIPELINING_SITE_BL:
res = Curl_pipeline_set_site_blacklist(va_arg(param, char **),
&multi->pipelining_site_bl);
break;
case CURLMOPT_PIPELINING_SERVER_BL:
res = Curl_pipeline_set_server_blacklist(va_arg(param, char **),
&multi->pipelining_server_bl);
break;
case CURLMOPT_MAX_TOTAL_CONNECTIONS:
multi->max_total_connections = va_arg(param, long);
break;
default:
res = CURLM_UNKNOWN_OPTION;
break;
}
va_end(param);
return res;
}
/* we define curl_multi_socket() in the public multi.h header */
#undef curl_multi_socket
CURLMcode curl_multi_socket(CURLM *multi_handle, curl_socket_t s,
int *running_handles)
{
CURLMcode result = multi_socket((struct Curl_multi *)multi_handle, FALSE, s,
0, running_handles);
if(CURLM_OK >= result)
update_timer((struct Curl_multi *)multi_handle);
return result;
}
CURLMcode curl_multi_socket_action(CURLM *multi_handle, curl_socket_t s,
int ev_bitmask, int *running_handles)
{
CURLMcode result = multi_socket((struct Curl_multi *)multi_handle, FALSE, s,
ev_bitmask, running_handles);
if(CURLM_OK >= result)
update_timer((struct Curl_multi *)multi_handle);
return result;
}
CURLMcode curl_multi_socket_all(CURLM *multi_handle, int *running_handles)
{
CURLMcode result = multi_socket((struct Curl_multi *)multi_handle,
TRUE, CURL_SOCKET_BAD, 0, running_handles);
if(CURLM_OK >= result)
update_timer((struct Curl_multi *)multi_handle);
return result;
}
static CURLMcode multi_timeout(struct Curl_multi *multi,
long *timeout_ms)
{
static struct timeval tv_zero = {0,0};
if(multi->timetree) {
/* we have a tree of expire times */
struct timeval now = Curl_tvnow();
/* splay the lowest to the bottom */
multi->timetree = Curl_splay(tv_zero, multi->timetree);
if(Curl_splaycomparekeys(multi->timetree->key, now) > 0) {
/* some time left before expiration */
*timeout_ms = curlx_tvdiff(multi->timetree->key, now);
if(!*timeout_ms)
/*
* Since we only provide millisecond resolution on the returned value
* and the diff might be less than one millisecond here, we don't
* return zero as that may cause short bursts of busyloops on fast
* processors while the diff is still present but less than one
* millisecond! instead we return 1 until the time is ripe.
*/
*timeout_ms=1;
}
else
/* 0 means immediately */
*timeout_ms = 0;
}
else
*timeout_ms = -1;
return CURLM_OK;
}
CURLMcode curl_multi_timeout(CURLM *multi_handle,
long *timeout_ms)
{
struct Curl_multi *multi=(struct Curl_multi *)multi_handle;
/* First, make some basic checks that the CURLM handle is a good handle */
if(!GOOD_MULTI_HANDLE(multi))
return CURLM_BAD_HANDLE;
return multi_timeout(multi, timeout_ms);
}
/*
* Tell the application it should update its timers, if it subscribes to the
* update timer callback.
*/
static int update_timer(struct Curl_multi *multi)
{
long timeout_ms;
if(!multi->timer_cb)
return 0;
if(multi_timeout(multi, &timeout_ms)) {
return -1;
}
if(timeout_ms < 0) {
static const struct timeval none={0,0};
if(Curl_splaycomparekeys(none, multi->timer_lastcall)) {
multi->timer_lastcall = none;
/* there's no timeout now but there was one previously, tell the app to
disable it */
return multi->timer_cb((CURLM*)multi, -1, multi->timer_userp);
}
return 0;
}
/* When multi_timeout() is done, multi->timetree points to the node with the
* timeout we got the (relative) time-out time for. We can thus easily check
* if this is the same (fixed) time as we got in a previous call and then
* avoid calling the callback again. */
if(Curl_splaycomparekeys(multi->timetree->key, multi->timer_lastcall) == 0)
return 0;
multi->timer_lastcall = multi->timetree->key;
return multi->timer_cb((CURLM*)multi, timeout_ms, multi->timer_userp);
}
static bool isHandleAtHead(struct SessionHandle *handle,
struct curl_llist *pipeline)
{
struct curl_llist_element *curr = pipeline->head;
if(curr)
return (curr->ptr == handle) ? TRUE : FALSE;
return FALSE;
}
/*
* multi_freetimeout()
*
* Callback used by the llist system when a single timeout list entry is
* destroyed.
*/
static void multi_freetimeout(void *user, void *entryptr)
{
(void)user;
/* the entry was plain malloc()'ed */
free(entryptr);
}
/*
* multi_addtimeout()
*
* Add a timestamp to the list of timeouts. Keep the list sorted so that head
* of list is always the timeout nearest in time.
*
*/
static CURLMcode
multi_addtimeout(struct curl_llist *timeoutlist,
struct timeval *stamp)
{
struct curl_llist_element *e;
struct timeval *timedup;
struct curl_llist_element *prev = NULL;
timedup = malloc(sizeof(*timedup));
if(!timedup)
return CURLM_OUT_OF_MEMORY;
/* copy the timestamp */
memcpy(timedup, stamp, sizeof(*timedup));
if(Curl_llist_count(timeoutlist)) {
/* find the correct spot in the list */
for(e = timeoutlist->head; e; e = e->next) {
struct timeval *checktime = e->ptr;
long diff = curlx_tvdiff(*checktime, *timedup);
if(diff > 0)
break;
prev = e;
}
}
/* else
this is the first timeout on the list */
if(!Curl_llist_insert_next(timeoutlist, prev, timedup)) {
free(timedup);
return CURLM_OUT_OF_MEMORY;
}
return CURLM_OK;
}
/*
* Curl_expire()
*
* given a number of milliseconds from now to use to set the 'act before
* this'-time for the transfer, to be extracted by curl_multi_timeout()
*
* Note that the timeout will be added to a queue of timeouts if it defines a
* moment in time that is later than the current head of queue.
*
* Pass zero to clear all timeout values for this handle.
*/
void Curl_expire(struct SessionHandle *data, long milli)
{
struct Curl_multi *multi = data->multi;
struct timeval *nowp = &data->state.expiretime;
int rc;
/* this is only interesting while there is still an associated multi struct
remaining! */
if(!multi)
return;
if(!milli) {
/* No timeout, clear the time data. */
if(nowp->tv_sec || nowp->tv_usec) {
/* Since this is an cleared time, we must remove the previous entry from
the splay tree */
struct curl_llist *list = data->state.timeoutlist;
rc = Curl_splayremovebyaddr(multi->timetree,
&data->state.timenode,
&multi->timetree);
if(rc)
infof(data, "Internal error clearing splay node = %d\n", rc);
/* flush the timeout list too */
while(list->size > 0)
Curl_llist_remove(list, list->tail, NULL);
#ifdef DEBUGBUILD
infof(data, "Expire cleared\n");
#endif
nowp->tv_sec = 0;
nowp->tv_usec = 0;
}
}
else {
struct timeval set;
set = Curl_tvnow();
set.tv_sec += milli/1000;
set.tv_usec += (milli%1000)*1000;
if(set.tv_usec >= 1000000) {
set.tv_sec++;
set.tv_usec -= 1000000;
}
if(nowp->tv_sec || nowp->tv_usec) {
/* This means that the struct is added as a node in the splay tree.
Compare if the new time is earlier, and only remove-old/add-new if it
is. */
long diff = curlx_tvdiff(set, *nowp);
if(diff > 0) {
/* the new expire time was later so just add it to the queue
and get out */
multi_addtimeout(data->state.timeoutlist, &set);
return;
}
/* the new time is newer than the presently set one, so add the current
to the queue and update the head */
multi_addtimeout(data->state.timeoutlist, nowp);
/* Since this is an updated time, we must remove the previous entry from
the splay tree first and then re-add the new value */
rc = Curl_splayremovebyaddr(multi->timetree,
&data->state.timenode,
&multi->timetree);
if(rc)
infof(data, "Internal error removing splay node = %d\n", rc);
}
*nowp = set;
data->state.timenode.payload = data;
multi->timetree = Curl_splayinsert(*nowp,
multi->timetree,
&data->state.timenode);
}
#if 0
Curl_splayprint(multi->timetree, 0, TRUE);
#endif
}
/*
* Curl_expire_latest()
*
* This is like Curl_expire() but will only add a timeout node to the list of
* timers if there is no timeout that will expire before the given time.
*
* Use this function if the code logic risks calling this function many times
* or if there's no particular conditional wait in the code for this specific
* time-out period to expire.
*
*/
void Curl_expire_latest(struct SessionHandle *data, long milli)
{
struct timeval *expire = &data->state.expiretime;
struct timeval set;
set = Curl_tvnow();
set.tv_sec += milli / 1000;
set.tv_usec += (milli % 1000) * 1000;
if(set.tv_usec >= 1000000) {
set.tv_sec++;
set.tv_usec -= 1000000;
}
if(expire->tv_sec || expire->tv_usec) {
/* This means that the struct is added as a node in the splay tree.
Compare if the new time is earlier, and only remove-old/add-new if it
is. */
long diff = curlx_tvdiff(set, *expire);
if(diff > 0)
/* the new expire time was later than the top time, so just skip this */
return;
}
/* Just add the timeout like normal */
Curl_expire(data, milli);
}
CURLMcode curl_multi_assign(CURLM *multi_handle,
curl_socket_t s, void *hashp)
{
struct Curl_sh_entry *there = NULL;
struct Curl_multi *multi = (struct Curl_multi *)multi_handle;
if(s != CURL_SOCKET_BAD)
there = Curl_hash_pick(multi->sockhash, (char *)&s, sizeof(curl_socket_t));
if(!there)
return CURLM_BAD_SOCKET;
there->socketp = hashp;
return CURLM_OK;
}
size_t Curl_multi_max_host_connections(struct Curl_multi *multi)
{
return multi ? multi->max_host_connections : 0;
}
size_t Curl_multi_max_total_connections(struct Curl_multi *multi)
{
return multi ? multi->max_total_connections : 0;
}
size_t Curl_multi_max_pipeline_length(struct Curl_multi *multi)
{
return multi ? multi->max_pipeline_length : 0;
}
curl_off_t Curl_multi_content_length_penalty_size(struct Curl_multi *multi)
{
return multi ? multi->content_length_penalty_size : 0;
}
curl_off_t Curl_multi_chunk_length_penalty_size(struct Curl_multi *multi)
{
return multi ? multi->chunk_length_penalty_size : 0;
}
struct curl_llist *Curl_multi_pipelining_site_bl(struct Curl_multi *multi)
{
return multi->pipelining_site_bl;
}
struct curl_llist *Curl_multi_pipelining_server_bl(struct Curl_multi *multi)
{
return multi->pipelining_server_bl;
}
void Curl_multi_process_pending_handles(struct Curl_multi *multi)
{
struct curl_llist_element *e = multi->pending->head;
while(e) {
struct SessionHandle *data = e->ptr;
struct curl_llist_element *next = e->next;
if(data->mstate == CURLM_STATE_CONNECT_PEND) {
multistate(data, CURLM_STATE_CONNECT);
/* Remove this node from the list */
Curl_llist_remove(multi->pending, e, NULL);
/* Make sure that the handle will be processed soonish. */
Curl_expire_latest(data, 1);
}
e = next; /* operate on next handle */
}
}
#ifdef DEBUGBUILD
void Curl_multi_dump(const struct Curl_multi *multi_handle)
{
struct Curl_multi *multi=(struct Curl_multi *)multi_handle;
struct SessionHandle *data;
int i;
fprintf(stderr, "* Multi status: %d handles, %d alive\n",
multi->num_easy, multi->num_alive);
for(data=multi->easyp; data; data = data->next) {
if(data->mstate < CURLM_STATE_COMPLETED) {
/* only display handles that are not completed */
fprintf(stderr, "handle %p, state %s, %d sockets\n",
(void *)data,
statename[data->mstate], data->numsocks);
for(i=0; i < data->numsocks; i++) {
curl_socket_t s = data->sockets[i];
struct Curl_sh_entry *entry =
Curl_hash_pick(multi->sockhash, (char *)&s, sizeof(s));
fprintf(stderr, "%d ", (int)s);
if(!entry) {
fprintf(stderr, "INTERNAL CONFUSION\n");
continue;
}
fprintf(stderr, "[%s %s] ",
entry->action&CURL_POLL_IN?"RECVING":"",
entry->action&CURL_POLL_OUT?"SENDING":"");
}
if(data->numsocks)
fprintf(stderr, "\n");
}
}
}
#endif
|
354896.c | /* A Bison parser, made by GNU Bison 3.0.2. */
/* Bison implementation for Yacc-like parsers in C
Copyright (C) 1984, 1989-1990, 2000-2013 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 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, see <http://www.gnu.org/licenses/>. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
/* C LALR(1) parser skeleton written by Richard Stallman, by
simplifying the original so-called "semantic" parser. */
/* All symbols defined below should begin with yy or YY, to avoid
infringing on user name space. This should be done even for local
variables, as they might otherwise be expanded by user macros.
There are some unavoidable exceptions within include files to
define necessary library symbols; they are noted "INFRINGES ON
USER NAME SPACE" below. */
/* Identify Bison output. */
#define YYBISON 1
/* Bison version. */
#define YYBISON_VERSION "3.0.2"
/* Skeleton name. */
#define YYSKELETON_NAME "yacc.c"
/* Pure parsers. */
#define YYPURE 1
/* Push parsers. */
#define YYPUSH 0
/* Pull parsers. */
#define YYPULL 1
/* Substitute the variable and function names. */
#define yyparse dapparse
#define yylex daplex
#define yyerror daperror
#define yydebug dapdebug
#define yynerrs dapnerrs
/* Copy the first part of user declarations. */
#line 11 "dap.y" /* yacc.c:339 */
#include "config.h"
#include "dapparselex.h"
#include "daptab.h"
int dapdebug = 0;
#line 79 "dap.tab.c" /* yacc.c:339 */
# ifndef YY_NULLPTR
# if defined __cplusplus && 201103L <= __cplusplus
# define YY_NULLPTR nullptr
# else
# define YY_NULLPTR 0
# endif
# endif
/* Enabling verbose error messages. */
#ifdef YYERROR_VERBOSE
# undef YYERROR_VERBOSE
# define YYERROR_VERBOSE 1
#else
# define YYERROR_VERBOSE 1
#endif
/* In a future release of Bison, this section will be replaced
by #include "dap.tab.h". */
#ifndef YY_DAP_DAP_TAB_H_INCLUDED
# define YY_DAP_DAP_TAB_H_INCLUDED
/* Debug traces. */
#ifndef YYDEBUG
# define YYDEBUG 1
#endif
#if YYDEBUG
extern int dapdebug;
#endif
/* Token type. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
enum yytokentype
{
SCAN_ALIAS = 258,
SCAN_ARRAY = 259,
SCAN_ATTR = 260,
SCAN_BYTE = 261,
SCAN_CODE = 262,
SCAN_DATASET = 263,
SCAN_DATA = 264,
SCAN_ERROR = 265,
SCAN_FLOAT32 = 266,
SCAN_FLOAT64 = 267,
SCAN_GRID = 268,
SCAN_INT16 = 269,
SCAN_INT32 = 270,
SCAN_MAPS = 271,
SCAN_MESSAGE = 272,
SCAN_SEQUENCE = 273,
SCAN_STRING = 274,
SCAN_STRUCTURE = 275,
SCAN_UINT16 = 276,
SCAN_UINT32 = 277,
SCAN_URL = 278,
SCAN_PTYPE = 279,
SCAN_PROG = 280,
WORD_WORD = 281,
WORD_STRING = 282
};
#endif
/* Value type. */
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
typedef int YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1
# define YYSTYPE_IS_DECLARED 1
#endif
int dapparse (DAPparsestate* parsestate);
#endif /* !YY_DAP_DAP_TAB_H_INCLUDED */
/* Copy the second part of user declarations. */
#line 157 "dap.tab.c" /* yacc.c:358 */
#ifdef short
# undef short
#endif
#ifdef YYTYPE_UINT8
typedef YYTYPE_UINT8 yytype_uint8;
#else
typedef unsigned char yytype_uint8;
#endif
#ifdef YYTYPE_INT8
typedef YYTYPE_INT8 yytype_int8;
#else
typedef signed char yytype_int8;
#endif
#ifdef YYTYPE_UINT16
typedef YYTYPE_UINT16 yytype_uint16;
#else
typedef unsigned short int yytype_uint16;
#endif
#ifdef YYTYPE_INT16
typedef YYTYPE_INT16 yytype_int16;
#else
typedef short int yytype_int16;
#endif
#ifndef YYSIZE_T
# ifdef __SIZE_TYPE__
# define YYSIZE_T __SIZE_TYPE__
# elif defined size_t
# define YYSIZE_T size_t
# elif ! defined YYSIZE_T
# include <stddef.h> /* INFRINGES ON USER NAME SPACE */
# define YYSIZE_T size_t
# else
# define YYSIZE_T unsigned int
# endif
#endif
#define YYSIZE_MAXIMUM ((YYSIZE_T) -1)
#ifndef YY_
# if defined YYENABLE_NLS && YYENABLE_NLS
# if ENABLE_NLS
# include <libintl.h> /* INFRINGES ON USER NAME SPACE */
# define YY_(Msgid) dgettext ("bison-runtime", Msgid)
# endif
# endif
# ifndef YY_
# define YY_(Msgid) Msgid
# endif
#endif
#ifndef YY_ATTRIBUTE
# if (defined __GNUC__ \
&& (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__))) \
|| defined __SUNPRO_C && 0x5110 <= __SUNPRO_C
# define YY_ATTRIBUTE(Spec) __attribute__(Spec)
# else
# define YY_ATTRIBUTE(Spec) /* empty */
# endif
#endif
#ifndef YY_ATTRIBUTE_PURE
# define YY_ATTRIBUTE_PURE YY_ATTRIBUTE ((__pure__))
#endif
#ifndef YY_ATTRIBUTE_UNUSED
# define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__))
#endif
#if !defined _Noreturn \
&& (!defined __STDC_VERSION__ || __STDC_VERSION__ < 201112)
# if defined _MSC_VER && 1200 <= _MSC_VER
# define _Noreturn __declspec (noreturn)
# else
# define _Noreturn YY_ATTRIBUTE ((__noreturn__))
# endif
#endif
/* Suppress unused-variable warnings by "using" E. */
#if ! defined lint || defined __GNUC__
# define YYUSE(E) ((void) (E))
#else
# define YYUSE(E) /* empty */
#endif
#if defined __GNUC__ && 407 <= __GNUC__ * 100 + __GNUC_MINOR__
/* Suppress an incorrect diagnostic about yylval being uninitialized. */
# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \
_Pragma ("GCC diagnostic push") \
_Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\
_Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"")
# define YY_IGNORE_MAYBE_UNINITIALIZED_END \
_Pragma ("GCC diagnostic pop")
#else
# define YY_INITIAL_VALUE(Value) Value
#endif
#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
# define YY_IGNORE_MAYBE_UNINITIALIZED_END
#endif
#ifndef YY_INITIAL_VALUE
# define YY_INITIAL_VALUE(Value) /* Nothing. */
#endif
#if ! defined yyoverflow || YYERROR_VERBOSE
/* The parser invokes alloca or malloc; define the necessary symbols. */
# ifdef YYSTACK_USE_ALLOCA
# if YYSTACK_USE_ALLOCA
# ifdef __GNUC__
# define YYSTACK_ALLOC __builtin_alloca
# elif defined __BUILTIN_VA_ARG_INCR
# include <alloca.h> /* INFRINGES ON USER NAME SPACE */
# elif defined _AIX
# define YYSTACK_ALLOC __alloca
# elif defined _MSC_VER
# include <malloc.h> /* INFRINGES ON USER NAME SPACE */
# define alloca _alloca
# else
# define YYSTACK_ALLOC alloca
# if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
/* Use EXIT_SUCCESS as a witness for stdlib.h. */
# ifndef EXIT_SUCCESS
# define EXIT_SUCCESS 0
# endif
# endif
# endif
# endif
# endif
# ifdef YYSTACK_ALLOC
/* Pacify GCC's 'empty if-body' warning. */
# define YYSTACK_FREE(Ptr) do { /* empty */; } while (0)
# ifndef YYSTACK_ALLOC_MAXIMUM
/* The OS might guarantee only one guard page at the bottom of the stack,
and a page size can be as small as 4096 bytes. So we cannot safely
invoke alloca (N) if N exceeds 4096. Use a slightly smaller number
to allow for a few compiler-allocated temporary stack slots. */
# define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */
# endif
# else
# define YYSTACK_ALLOC YYMALLOC
# define YYSTACK_FREE YYFREE
# ifndef YYSTACK_ALLOC_MAXIMUM
# define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM
# endif
# if (defined __cplusplus && ! defined EXIT_SUCCESS \
&& ! ((defined YYMALLOC || defined malloc) \
&& (defined YYFREE || defined free)))
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
# ifndef EXIT_SUCCESS
# define EXIT_SUCCESS 0
# endif
# endif
# ifndef YYMALLOC
# define YYMALLOC malloc
# if ! defined malloc && ! defined EXIT_SUCCESS
void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */
# endif
# endif
# ifndef YYFREE
# define YYFREE free
# if ! defined free && ! defined EXIT_SUCCESS
void free (void *); /* INFRINGES ON USER NAME SPACE */
# endif
# endif
# endif
#endif /* ! defined yyoverflow || YYERROR_VERBOSE */
#if (! defined yyoverflow \
&& (! defined __cplusplus \
|| (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL)))
/* A type that is properly aligned for any stack member. */
union yyalloc
{
yytype_int16 yyss_alloc;
YYSTYPE yyvs_alloc;
};
/* The size of the maximum gap between one aligned stack and the next. */
# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1)
/* The size of an array large to enough to hold all stacks, each with
N elements. */
# define YYSTACK_BYTES(N) \
((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \
+ YYSTACK_GAP_MAXIMUM)
# define YYCOPY_NEEDED 1
/* Relocate STACK from its old location to the new one. The
local variables YYSIZE and YYSTACKSIZE give the old and new number of
elements in the stack, and YYPTR gives the new location of the
stack. Advance YYPTR to a properly aligned location for the next
stack. */
# define YYSTACK_RELOCATE(Stack_alloc, Stack) \
do \
{ \
YYSIZE_T yynewbytes; \
YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \
Stack = &yyptr->Stack_alloc; \
yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
yyptr += yynewbytes / sizeof (*yyptr); \
} \
while (0)
#endif
#if defined YYCOPY_NEEDED && YYCOPY_NEEDED
/* Copy COUNT objects from SRC to DST. The source and destination do
not overlap. */
# ifndef YYCOPY
# if defined __GNUC__ && 1 < __GNUC__
# define YYCOPY(Dst, Src, Count) \
__builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src)))
# else
# define YYCOPY(Dst, Src, Count) \
do \
{ \
YYSIZE_T yyi; \
for (yyi = 0; yyi < (Count); yyi++) \
(Dst)[yyi] = (Src)[yyi]; \
} \
while (0)
# endif
# endif
#endif /* !YYCOPY_NEEDED */
/* YYFINAL -- State number of the termination state. */
#define YYFINAL 9
/* YYLAST -- Last index in YYTABLE. */
#define YYLAST 369
/* YYNTOKENS -- Number of terminals. */
#define YYNTOKENS 36
/* YYNNTS -- Number of nonterminals. */
#define YYNNTS 34
/* YYNRULES -- Number of rules. */
#define YYNRULES 106
/* YYNSTATES -- Number of states. */
#define YYNSTATES 201
/* YYTRANSLATE[YYX] -- Symbol number corresponding to YYX as returned
by yylex, with out-of-bounds checking. */
#define YYUNDEFTOK 2
#define YYMAXUTOK 282
#define YYTRANSLATE(YYX) \
((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK)
/* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM
as returned by yylex, without out-of-bounds checking. */
static const yytype_uint8 yytranslate[] =
{
0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 35, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 31, 30,
2, 34, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 32, 2, 33, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 28, 2, 29, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 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
};
#if YYDEBUG
/* YYRLINE[YYN] -- Source line where rule number YYN was defined. */
static const yytype_uint16 yyrline[] =
{
0, 54, 54, 55, 56, 57, 58, 62, 66, 70,
75, 81, 82, 88, 90, 92, 94, 97, 103, 104,
105, 106, 107, 108, 109, 110, 111, 115, 116, 120,
121, 122, 123, 128, 129, 133, 136, 137, 142, 143,
147, 148, 150, 152, 154, 156, 158, 160, 162, 164,
166, 167, 172, 173, 177, 178, 182, 183, 187, 188,
192, 193, 196, 197, 200, 201, 204, 205, 209, 210,
214, 218, 219, 230, 234, 238, 238, 239, 239, 240,
240, 241, 241, 247, 248, 249, 250, 251, 252, 253,
254, 255, 256, 257, 258, 259, 260, 261, 262, 263,
264, 265, 266, 267, 268, 269, 270
};
#endif
#if YYDEBUG || YYERROR_VERBOSE || 1
/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
First, the terminals, then, starting at YYNTOKENS, nonterminals. */
static const char *const yytname[] =
{
"$end", "error", "$undefined", "SCAN_ALIAS", "SCAN_ARRAY", "SCAN_ATTR",
"SCAN_BYTE", "SCAN_CODE", "SCAN_DATASET", "SCAN_DATA", "SCAN_ERROR",
"SCAN_FLOAT32", "SCAN_FLOAT64", "SCAN_GRID", "SCAN_INT16", "SCAN_INT32",
"SCAN_MAPS", "SCAN_MESSAGE", "SCAN_SEQUENCE", "SCAN_STRING",
"SCAN_STRUCTURE", "SCAN_UINT16", "SCAN_UINT32", "SCAN_URL", "SCAN_PTYPE",
"SCAN_PROG", "WORD_WORD", "WORD_STRING", "'{'", "'}'", "';'", "':'",
"'['", "']'", "'='", "','", "$accept", "start", "dataset", "attr", "err",
"datasetbody", "declarations", "declaration", "base_type", "array_decls",
"array_decl", "datasetname", "var_name", "attributebody", "attr_list",
"attribute", "bytes", "int16", "uint16", "int32", "uint32", "float32",
"float64", "strs", "urls", "url", "str_or_id", "alias", "errorbody",
"errorcode", "errormsg", "errorptype", "errorprog", "name", YY_NULLPTR
};
#endif
# ifdef YYPRINT
/* YYTOKNUM[NUM] -- (External) token number corresponding to the
(internal) symbol number NUM (which must be that of a token). */
static const yytype_uint16 yytoknum[] =
{
0, 256, 257, 258, 259, 260, 261, 262, 263, 264,
265, 266, 267, 268, 269, 270, 271, 272, 273, 274,
275, 276, 277, 278, 279, 280, 281, 282, 123, 125,
59, 58, 91, 93, 61, 44
};
# endif
#define YYPACT_NINF -91
#define yypact_value_is_default(Yystate) \
(!!((Yystate) == (-91)))
#define YYTABLE_NINF -1
#define yytable_value_is_error(Yytable_value) \
0
/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
STATE-NUM. */
static const yytype_int16 yypact[] =
{
6, -91, -91, -91, -91, 9, -22, 7, -16, -91,
-91, 10, -91, -91, -91, 20, -91, 37, -91, 191,
-6, 14, -91, -91, -91, -91, 17, -91, -91, 18,
-91, 19, -91, -91, -91, 271, -91, 320, -91, 27,
-91, -91, 320, -91, -91, -91, -91, 320, 320, -91,
320, 320, -91, -91, -91, 320, -91, 320, 320, 320,
-91, -91, -91, -91, -91, 24, 43, 35, 39, 50,
74, -91, -91, -91, -91, -91, -91, -91, -91, -91,
-91, -91, -91, -91, 55, -91, -91, -91, 60, 67,
68, 70, 71, 73, 295, 77, 78, 295, -91, -91,
65, 79, 66, 81, 76, 69, 127, -91, 4, -91,
-91, -20, -91, -13, -91, -12, -91, -10, -91, -9,
-91, 32, -91, -91, -91, 33, -91, 34, 42, -91,
-91, 218, -91, 80, 82, 75, 83, 346, 320, 320,
-91, -91, 159, -91, -91, 85, -91, 88, -91, 89,
-91, 90, -91, 91, -91, 295, -91, 92, -91, 93,
-91, 295, -91, -91, 95, 94, 96, 105, 97, -91,
98, 103, 100, -91, -91, -91, -91, -91, -91, -91,
-91, -91, -91, 102, -91, 99, -91, 12, -91, 111,
109, -91, -91, -91, -91, 118, 244, -91, 320, 106,
-91
};
/* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM.
Performed when YYTABLE does not specify something else to do. Zero
means the default is an error. */
static const yytype_uint8 yydefact[] =
{
0, 6, 8, 7, 9, 0, 0, 0, 0, 1,
11, 2, 37, 38, 4, 75, 5, 0, 3, 0,
0, 77, 17, 18, 23, 24, 0, 19, 21, 0,
26, 0, 20, 22, 25, 0, 12, 0, 51, 84,
85, 86, 87, 103, 88, 89, 90, 91, 92, 93,
94, 95, 96, 104, 97, 98, 99, 100, 101, 102,
106, 105, 83, 36, 39, 0, 0, 0, 0, 79,
0, 11, 11, 34, 84, 87, 91, 92, 94, 95,
98, 100, 101, 102, 0, 33, 35, 27, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 40, 38,
0, 0, 0, 81, 0, 0, 0, 10, 0, 73,
52, 0, 62, 0, 64, 0, 54, 0, 58, 0,
72, 0, 66, 71, 56, 0, 60, 0, 0, 68,
70, 0, 76, 0, 0, 0, 0, 0, 0, 0,
32, 13, 0, 28, 41, 0, 46, 0, 47, 0,
42, 0, 44, 0, 48, 0, 43, 0, 45, 0,
49, 0, 50, 78, 0, 0, 0, 0, 0, 27,
83, 0, 0, 53, 63, 65, 55, 59, 67, 57,
61, 69, 80, 0, 74, 0, 15, 0, 29, 0,
0, 82, 11, 14, 30, 0, 0, 31, 0, 0,
16
};
/* YYPGOTO[NTERM-NUM]. */
static const yytype_int8 yypgoto[] =
{
-91, -91, -91, -91, -91, -91, -69, -15, -91, -17,
-91, -91, -37, -91, 54, -91, -91, -91, -91, -91,
-91, -91, -91, -91, -91, -7, -90, -91, -91, -91,
-91, -91, -91, -18
};
/* YYDEFGOTO[NTERM-NUM]. */
static const yytype_int16 yydefgoto[] =
{
-1, 5, 6, 7, 8, 11, 17, 36, 37, 108,
143, 84, 85, 14, 19, 64, 111, 117, 125, 119,
127, 113, 115, 121, 128, 129, 130, 65, 16, 21,
69, 103, 136, 86
};
/* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If
positive, shift that token. If negative, reduce the rule whose
number is the opposite. If YYTABLE_NINF, syntax error. */
static const yytype_uint8 yytable[] =
{
87, 66, 105, 106, 122, 140, 10, 1, 12, 9,
144, 2, 15, 140, 3, 145, 4, 146, 148, 18,
150, 152, 147, 149, 89, 151, 153, 20, 67, 90,
91, 68, 92, 93, 141, 13, 142, 94, 22, 95,
96, 97, 193, 23, 142, 70, 71, 72, 24, 25,
26, 27, 28, 88, 98, 29, 30, 31, 32, 33,
34, 100, 154, 156, 158, 178, 35, 155, 157, 159,
22, 99, 160, 101, 102, 23, 123, 161, 104, 123,
24, 25, 26, 27, 28, 107, 109, 29, 30, 31,
32, 33, 34, 110, 112, 132, 114, 116, 138, 118,
134, 168, 169, 124, 126, 133, 135, 137, 164, 165,
163, 173, 166, 66, 174, 175, 176, 177, 179, 180,
183, 185, 167, 196, 172, 182, 184, 186, 22, 189,
192, 188, 191, 23, 190, 195, 200, 123, 24, 25,
26, 27, 28, 123, 194, 29, 30, 31, 32, 33,
34, 197, 187, 131, 181, 0, 139, 0, 0, 0,
0, 199, 74, 40, 41, 75, 43, 44, 45, 46,
76, 77, 49, 78, 79, 52, 53, 54, 80, 56,
81, 82, 83, 60, 61, 170, 0, 0, 0, 0,
0, 0, 38, 171, 39, 40, 41, 42, 43, 44,
45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
55, 56, 57, 58, 59, 60, 61, 62, 0, 38,
63, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
58, 59, 60, 61, 62, 22, 0, 162, 0, 0,
23, 0, 0, 0, 0, 24, 25, 26, 27, 28,
0, 0, 29, 30, 31, 32, 33, 34, 0, 0,
0, 0, 73, 198, 74, 40, 41, 75, 43, 44,
45, 46, 76, 77, 49, 78, 79, 52, 53, 54,
80, 56, 81, 82, 83, 60, 61, 62, 74, 40,
41, 75, 43, 44, 45, 46, 76, 77, 49, 78,
79, 52, 53, 54, 80, 56, 81, 82, 83, 60,
61, 62, 120, 74, 40, 41, 75, 43, 44, 45,
46, 76, 77, 49, 78, 79, 52, 53, 54, 80,
56, 81, 82, 83, 60, 61, 62, 22, 0, 0,
0, 0, 23, 0, 0, 0, 0, 24, 25, 26,
27, 28, 0, 0, 29, 30, 31, 32, 33, 34
};
static const yytype_int16 yycheck[] =
{
37, 19, 71, 72, 94, 1, 28, 1, 1, 0,
30, 5, 28, 1, 8, 35, 10, 30, 30, 9,
30, 30, 35, 35, 42, 35, 35, 7, 34, 47,
48, 17, 50, 51, 30, 28, 32, 55, 1, 57,
58, 59, 30, 6, 32, 28, 28, 28, 11, 12,
13, 14, 15, 26, 30, 18, 19, 20, 21, 22,
23, 26, 30, 30, 30, 155, 29, 35, 35, 35,
1, 28, 30, 34, 24, 6, 94, 35, 4, 97,
11, 12, 13, 14, 15, 30, 26, 18, 19, 20,
21, 22, 23, 26, 26, 30, 26, 26, 29, 26,
34, 138, 139, 26, 26, 26, 25, 31, 26, 34,
30, 26, 29, 131, 26, 26, 26, 26, 26, 26,
26, 16, 137, 192, 142, 30, 30, 30, 1, 26,
31, 33, 30, 6, 34, 26, 30, 155, 11, 12,
13, 14, 15, 161, 33, 18, 19, 20, 21, 22,
23, 33, 169, 99, 161, -1, 29, -1, -1, -1,
-1, 198, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, -1, -1, -1, -1,
-1, -1, 1, 34, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24, 25, 26, -1, 1,
29, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
22, 23, 24, 25, 26, 1, -1, 29, -1, -1,
6, -1, -1, -1, -1, 11, 12, 13, 14, 15,
-1, -1, 18, 19, 20, 21, 22, 23, -1, -1,
-1, -1, 1, 29, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24, 25, 26, 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, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 1, -1, -1,
-1, -1, 6, -1, -1, -1, -1, 11, 12, 13,
14, 15, -1, -1, 18, 19, 20, 21, 22, 23
};
/* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
symbol of state STATE-NUM. */
static const yytype_uint8 yystos[] =
{
0, 1, 5, 8, 10, 37, 38, 39, 40, 0,
28, 41, 1, 28, 49, 28, 64, 42, 9, 50,
7, 65, 1, 6, 11, 12, 13, 14, 15, 18,
19, 20, 21, 22, 23, 29, 43, 44, 1, 3,
4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 29, 51, 63, 69, 34, 17, 66,
28, 28, 28, 1, 3, 6, 11, 12, 14, 15,
19, 21, 22, 23, 47, 48, 69, 48, 26, 69,
69, 69, 69, 69, 69, 69, 69, 69, 30, 28,
26, 34, 24, 67, 4, 42, 42, 30, 45, 26,
26, 52, 26, 57, 26, 58, 26, 53, 26, 55,
27, 59, 62, 69, 26, 54, 26, 56, 60, 61,
62, 50, 30, 26, 34, 25, 68, 31, 29, 29,
1, 30, 32, 46, 30, 35, 30, 35, 30, 35,
30, 35, 30, 35, 30, 35, 30, 35, 30, 35,
30, 35, 29, 30, 26, 34, 29, 43, 48, 48,
26, 34, 69, 26, 26, 26, 26, 26, 62, 26,
26, 61, 30, 26, 30, 16, 30, 45, 33, 26,
34, 30, 31, 30, 33, 26, 42, 33, 29, 48,
30
};
/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */
static const yytype_uint8 yyr1[] =
{
0, 36, 37, 37, 37, 37, 37, 38, 39, 40,
41, 42, 42, 43, 43, 43, 43, 43, 44, 44,
44, 44, 44, 44, 44, 44, 44, 45, 45, 46,
46, 46, 46, 47, 47, 48, 49, 49, 50, 50,
51, 51, 51, 51, 51, 51, 51, 51, 51, 51,
51, 51, 52, 52, 53, 53, 54, 54, 55, 55,
56, 56, 57, 57, 58, 58, 59, 59, 60, 60,
61, 62, 62, 63, 64, 65, 65, 66, 66, 67,
67, 68, 68, 69, 69, 69, 69, 69, 69, 69,
69, 69, 69, 69, 69, 69, 69, 69, 69, 69,
69, 69, 69, 69, 69, 69, 69
};
/* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */
static const yytype_uint8 yyr2[] =
{
0, 2, 2, 3, 2, 2, 1, 1, 1, 1,
5, 0, 2, 4, 7, 6, 11, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 0, 2, 3,
4, 5, 1, 1, 1, 1, 3, 1, 0, 2,
2, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 1, 1, 3, 1, 3, 1, 3, 1, 3,
1, 3, 1, 3, 1, 3, 1, 3, 1, 3,
1, 1, 1, 3, 7, 0, 4, 0, 4, 0,
4, 0, 4, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1
};
#define yyerrok (yyerrstatus = 0)
#define yyclearin (yychar = YYEMPTY)
#define YYEMPTY (-2)
#define YYEOF 0
#define YYACCEPT goto yyacceptlab
#define YYABORT goto yyabortlab
#define YYERROR goto yyerrorlab
#define YYRECOVERING() (!!yyerrstatus)
#define YYBACKUP(Token, Value) \
do \
if (yychar == YYEMPTY) \
{ \
yychar = (Token); \
yylval = (Value); \
YYPOPSTACK (yylen); \
yystate = *yyssp; \
goto yybackup; \
} \
else \
{ \
yyerror (parsestate, YY_("syntax error: cannot back up")); \
YYERROR; \
} \
while (0)
/* Error token number */
#define YYTERROR 1
#define YYERRCODE 256
/* Enable debugging if requested. */
#if YYDEBUG
# ifndef YYFPRINTF
# include <stdio.h> /* INFRINGES ON USER NAME SPACE */
# define YYFPRINTF fprintf
# endif
# define YYDPRINTF(Args) \
do { \
if (yydebug) \
YYFPRINTF Args; \
} while (0)
/* This macro is provided for backward compatibility. */
#ifndef YY_LOCATION_PRINT
# define YY_LOCATION_PRINT(File, Loc) ((void) 0)
#endif
# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \
do { \
if (yydebug) \
{ \
YYFPRINTF (stderr, "%s ", Title); \
yy_symbol_print (stderr, \
Type, Value, parsestate); \
YYFPRINTF (stderr, "\n"); \
} \
} while (0)
/*----------------------------------------.
| Print this symbol's value on YYOUTPUT. |
`----------------------------------------*/
static void
yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, DAPparsestate* parsestate)
{
FILE *yyo = yyoutput;
YYUSE (yyo);
YYUSE (parsestate);
if (!yyvaluep)
return;
# ifdef YYPRINT
if (yytype < YYNTOKENS)
YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep);
# endif
YYUSE (yytype);
}
/*--------------------------------.
| Print this symbol on YYOUTPUT. |
`--------------------------------*/
static void
yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, DAPparsestate* parsestate)
{
YYFPRINTF (yyoutput, "%s %s (",
yytype < YYNTOKENS ? "token" : "nterm", yytname[yytype]);
yy_symbol_value_print (yyoutput, yytype, yyvaluep, parsestate);
YYFPRINTF (yyoutput, ")");
}
/*------------------------------------------------------------------.
| yy_stack_print -- Print the state stack from its BOTTOM up to its |
| TOP (included). |
`------------------------------------------------------------------*/
static void
yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop)
{
YYFPRINTF (stderr, "Stack now");
for (; yybottom <= yytop; yybottom++)
{
int yybot = *yybottom;
YYFPRINTF (stderr, " %d", yybot);
}
YYFPRINTF (stderr, "\n");
}
# define YY_STACK_PRINT(Bottom, Top) \
do { \
if (yydebug) \
yy_stack_print ((Bottom), (Top)); \
} while (0)
/*------------------------------------------------.
| Report that the YYRULE is going to be reduced. |
`------------------------------------------------*/
static void
yy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, int yyrule, DAPparsestate* parsestate)
{
unsigned long int yylno = yyrline[yyrule];
int yynrhs = yyr2[yyrule];
int yyi;
YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n",
yyrule - 1, yylno);
/* The symbols being reduced. */
for (yyi = 0; yyi < yynrhs; yyi++)
{
YYFPRINTF (stderr, " $%d = ", yyi + 1);
yy_symbol_print (stderr,
yystos[yyssp[yyi + 1 - yynrhs]],
&(yyvsp[(yyi + 1) - (yynrhs)])
, parsestate);
YYFPRINTF (stderr, "\n");
}
}
# define YY_REDUCE_PRINT(Rule) \
do { \
if (yydebug) \
yy_reduce_print (yyssp, yyvsp, Rule, parsestate); \
} while (0)
/* Nonzero means print parse trace. It is left uninitialized so that
multiple parsers can coexist. */
int yydebug;
#else /* !YYDEBUG */
# define YYDPRINTF(Args)
# define YY_SYMBOL_PRINT(Title, Type, Value, Location)
# define YY_STACK_PRINT(Bottom, Top)
# define YY_REDUCE_PRINT(Rule)
#endif /* !YYDEBUG */
/* YYINITDEPTH -- initial size of the parser's stacks. */
#ifndef YYINITDEPTH
# define YYINITDEPTH 200
#endif
/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only
if the built-in stack extension method is used).
Do not make this value too large; the results are undefined if
YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH)
evaluated with infinite-precision integer arithmetic. */
#ifndef YYMAXDEPTH
# define YYMAXDEPTH 10000
#endif
#if YYERROR_VERBOSE
# ifndef yystrlen
# if defined __GLIBC__ && defined _STRING_H
# define yystrlen strlen
# else
/* Return the length of YYSTR. */
static YYSIZE_T
yystrlen (const char *yystr)
{
YYSIZE_T yylen;
for (yylen = 0; yystr[yylen]; yylen++)
continue;
return yylen;
}
# endif
# endif
# ifndef yystpcpy
# if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE
# define yystpcpy stpcpy
# else
/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in
YYDEST. */
static char *
yystpcpy (char *yydest, const char *yysrc)
{
char *yyd = yydest;
const char *yys = yysrc;
while ((*yyd++ = *yys++) != '\0')
continue;
return yyd - 1;
}
# endif
# endif
# ifndef yytnamerr
/* Copy to YYRES the contents of YYSTR after stripping away unnecessary
quotes and backslashes, so that it's suitable for yyerror. The
heuristic is that double-quoting is unnecessary unless the string
contains an apostrophe, a comma, or backslash (other than
backslash-backslash). YYSTR is taken from yytname. If YYRES is
null, do not copy; instead, return the length of what the result
would have been. */
static YYSIZE_T
yytnamerr (char *yyres, const char *yystr)
{
if (*yystr == '"')
{
YYSIZE_T yyn = 0;
char const *yyp = yystr;
for (;;)
switch (*++yyp)
{
case '\'':
case ',':
goto do_not_strip_quotes;
case '\\':
if (*++yyp != '\\')
goto do_not_strip_quotes;
/* Fall through. */
default:
if (yyres)
yyres[yyn] = *yyp;
yyn++;
break;
case '"':
if (yyres)
yyres[yyn] = '\0';
return yyn;
}
do_not_strip_quotes: ;
}
if (! yyres)
return yystrlen (yystr);
return yystpcpy (yyres, yystr) - yyres;
}
# endif
/* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message
about the unexpected token YYTOKEN for the state stack whose top is
YYSSP.
Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is
not large enough to hold the message. In that case, also set
*YYMSG_ALLOC to the required number of bytes. Return 2 if the
required number of bytes is too large to store. */
static int
yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg,
yytype_int16 *yyssp, int yytoken)
{
YYSIZE_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]);
YYSIZE_T yysize = yysize0;
enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
/* Internationalized format string. */
const char *yyformat = YY_NULLPTR;
/* Arguments of yyformat. */
char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
/* Number of reported tokens (one for the "unexpected", one per
"expected"). */
int yycount = 0;
/* There are many possibilities here to consider:
- If this state is a consistent state with a default action, then
the only way this function was invoked is if the default action
is an error action. In that case, don't check for expected
tokens because there are none.
- The only way there can be no lookahead present (in yychar) is if
this state is a consistent state with a default action. Thus,
detecting the absence of a lookahead is sufficient to determine
that there is no unexpected or expected token to report. In that
case, just report a simple "syntax error".
- Don't assume there isn't a lookahead just because this state is a
consistent state with a default action. There might have been a
previous inconsistent state, consistent state with a non-default
action, or user semantic action that manipulated yychar.
- Of course, the expected token list depends on states to have
correct lookahead information, and it depends on the parser not
to perform extra reductions after fetching a lookahead from the
scanner and before detecting a syntax error. Thus, state merging
(from LALR or IELR) and default reductions corrupt the expected
token list. However, the list is correct for canonical LR with
one exception: it will still contain any token that will not be
accepted due to an error action in a later state.
*/
if (yytoken != YYEMPTY)
{
int yyn = yypact[*yyssp];
yyarg[yycount++] = yytname[yytoken];
if (!yypact_value_is_default (yyn))
{
/* Start YYX at -YYN if negative to avoid negative indexes in
YYCHECK. In other words, skip the first -YYN actions for
this state because they are default actions. */
int yyxbegin = yyn < 0 ? -yyn : 0;
/* Stay within bounds of both yycheck and yytname. */
int yychecklim = YYLAST - yyn + 1;
int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
int yyx;
for (yyx = yyxbegin; yyx < yyxend; ++yyx)
if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR
&& !yytable_value_is_error (yytable[yyx + yyn]))
{
if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
{
yycount = 1;
yysize = yysize0;
break;
}
yyarg[yycount++] = yytname[yyx];
{
YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]);
if (! (yysize <= yysize1
&& yysize1 <= YYSTACK_ALLOC_MAXIMUM))
return 2;
yysize = yysize1;
}
}
}
}
switch (yycount)
{
# define YYCASE_(N, S) \
case N: \
yyformat = S; \
break
YYCASE_(0, YY_("syntax error"));
YYCASE_(1, YY_("syntax error, unexpected %s"));
YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s"));
YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s"));
YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s"));
YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"));
# undef YYCASE_
}
{
YYSIZE_T yysize1 = yysize + yystrlen (yyformat);
if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM))
return 2;
yysize = yysize1;
}
if (*yymsg_alloc < yysize)
{
*yymsg_alloc = 2 * yysize;
if (! (yysize <= *yymsg_alloc
&& *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM))
*yymsg_alloc = YYSTACK_ALLOC_MAXIMUM;
return 1;
}
/* Avoid sprintf, as that infringes on the user's name space.
Don't have undefined behavior even if the translation
produced a string with the wrong number of "%s"s. */
{
char *yyp = *yymsg;
int yyi = 0;
while ((*yyp = *yyformat) != '\0')
if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount)
{
yyp += yytnamerr (yyp, yyarg[yyi++]);
yyformat += 2;
}
else
{
yyp++;
yyformat++;
}
}
return 0;
}
#endif /* YYERROR_VERBOSE */
/*-----------------------------------------------.
| Release the memory associated to this symbol. |
`-----------------------------------------------*/
static void
yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, DAPparsestate* parsestate)
{
YYUSE (yyvaluep);
YYUSE (parsestate);
if (!yymsg)
yymsg = "Deleting";
YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
YYUSE (yytype);
YY_IGNORE_MAYBE_UNINITIALIZED_END
}
/*----------.
| yyparse. |
`----------*/
int
yyparse (DAPparsestate* parsestate)
{
/* The lookahead symbol. */
int yychar;
/* The semantic value of the lookahead symbol. */
/* Default value used for initialization, for pacifying older GCCs
or non-GCC compilers. */
YY_INITIAL_VALUE (static YYSTYPE yyval_default;)
YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default);
/* Number of syntax errors so far. */
int yynerrs;
int yystate;
/* Number of tokens to shift before error messages enabled. */
int yyerrstatus;
/* The stacks and their tools:
'yyss': related to states.
'yyvs': related to semantic values.
Refer to the stacks through separate pointers, to allow yyoverflow
to reallocate them elsewhere. */
/* The state stack. */
yytype_int16 yyssa[YYINITDEPTH];
yytype_int16 *yyss;
yytype_int16 *yyssp;
/* The semantic value stack. */
YYSTYPE yyvsa[YYINITDEPTH];
YYSTYPE *yyvs;
YYSTYPE *yyvsp;
YYSIZE_T yystacksize;
int yyn;
int yyresult;
/* Lookahead token as an internal (translated) token number. */
int yytoken = 0;
/* The variables used to return semantic value and location from the
action routines. */
YYSTYPE yyval;
#if YYERROR_VERBOSE
/* Buffer for error messages, and its allocated size. */
char yymsgbuf[128];
char *yymsg = yymsgbuf;
YYSIZE_T yymsg_alloc = sizeof yymsgbuf;
#endif
#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N))
/* The number of symbols on the RHS of the reduced rule.
Keep to zero when no symbol should be popped. */
int yylen = 0;
yyssp = yyss = yyssa;
yyvsp = yyvs = yyvsa;
yystacksize = YYINITDEPTH;
YYDPRINTF ((stderr, "Starting parse\n"));
yystate = 0;
yyerrstatus = 0;
yynerrs = 0;
yychar = YYEMPTY; /* Cause a token to be read. */
goto yysetstate;
/*------------------------------------------------------------.
| yynewstate -- Push a new state, which is found in yystate. |
`------------------------------------------------------------*/
yynewstate:
/* In all cases, when you get here, the value and location stacks
have just been pushed. So pushing a state here evens the stacks. */
yyssp++;
yysetstate:
*yyssp = yystate;
if (yyss + yystacksize - 1 <= yyssp)
{
/* Get the current used size of the three stacks, in elements. */
YYSIZE_T yysize = yyssp - yyss + 1;
#ifdef yyoverflow
{
/* Give user a chance to reallocate the stack. Use copies of
these so that the &'s don't force the real ones into
memory. */
YYSTYPE *yyvs1 = yyvs;
yytype_int16 *yyss1 = yyss;
/* Each stack pointer address is followed by the size of the
data in use in that stack, in bytes. This used to be a
conditional around just the two extra args, but that might
be undefined if yyoverflow is a macro. */
yyoverflow (YY_("memory exhausted"),
&yyss1, yysize * sizeof (*yyssp),
&yyvs1, yysize * sizeof (*yyvsp),
&yystacksize);
yyss = yyss1;
yyvs = yyvs1;
}
#else /* no yyoverflow */
# ifndef YYSTACK_RELOCATE
goto yyexhaustedlab;
# else
/* Extend the stack our own way. */
if (YYMAXDEPTH <= yystacksize)
goto yyexhaustedlab;
yystacksize *= 2;
if (YYMAXDEPTH < yystacksize)
yystacksize = YYMAXDEPTH;
{
yytype_int16 *yyss1 = yyss;
union yyalloc *yyptr =
(union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
if (! yyptr)
goto yyexhaustedlab;
YYSTACK_RELOCATE (yyss_alloc, yyss);
YYSTACK_RELOCATE (yyvs_alloc, yyvs);
# undef YYSTACK_RELOCATE
if (yyss1 != yyssa)
YYSTACK_FREE (yyss1);
}
# endif
#endif /* no yyoverflow */
yyssp = yyss + yysize - 1;
yyvsp = yyvs + yysize - 1;
YYDPRINTF ((stderr, "Stack size increased to %lu\n",
(unsigned long int) yystacksize));
if (yyss + yystacksize - 1 <= yyssp)
YYABORT;
}
YYDPRINTF ((stderr, "Entering state %d\n", yystate));
if (yystate == YYFINAL)
YYACCEPT;
goto yybackup;
/*-----------.
| yybackup. |
`-----------*/
yybackup:
/* Do appropriate processing given the current state. Read a
lookahead token if we need one and don't already have one. */
/* First try to decide what to do without reference to lookahead token. */
yyn = yypact[yystate];
if (yypact_value_is_default (yyn))
goto yydefault;
/* Not known => get a lookahead token if don't already have one. */
/* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */
if (yychar == YYEMPTY)
{
YYDPRINTF ((stderr, "Reading a token: "));
yychar = yylex (&yylval, parsestate);
}
if (yychar <= YYEOF)
{
yychar = yytoken = YYEOF;
YYDPRINTF ((stderr, "Now at end of input.\n"));
}
else
{
yytoken = YYTRANSLATE (yychar);
YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
}
/* If the proper action on seeing token YYTOKEN is to reduce or to
detect an error, take that action. */
yyn += yytoken;
if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken)
goto yydefault;
yyn = yytable[yyn];
if (yyn <= 0)
{
if (yytable_value_is_error (yyn))
goto yyerrlab;
yyn = -yyn;
goto yyreduce;
}
/* Count tokens shifted since error; after three, turn off error
status. */
if (yyerrstatus)
yyerrstatus--;
/* Shift the lookahead token. */
YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
/* Discard the shifted token. */
yychar = YYEMPTY;
yystate = yyn;
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
*++yyvsp = yylval;
YY_IGNORE_MAYBE_UNINITIALIZED_END
goto yynewstate;
/*-----------------------------------------------------------.
| yydefault -- do the default action for the current state. |
`-----------------------------------------------------------*/
yydefault:
yyn = yydefact[yystate];
if (yyn == 0)
goto yyerrlab;
goto yyreduce;
/*-----------------------------.
| yyreduce -- Do a reduction. |
`-----------------------------*/
yyreduce:
/* yyn is the number of a rule to reduce with. */
yylen = yyr2[yyn];
/* If YYLEN is nonzero, implement the default value of the action:
'$$ = $1'.
Otherwise, the following line sets YYVAL to garbage.
This behavior is undocumented and Bison
users should not rely upon it. Assigning to YYVAL
unconditionally makes the parser a bit smaller, and it avoids a
GCC warning that YYVAL may be used uninitialized. */
yyval = yyvsp[1-yylen];
YY_REDUCE_PRINT (yyn);
switch (yyn)
{
case 6:
#line 58 "dap.y" /* yacc.c:1646 */
{dap_unrecognizedresponse(parsestate); YYABORT;}
#line 1412 "dap.tab.c" /* yacc.c:1646 */
break;
case 7:
#line 63 "dap.y" /* yacc.c:1646 */
{dap_tagparse(parsestate,SCAN_DATASET);}
#line 1418 "dap.tab.c" /* yacc.c:1646 */
break;
case 8:
#line 67 "dap.y" /* yacc.c:1646 */
{dap_tagparse(parsestate,SCAN_ATTR);}
#line 1424 "dap.tab.c" /* yacc.c:1646 */
break;
case 9:
#line 71 "dap.y" /* yacc.c:1646 */
{dap_tagparse(parsestate,SCAN_ERROR);}
#line 1430 "dap.tab.c" /* yacc.c:1646 */
break;
case 10:
#line 76 "dap.y" /* yacc.c:1646 */
{dap_datasetbody(parsestate,(yyvsp[-1]),(yyvsp[-3]));}
#line 1436 "dap.tab.c" /* yacc.c:1646 */
break;
case 11:
#line 81 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_declarations(parsestate,null,null);}
#line 1442 "dap.tab.c" /* yacc.c:1646 */
break;
case 12:
#line 82 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_declarations(parsestate,(yyvsp[-1]),(yyvsp[0]));}
#line 1448 "dap.tab.c" /* yacc.c:1646 */
break;
case 13:
#line 89 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_makebase(parsestate,(yyvsp[-2]),(yyvsp[-3]),(yyvsp[-1]));}
#line 1454 "dap.tab.c" /* yacc.c:1646 */
break;
case 14:
#line 91 "dap.y" /* yacc.c:1646 */
{if(((yyval)=dap_makestructure(parsestate,(yyvsp[-2]),(yyvsp[-1]),(yyvsp[-4])))==null) {YYABORT;}}
#line 1460 "dap.tab.c" /* yacc.c:1646 */
break;
case 15:
#line 93 "dap.y" /* yacc.c:1646 */
{if(((yyval)=dap_makesequence(parsestate,(yyvsp[-1]),(yyvsp[-3])))==null) {YYABORT;}}
#line 1466 "dap.tab.c" /* yacc.c:1646 */
break;
case 16:
#line 96 "dap.y" /* yacc.c:1646 */
{if(((yyval)=dap_makegrid(parsestate,(yyvsp[-1]),(yyvsp[-6]),(yyvsp[-3])))==null) {YYABORT;}}
#line 1472 "dap.tab.c" /* yacc.c:1646 */
break;
case 17:
#line 98 "dap.y" /* yacc.c:1646 */
{dapsemanticerror(parsestate,OC_EBADTYPE,"Unrecognized type"); YYABORT;}
#line 1478 "dap.tab.c" /* yacc.c:1646 */
break;
case 18:
#line 103 "dap.y" /* yacc.c:1646 */
{(yyval)=(Object)SCAN_BYTE;}
#line 1484 "dap.tab.c" /* yacc.c:1646 */
break;
case 19:
#line 104 "dap.y" /* yacc.c:1646 */
{(yyval)=(Object)SCAN_INT16;}
#line 1490 "dap.tab.c" /* yacc.c:1646 */
break;
case 20:
#line 105 "dap.y" /* yacc.c:1646 */
{(yyval)=(Object)SCAN_UINT16;}
#line 1496 "dap.tab.c" /* yacc.c:1646 */
break;
case 21:
#line 106 "dap.y" /* yacc.c:1646 */
{(yyval)=(Object)SCAN_INT32;}
#line 1502 "dap.tab.c" /* yacc.c:1646 */
break;
case 22:
#line 107 "dap.y" /* yacc.c:1646 */
{(yyval)=(Object)SCAN_UINT32;}
#line 1508 "dap.tab.c" /* yacc.c:1646 */
break;
case 23:
#line 108 "dap.y" /* yacc.c:1646 */
{(yyval)=(Object)SCAN_FLOAT32;}
#line 1514 "dap.tab.c" /* yacc.c:1646 */
break;
case 24:
#line 109 "dap.y" /* yacc.c:1646 */
{(yyval)=(Object)SCAN_FLOAT64;}
#line 1520 "dap.tab.c" /* yacc.c:1646 */
break;
case 25:
#line 110 "dap.y" /* yacc.c:1646 */
{(yyval)=(Object)SCAN_URL;}
#line 1526 "dap.tab.c" /* yacc.c:1646 */
break;
case 26:
#line 111 "dap.y" /* yacc.c:1646 */
{(yyval)=(Object)SCAN_STRING;}
#line 1532 "dap.tab.c" /* yacc.c:1646 */
break;
case 27:
#line 115 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_arraydecls(parsestate,null,null);}
#line 1538 "dap.tab.c" /* yacc.c:1646 */
break;
case 28:
#line 116 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_arraydecls(parsestate,(yyvsp[-1]),(yyvsp[0]));}
#line 1544 "dap.tab.c" /* yacc.c:1646 */
break;
case 29:
#line 120 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_arraydecl(parsestate,null,(yyvsp[-1]));}
#line 1550 "dap.tab.c" /* yacc.c:1646 */
break;
case 30:
#line 121 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_arraydecl(parsestate,null,(yyvsp[-1]));}
#line 1556 "dap.tab.c" /* yacc.c:1646 */
break;
case 31:
#line 122 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_arraydecl(parsestate,(yyvsp[-3]),(yyvsp[-1]));}
#line 1562 "dap.tab.c" /* yacc.c:1646 */
break;
case 32:
#line 124 "dap.y" /* yacc.c:1646 */
{dapsemanticerror(parsestate,OC_EDIMSIZE,"Illegal dimension declaration"); YYABORT;}
#line 1568 "dap.tab.c" /* yacc.c:1646 */
break;
case 33:
#line 128 "dap.y" /* yacc.c:1646 */
{(yyval)=(yyvsp[0]);}
#line 1574 "dap.tab.c" /* yacc.c:1646 */
break;
case 34:
#line 130 "dap.y" /* yacc.c:1646 */
{dapsemanticerror(parsestate,OC_EDDS,"Illegal dataset declaration"); YYABORT;}
#line 1580 "dap.tab.c" /* yacc.c:1646 */
break;
case 35:
#line 133 "dap.y" /* yacc.c:1646 */
{(yyval)=(yyvsp[0]);}
#line 1586 "dap.tab.c" /* yacc.c:1646 */
break;
case 36:
#line 136 "dap.y" /* yacc.c:1646 */
{dap_attributebody(parsestate,(yyvsp[-1]));}
#line 1592 "dap.tab.c" /* yacc.c:1646 */
break;
case 37:
#line 138 "dap.y" /* yacc.c:1646 */
{dapsemanticerror(parsestate,OC_EDAS,"Illegal DAS body"); YYABORT;}
#line 1598 "dap.tab.c" /* yacc.c:1646 */
break;
case 38:
#line 142 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attrlist(parsestate,null,null);}
#line 1604 "dap.tab.c" /* yacc.c:1646 */
break;
case 39:
#line 143 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attrlist(parsestate,(yyvsp[-1]),(yyvsp[0]));}
#line 1610 "dap.tab.c" /* yacc.c:1646 */
break;
case 40:
#line 147 "dap.y" /* yacc.c:1646 */
{(yyval)=null;}
#line 1616 "dap.tab.c" /* yacc.c:1646 */
break;
case 41:
#line 149 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attribute(parsestate,(yyvsp[-2]),(yyvsp[-1]),(Object)SCAN_BYTE);}
#line 1622 "dap.tab.c" /* yacc.c:1646 */
break;
case 42:
#line 151 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attribute(parsestate,(yyvsp[-2]),(yyvsp[-1]),(Object)SCAN_INT16);}
#line 1628 "dap.tab.c" /* yacc.c:1646 */
break;
case 43:
#line 153 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attribute(parsestate,(yyvsp[-2]),(yyvsp[-1]),(Object)SCAN_UINT16);}
#line 1634 "dap.tab.c" /* yacc.c:1646 */
break;
case 44:
#line 155 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attribute(parsestate,(yyvsp[-2]),(yyvsp[-1]),(Object)SCAN_INT32);}
#line 1640 "dap.tab.c" /* yacc.c:1646 */
break;
case 45:
#line 157 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attribute(parsestate,(yyvsp[-2]),(yyvsp[-1]),(Object)SCAN_UINT32);}
#line 1646 "dap.tab.c" /* yacc.c:1646 */
break;
case 46:
#line 159 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attribute(parsestate,(yyvsp[-2]),(yyvsp[-1]),(Object)SCAN_FLOAT32);}
#line 1652 "dap.tab.c" /* yacc.c:1646 */
break;
case 47:
#line 161 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attribute(parsestate,(yyvsp[-2]),(yyvsp[-1]),(Object)SCAN_FLOAT64);}
#line 1658 "dap.tab.c" /* yacc.c:1646 */
break;
case 48:
#line 163 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attribute(parsestate,(yyvsp[-2]),(yyvsp[-1]),(Object)SCAN_STRING);}
#line 1664 "dap.tab.c" /* yacc.c:1646 */
break;
case 49:
#line 165 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attribute(parsestate,(yyvsp[-2]),(yyvsp[-1]),(Object)SCAN_URL);}
#line 1670 "dap.tab.c" /* yacc.c:1646 */
break;
case 50:
#line 166 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attrset(parsestate,(yyvsp[-3]),(yyvsp[-1]));}
#line 1676 "dap.tab.c" /* yacc.c:1646 */
break;
case 51:
#line 168 "dap.y" /* yacc.c:1646 */
{dapsemanticerror(parsestate,OC_EDAS,"Illegal attribute"); YYABORT;}
#line 1682 "dap.tab.c" /* yacc.c:1646 */
break;
case 52:
#line 172 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attrvalue(parsestate,null,(yyvsp[0]),(Object)SCAN_BYTE);}
#line 1688 "dap.tab.c" /* yacc.c:1646 */
break;
case 53:
#line 174 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attrvalue(parsestate,(yyvsp[-2]),(yyvsp[0]),(Object)SCAN_BYTE);}
#line 1694 "dap.tab.c" /* yacc.c:1646 */
break;
case 54:
#line 177 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attrvalue(parsestate,null,(yyvsp[0]),(Object)SCAN_INT16);}
#line 1700 "dap.tab.c" /* yacc.c:1646 */
break;
case 55:
#line 179 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attrvalue(parsestate,(yyvsp[-2]),(yyvsp[0]),(Object)SCAN_INT16);}
#line 1706 "dap.tab.c" /* yacc.c:1646 */
break;
case 56:
#line 182 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attrvalue(parsestate,null,(yyvsp[0]),(Object)SCAN_UINT16);}
#line 1712 "dap.tab.c" /* yacc.c:1646 */
break;
case 57:
#line 184 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attrvalue(parsestate,(yyvsp[-2]),(yyvsp[0]),(Object)SCAN_UINT16);}
#line 1718 "dap.tab.c" /* yacc.c:1646 */
break;
case 58:
#line 187 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attrvalue(parsestate,null,(yyvsp[0]),(Object)SCAN_INT32);}
#line 1724 "dap.tab.c" /* yacc.c:1646 */
break;
case 59:
#line 189 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attrvalue(parsestate,(yyvsp[-2]),(yyvsp[0]),(Object)SCAN_INT32);}
#line 1730 "dap.tab.c" /* yacc.c:1646 */
break;
case 60:
#line 192 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attrvalue(parsestate,null,(yyvsp[0]),(Object)SCAN_UINT32);}
#line 1736 "dap.tab.c" /* yacc.c:1646 */
break;
case 61:
#line 193 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attrvalue(parsestate,(yyvsp[-2]),(yyvsp[0]),(Object)SCAN_UINT32);}
#line 1742 "dap.tab.c" /* yacc.c:1646 */
break;
case 62:
#line 196 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attrvalue(parsestate,null,(yyvsp[0]),(Object)SCAN_FLOAT32);}
#line 1748 "dap.tab.c" /* yacc.c:1646 */
break;
case 63:
#line 197 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attrvalue(parsestate,(yyvsp[-2]),(yyvsp[0]),(Object)SCAN_FLOAT32);}
#line 1754 "dap.tab.c" /* yacc.c:1646 */
break;
case 64:
#line 200 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attrvalue(parsestate,null,(yyvsp[0]),(Object)SCAN_FLOAT64);}
#line 1760 "dap.tab.c" /* yacc.c:1646 */
break;
case 65:
#line 201 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attrvalue(parsestate,(yyvsp[-2]),(yyvsp[0]),(Object)SCAN_FLOAT64);}
#line 1766 "dap.tab.c" /* yacc.c:1646 */
break;
case 66:
#line 204 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attrvalue(parsestate,null,(yyvsp[0]),(Object)SCAN_STRING);}
#line 1772 "dap.tab.c" /* yacc.c:1646 */
break;
case 67:
#line 205 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attrvalue(parsestate,(yyvsp[-2]),(yyvsp[0]),(Object)SCAN_STRING);}
#line 1778 "dap.tab.c" /* yacc.c:1646 */
break;
case 68:
#line 209 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attrvalue(parsestate,null,(yyvsp[0]),(Object)SCAN_URL);}
#line 1784 "dap.tab.c" /* yacc.c:1646 */
break;
case 69:
#line 210 "dap.y" /* yacc.c:1646 */
{(yyval)=dap_attrvalue(parsestate,(yyvsp[-2]),(yyvsp[0]),(Object)SCAN_URL);}
#line 1790 "dap.tab.c" /* yacc.c:1646 */
break;
case 70:
#line 214 "dap.y" /* yacc.c:1646 */
{(yyval)=(yyvsp[0]);}
#line 1796 "dap.tab.c" /* yacc.c:1646 */
break;
case 71:
#line 218 "dap.y" /* yacc.c:1646 */
{(yyval)=(yyvsp[0]);}
#line 1802 "dap.tab.c" /* yacc.c:1646 */
break;
case 72:
#line 219 "dap.y" /* yacc.c:1646 */
{(yyval)=(yyvsp[0]);}
#line 1808 "dap.tab.c" /* yacc.c:1646 */
break;
case 73:
#line 230 "dap.y" /* yacc.c:1646 */
{(yyval)=(yyvsp[-1]); (yyval)=(yyvsp[0]); (yyval)=null;}
#line 1814 "dap.tab.c" /* yacc.c:1646 */
break;
case 74:
#line 235 "dap.y" /* yacc.c:1646 */
{dap_errorbody(parsestate,(yyvsp[-5]),(yyvsp[-4]),(yyvsp[-3]),(yyvsp[-2]));}
#line 1820 "dap.tab.c" /* yacc.c:1646 */
break;
case 75:
#line 238 "dap.y" /* yacc.c:1646 */
{(yyval)=null;}
#line 1826 "dap.tab.c" /* yacc.c:1646 */
break;
case 76:
#line 238 "dap.y" /* yacc.c:1646 */
{(yyval)=(yyvsp[-1]);}
#line 1832 "dap.tab.c" /* yacc.c:1646 */
break;
case 77:
#line 239 "dap.y" /* yacc.c:1646 */
{(yyval)=null;}
#line 1838 "dap.tab.c" /* yacc.c:1646 */
break;
case 78:
#line 239 "dap.y" /* yacc.c:1646 */
{(yyval)=(yyvsp[-1]);}
#line 1844 "dap.tab.c" /* yacc.c:1646 */
break;
case 79:
#line 240 "dap.y" /* yacc.c:1646 */
{(yyval)=null;}
#line 1850 "dap.tab.c" /* yacc.c:1646 */
break;
case 80:
#line 240 "dap.y" /* yacc.c:1646 */
{(yyval)=(yyvsp[-1]);}
#line 1856 "dap.tab.c" /* yacc.c:1646 */
break;
case 81:
#line 241 "dap.y" /* yacc.c:1646 */
{(yyval)=null;}
#line 1862 "dap.tab.c" /* yacc.c:1646 */
break;
case 82:
#line 241 "dap.y" /* yacc.c:1646 */
{(yyval)=(yyvsp[-1]);}
#line 1868 "dap.tab.c" /* yacc.c:1646 */
break;
case 83:
#line 247 "dap.y" /* yacc.c:1646 */
{(yyval)=dapdecode(parsestate->lexstate,(yyvsp[0]));}
#line 1874 "dap.tab.c" /* yacc.c:1646 */
break;
case 84:
#line 248 "dap.y" /* yacc.c:1646 */
{(yyval)=strdup("alias");}
#line 1880 "dap.tab.c" /* yacc.c:1646 */
break;
case 85:
#line 249 "dap.y" /* yacc.c:1646 */
{(yyval)=strdup("array");}
#line 1886 "dap.tab.c" /* yacc.c:1646 */
break;
case 86:
#line 250 "dap.y" /* yacc.c:1646 */
{(yyval)=strdup("attributes");}
#line 1892 "dap.tab.c" /* yacc.c:1646 */
break;
case 87:
#line 251 "dap.y" /* yacc.c:1646 */
{(yyval)=strdup("byte");}
#line 1898 "dap.tab.c" /* yacc.c:1646 */
break;
case 88:
#line 252 "dap.y" /* yacc.c:1646 */
{(yyval)=strdup("dataset");}
#line 1904 "dap.tab.c" /* yacc.c:1646 */
break;
case 89:
#line 253 "dap.y" /* yacc.c:1646 */
{(yyval)=strdup("data");}
#line 1910 "dap.tab.c" /* yacc.c:1646 */
break;
case 90:
#line 254 "dap.y" /* yacc.c:1646 */
{(yyval)=strdup("error");}
#line 1916 "dap.tab.c" /* yacc.c:1646 */
break;
case 91:
#line 255 "dap.y" /* yacc.c:1646 */
{(yyval)=strdup("float32");}
#line 1922 "dap.tab.c" /* yacc.c:1646 */
break;
case 92:
#line 256 "dap.y" /* yacc.c:1646 */
{(yyval)=strdup("float64");}
#line 1928 "dap.tab.c" /* yacc.c:1646 */
break;
case 93:
#line 257 "dap.y" /* yacc.c:1646 */
{(yyval)=strdup("grid");}
#line 1934 "dap.tab.c" /* yacc.c:1646 */
break;
case 94:
#line 258 "dap.y" /* yacc.c:1646 */
{(yyval)=strdup("int16");}
#line 1940 "dap.tab.c" /* yacc.c:1646 */
break;
case 95:
#line 259 "dap.y" /* yacc.c:1646 */
{(yyval)=strdup("int32");}
#line 1946 "dap.tab.c" /* yacc.c:1646 */
break;
case 96:
#line 260 "dap.y" /* yacc.c:1646 */
{(yyval)=strdup("maps");}
#line 1952 "dap.tab.c" /* yacc.c:1646 */
break;
case 97:
#line 261 "dap.y" /* yacc.c:1646 */
{(yyval)=strdup("sequence");}
#line 1958 "dap.tab.c" /* yacc.c:1646 */
break;
case 98:
#line 262 "dap.y" /* yacc.c:1646 */
{(yyval)=strdup("string");}
#line 1964 "dap.tab.c" /* yacc.c:1646 */
break;
case 99:
#line 263 "dap.y" /* yacc.c:1646 */
{(yyval)=strdup("structure");}
#line 1970 "dap.tab.c" /* yacc.c:1646 */
break;
case 100:
#line 264 "dap.y" /* yacc.c:1646 */
{(yyval)=strdup("uint16");}
#line 1976 "dap.tab.c" /* yacc.c:1646 */
break;
case 101:
#line 265 "dap.y" /* yacc.c:1646 */
{(yyval)=strdup("uint32");}
#line 1982 "dap.tab.c" /* yacc.c:1646 */
break;
case 102:
#line 266 "dap.y" /* yacc.c:1646 */
{(yyval)=strdup("url");}
#line 1988 "dap.tab.c" /* yacc.c:1646 */
break;
case 103:
#line 267 "dap.y" /* yacc.c:1646 */
{(yyval)=strdup("code");}
#line 1994 "dap.tab.c" /* yacc.c:1646 */
break;
case 104:
#line 268 "dap.y" /* yacc.c:1646 */
{(yyval)=strdup("message");}
#line 2000 "dap.tab.c" /* yacc.c:1646 */
break;
case 105:
#line 269 "dap.y" /* yacc.c:1646 */
{(yyval)=strdup("program");}
#line 2006 "dap.tab.c" /* yacc.c:1646 */
break;
case 106:
#line 270 "dap.y" /* yacc.c:1646 */
{(yyval)=strdup("program_type");}
#line 2012 "dap.tab.c" /* yacc.c:1646 */
break;
#line 2016 "dap.tab.c" /* yacc.c:1646 */
default: break;
}
/* User semantic actions sometimes alter yychar, and that requires
that yytoken be updated with the new translation. We take the
approach of translating immediately before every use of yytoken.
One alternative is translating here after every semantic action,
but that translation would be missed if the semantic action invokes
YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or
if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an
incorrect destructor might then be invoked immediately. In the
case of YYERROR or YYBACKUP, subsequent parser actions might lead
to an incorrect destructor call or verbose syntax error message
before the lookahead is translated. */
YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc);
YYPOPSTACK (yylen);
yylen = 0;
YY_STACK_PRINT (yyss, yyssp);
*++yyvsp = yyval;
/* Now 'shift' the result of the reduction. Determine what state
that goes to, based on the state we popped back to and the rule
number reduced by. */
yyn = yyr1[yyn];
yystate = yypgoto[yyn - YYNTOKENS] + *yyssp;
if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp)
yystate = yytable[yystate];
else
yystate = yydefgoto[yyn - YYNTOKENS];
goto yynewstate;
/*--------------------------------------.
| yyerrlab -- here on detecting error. |
`--------------------------------------*/
yyerrlab:
/* Make sure we have latest lookahead translation. See comments at
user semantic actions for why this is necessary. */
yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar);
/* If not already recovering from an error, report this error. */
if (!yyerrstatus)
{
++yynerrs;
#if ! YYERROR_VERBOSE
yyerror (parsestate, YY_("syntax error"));
#else
# define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \
yyssp, yytoken)
{
char const *yymsgp = YY_("syntax error");
int yysyntax_error_status;
yysyntax_error_status = YYSYNTAX_ERROR;
if (yysyntax_error_status == 0)
yymsgp = yymsg;
else if (yysyntax_error_status == 1)
{
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc);
if (!yymsg)
{
yymsg = yymsgbuf;
yymsg_alloc = sizeof yymsgbuf;
yysyntax_error_status = 2;
}
else
{
yysyntax_error_status = YYSYNTAX_ERROR;
yymsgp = yymsg;
}
}
yyerror (parsestate, yymsgp);
if (yysyntax_error_status == 2)
goto yyexhaustedlab;
}
# undef YYSYNTAX_ERROR
#endif
}
if (yyerrstatus == 3)
{
/* If just tried and failed to reuse lookahead token after an
error, discard it. */
if (yychar <= YYEOF)
{
/* Return failure if at end of input. */
if (yychar == YYEOF)
YYABORT;
}
else
{
yydestruct ("Error: discarding",
yytoken, &yylval, parsestate);
yychar = YYEMPTY;
}
}
/* Else will try to reuse lookahead token after shifting the error
token. */
goto yyerrlab1;
/*---------------------------------------------------.
| yyerrorlab -- error raised explicitly by YYERROR. |
`---------------------------------------------------*/
yyerrorlab:
/* Pacify compilers like GCC when the user code never invokes
YYERROR and the label yyerrorlab therefore never appears in user
code. */
if (/*CONSTCOND*/ 0)
goto yyerrorlab;
/* Do not reclaim the symbols of the rule whose action triggered
this YYERROR. */
YYPOPSTACK (yylen);
yylen = 0;
YY_STACK_PRINT (yyss, yyssp);
yystate = *yyssp;
goto yyerrlab1;
/*-------------------------------------------------------------.
| yyerrlab1 -- common code for both syntax error and YYERROR. |
`-------------------------------------------------------------*/
yyerrlab1:
yyerrstatus = 3; /* Each real token shifted decrements this. */
for (;;)
{
yyn = yypact[yystate];
if (!yypact_value_is_default (yyn))
{
yyn += YYTERROR;
if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
{
yyn = yytable[yyn];
if (0 < yyn)
break;
}
}
/* Pop the current state because it cannot handle the error token. */
if (yyssp == yyss)
YYABORT;
yydestruct ("Error: popping",
yystos[yystate], yyvsp, parsestate);
YYPOPSTACK (1);
yystate = *yyssp;
YY_STACK_PRINT (yyss, yyssp);
}
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
*++yyvsp = yylval;
YY_IGNORE_MAYBE_UNINITIALIZED_END
/* Shift the error token. */
YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp);
yystate = yyn;
goto yynewstate;
/*-------------------------------------.
| yyacceptlab -- YYACCEPT comes here. |
`-------------------------------------*/
yyacceptlab:
yyresult = 0;
goto yyreturn;
/*-----------------------------------.
| yyabortlab -- YYABORT comes here. |
`-----------------------------------*/
yyabortlab:
yyresult = 1;
goto yyreturn;
#if !defined yyoverflow || YYERROR_VERBOSE
/*-------------------------------------------------.
| yyexhaustedlab -- memory exhaustion comes here. |
`-------------------------------------------------*/
yyexhaustedlab:
yyerror (parsestate, YY_("memory exhausted"));
yyresult = 2;
/* Fall through. */
#endif
yyreturn:
if (yychar != YYEMPTY)
{
/* Make sure we have latest lookahead translation. See comments at
user semantic actions for why this is necessary. */
yytoken = YYTRANSLATE (yychar);
yydestruct ("Cleanup: discarding lookahead",
yytoken, &yylval, parsestate);
}
/* Do not reclaim the symbols of the rule whose action triggered
this YYABORT or YYACCEPT. */
YYPOPSTACK (yylen);
YY_STACK_PRINT (yyss, yyssp);
while (yyssp != yyss)
{
yydestruct ("Cleanup: popping",
yystos[*yyssp], yyvsp, parsestate);
YYPOPSTACK (1);
}
#ifndef yyoverflow
if (yyss != yyssa)
YYSTACK_FREE (yyss);
#endif
#if YYERROR_VERBOSE
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
#endif
return yyresult;
}
#line 273 "dap.y" /* yacc.c:1906 */
|
655343.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "pager.h"
/*
* The following macro places double quotes around the expansion of
* a macro.
*/
#define QUOTE_VALUE(s) #s
#define QUOTE_MACRO(s) QUOTE_VALUE(s)
/*
* If no default pager was specified on the compile either set the
* default to the NULL string (no external pager available) or
* substitute the pager appropriate to the operating system being used.
*/
#ifdef PAGER
#define PAGER_CMD QUOTE_MACRO(PAGER)
#else
#define PAGER_CMD "more"
#endif
typedef struct { /* Send pager characteristics between functions */
int (*queryfn)(void); /* Internal pager query function */
Pagetype type; /* Required pager type */
} Ptype;
static void do_page(Pager *page, Ptype *ptype);
static int p_getline(char *reply, int nmax, FILE *fd);
static int p_query(void);
static int int_pager(Pager *page, Ptype *ptype);
static int ext_pager(Pager *page);
/*.......................................................................
* Initialize a new text pager and return a dynamically allocated
* descriptor to be used with calls to the pager method functions.
* Text lines supplied via the page_file() and pprintf() method
* functions will be written to a temporary file until end_Pager() is
* called. At that point the temporary file will be presented to the
* pager and then deleted. In principle any number of pagers can be
* in use at once (until memory or file space runs out).
*
* Input:
* Output:
* return Pager * The new pager descriptor, or NULL on error.
*/
Pager *new_Pager(void)
{
Pager *page=NULL; /* The pointer to the pager descriptor to be returned */
/*
* Allocate a new pager descriptor.
*/
page = (Pager *) malloc(sizeof(Pager));
if(page==NULL) {
fprintf(stderr, "new_Pager: Insufficient memory to initialize pager\n");
return page;
};
/*
* Initialize pointers to NULL for the sake of del_Pager().
*/
page->fd = 0;
page->line_no = 0;
page->headlen = -1;
/*
* Open a temporary file to compile the text in.
*/
page->fd = fopen(tmpnam(page->fname), "w");
if(page->fd==NULL) {
fprintf(stderr, "new_Pager: Unable to open scratch file\n");
return del_Pager(page);
};
/*
* Return the initialized container.
*/
return page;
}
/*.......................................................................
* If the given Pager descriptor contains a valid pointer to a scratch
* file, close the file, have its contents paged and then delete the file.
* Finally release all memory allocated in the descriptor.
*
* Input:
* page Pager * A pager descriptor returned by new_Pager().
* dopage int If false, don't page the scratch file.
* queryfn int (*)(void) Optional pointer to a user query function.
* This will be used if type==PAGE_INT or no
* external pager is available to prompt the
* user at the end of each page. Send NULL to
* select the default function. This function
* should return one of the following:
* 0 - Display next page.
* 1 - Quit pager.
* 2 - Switch to external pager if available.
* type Pagetype The type of paging wanted.
* PAGE_INT - Use internal pager.
* PAGE_EXT - Use external pager if defined.
* Otherwise use internal pager.
* PAGE_OFF - No pager - simply echo the text
* to stdout.
* Output:
* return Pager * Always NULL. Use like:
* page = end_Pager(page,1,NULL,PAGE_EXT,-1);
*/
Pager *end_Pager(Pager *page, int dopage, int (*queryfn)(void), Pagetype type)
{
Ptype ptype; /* Used to send pager characteristics between functions */
/*
* No container?
*/
if(page==NULL)
return page;
/*
* Collect pager characteristics into container.
*/
ptype.type = type;
ptype.queryfn = queryfn ? queryfn : p_query;
/*
* Is there a scratch file to be paged?
*/
if(page->fd==NULL) {
fprintf(stderr, "end_Pager: No scratch file to page.\n");
} else {
/*
* Close the file, have it paged if it contains anything and delete it.
*/
if(fclose(page->fd)==EOF) {
if(dopage)
fprintf(stderr, "end_Pager: Error closing scratch file\n");
} else if(dopage && page->line_no>0) {
do_page(page, &ptype);
};
/*
* del_Pager() will try to close the file and delete it again if fd!=NULL.
*/
page->fd = NULL;
/*
* Delete the scratch file.
*/
if(remove(page->fname)) {
fprintf(stderr, "end_Pager: Error deleting scratch file: %s\n",
page->fname);
};
};
/*
* Delete the container.
*/
return del_Pager(page);
}
/*.......................................................................
* Delete the pager scratch file and pager descriptor.
*
* Input:
* page Pager * The descriptor of the pager.
* Output:
* return Pager * Allways NULL. Use like: page=del_Pager(page);
*/
Pager *del_Pager(Pager *page)
{
/*
* Container already deleted?
*/
if(page==NULL)
return page;
/*
* Is there a scratch file to be deleted?
*/
if(page->fd) {
/*
* Close the file - ignore errors since the state of the contents no
* longer concern us.
*/
fclose(page->fd);
/*
* Delete it.
*/
if(remove(page->fname)) {
fprintf(stderr, "del_Pager: Error deleting scratch file: %s\n",
page->fname);
};
};
/*
* Delete the container.
*/
free(page);
return NULL;
}
/*.......................................................................
* Private function for the use of end_Pager(). This function takes
* the already closed scratch file named in page->fname[] and has it
* paged.
*
* Input:
* page Pager * The descriptor of the pager.
* ptype Ptype * Pager characteristics.
*/
static void do_page(Pager *page, Ptype *ptype)
{
/*
* Run the internal pager if reuested, or if the external pager returns
* with an error.
*/
if(ptype->type!=PAGE_EXT || (ptype->type==PAGE_EXT && ext_pager(page)))
int_pager(page, ptype);
return;
}
/*.......................................................................
* Run the internal pager on the closed scratch file named in page->fname.
*
* Input:
* page Pager * The pager descriptor.
* ptype Ptype * Pager characteristics.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int int_pager(Pager *page, Ptype *ptype)
{
FILE *scrfd; /* Pointer to open scratch file */
int reply=0; /* Reply from user query function */
char *cptr; /* Pointer to reply from getenv() */
int nlines=24; /* The number of lines per page */
int ncolumns=80; /* The width of the page */
int first=1; /* True only for first page */
/*
* Open the scratch file for read.
*/
scrfd = fopen(page->fname, "r");
if(scrfd==NULL) {
fprintf(stderr, "int_pager: Error opening scratch file\n");
return 1;
};
/*
* See if the environment has recorded the number of lines available in
* the LINES environment variable. (This is normally the case on
* SYSV machines).
*/
cptr = getenv("LINES");
if(cptr)
nlines = atoi(cptr);
/*
* We require at least 3 lines - two for the query and prompt and one
* for a single line of text.
*/
if(nlines < 3)
nlines = 3;
/*
* See if the environment has recorded the number of columns available in
* the COLUMNS environment variable. (This is normally the case on
* SYSV machines).
*/
cptr = getenv("COLUMNS");
if(cptr)
ncolumns = atoi(cptr);
/*
* Non-sensical value?
*/
if(ncolumns < 2)
ncolumns = 80;
/*
* Write pages of 'nlines-2' lines, and prompt at the end of each.
*/
do {
int lnum=0; /* Line number within current page */
/*
* On the first page, advance the line count to within headlen of the
* end of the page so that the pager prompt will be presented after
* just headlen lines.
*/
if(first && page->headlen>=0 && page->headlen <= nlines-2) {
first = 0;
lnum = nlines - 2 - page->headlen;
};
/*
* Print up to nlines-2 lines.
*/
for(; lnum<nlines-2; lnum++) {
/*
* Read the next line from the scratch file and echo it to stdout.
*/
if(p_getline(page->buffer, PAGE_WIDTH, scrfd))
break;
/*
* Assume that the screen is 'ncolumns' characters across and truncate the
* output line if it will not fit in this space.
*/
fprintf(stdout, "%-.*s\n", ncolumns-1, page->buffer);
};
} while(!feof(scrfd) && !ferror(scrfd) &&
(ptype->type==PAGE_OFF || (reply=ptype->queryfn())==0));
/*
* Close the scratch file.
*/
fclose(scrfd);
/*
* Run external pager?
*/
return reply==2 ? ext_pager(page) : 0;
}
/*.......................................................................
* Run the external pager on the closed scratch file named in page->fname.
*
* Input:
* page Pager * The pager descriptor.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int ext_pager(Pager *page)
{
char *command; /* The pager command. */
/*
* See if the user has set the PAGER environment variable.
*/
command = getenv("PAGER");
/*
* Skip white-space and check for the empty string?
*/
if(command) {
while(isspace((int)*command))
command++;
if(*command == '\0')
command = NULL;
};
/*
* No valid PAGER variable? Then substitute the default pager if there is one.
*/
if(command==NULL)
command = PAGER_CMD;
/*
* Skip white-space and check for the empty string?
*/
if(command) {
while(isspace((int)*command))
command++;
if(*command == '\0')
command = NULL;
};
/*
* If an external pager has been selected, compose a shell command to have
* the scratch file paged, then have it executed.
*/
if(command) {
/*
* Is there insufficient room in page->buffer to compose the full
* command in?
*/
if(strlen(command) + 1 + strlen(page->fname) + 1 > PAGE_WIDTH) {
fprintf(stderr, "Pager command too long for buffer.\n");
return 1;
} else {
/*
* Compose the full pager command.
*/
sprintf(page->buffer, "%s %s", command, page->fname);
/*
* Have it executed.
*/
system(page->buffer);
};
/*
* External pager requested, but non available?
*/
} else {
return 1;
};
return 0;
}
/*.......................................................................
* Take either the pointer to an open file, or the name of a file to
* read from. Read and discard the first nskip lines, then prepend the
* supplied prefix to each line of the remaining lines and echo them
* to into the pager scratch file.
*
* Input:
* page Pager * A pager descriptor from new_Pager().
* name char * The name of the file to page, or NULL if the fd
* argument is to be used istead.
* fd FILE * If name==NULL, then this must be a non-NULL
* pointer to a file opened for reading. Otherwise
* send NULL.
* nskip int The number of lines to skip in the input file -
* send 0 if non are to be skipped.
* prefix char * The string to prepend to each line in the scratch
* file. Send "" or NULL if not required.
* Output:
* return int 0 - OK.
* 1 - Error (don't forget to call del_Pager() after
* this happens).
*/
int page_file(Pager *page, char *name, FILE *fd, int nskip, char *prefix)
{
int waserr=0; /* Error status */
/*
* Check arguments.
*/
if(page==NULL) {
fprintf(stderr, "page_file: NULL Pager descriptor received.\n");
return 1;
};
/*
* At least one file specification must have been provided.
*/
if(name==NULL && fd==NULL) {
fprintf(stderr, "page_file: No file specification provided.\n");
return 1;
};
/*
* Previous error writing the scratch file?
*/
if(ferror(page->fd))
return 1;
/*
* Open the named file for read if given.
*/
if(name) {
fd = fopen(name, "r");
if(fd==NULL) {
fprintf(stderr, "page_file: Error opening file: %s\n", name);
return 1;
};
};
/*
* Skip the first nskip lines of the input file.
*/
if(nskip > 0) {
int nlines;
for(nlines=0; nlines<nskip; nlines++) {
if(p_getline(page->buffer, PAGE_WIDTH, fd))
break;
};
};
/*
* If there are any remaining lines in the input file, echo them to
* the scratch file.
*/
while(!waserr && !feof(fd) && !ferror(fd) && p_getline(page->buffer, PAGE_WIDTH, fd)==0) {
waserr = pprintf(page, "%s%s\n", prefix ? prefix : "", page->buffer) < 0;
};
/*
* Error reading file?
*/
if(ferror(fd) && !feof(fd)) {
fprintf(stderr, "page_file: Error reading file.\n");
waserr = 1;
};
/*
* Close the file if it was opened in this function.
*/
if(name)
fclose(fd);
return waserr;
}
/*.......................................................................
* Write text to the pager scratch file.
*
* Input:
* page Pager * A pager descriptor from new_Pager().
* format char * A printf() style format string. Newline
* characters will not be inserted for you. For
* the purposes of line counting, it will be assumed
* that all newline ('\n') characters will be in the
* format string.
* ... Variable argument list matching format items in
* 'format'.
* Output:
* return int The number of characters printed, or -ve on error.
*/
int pprintf(Pager *page, const char *format, ...)
{
va_list args; /* Variable argument list */
char *cptr; /* Pointer into format[] */
int iret=0; /* Return value */
/*
* Check arguments.
*/
if(page==NULL) {
fprintf(stderr, "pprintf: NULL Pager descriptor received\n");
return -1;
};
/*
* Nothing to write to the file?
*/
if(format==NULL)
return iret;
/*
* File no longer valid?
*/
if(ferror(page->fd))
return -1;
/*
* Count newline characters in the format string.
*/
for(cptr=(char *)format; *cptr!='\0'; cptr++)
if(*cptr=='\n') page->line_no++;
/*
* Write the text line to the scratch file.
*/
va_start(args, format);
iret = vfprintf(page->fd, format, args);
va_end(args);
/*
* Error writing file?
*/
if(iret < 0)
fprintf(stderr, "Error writing to pager scratch file: %s\n", page->fname);
return iret;
}
/*.......................................................................
* Read a line of text from a text file pointed to by fd. If any '\n'
* is found in the read string, it is replaced with '\0'. If no '\n'
* is found then the line has clearly been truncated, and all
* characters up to and including the next '\n' or EOF are consumed
* such that the next read will start at the start of a new line. The
* text read is left in page->buffer[].
*
* Input/Output:
* reply char * A buffer for at least nmax characters. This will
* contain the line that was read except after an error.
* Input:
* nmax int The number of elements in reply[].
* fd FILE * The pointer to a file opened for read.
* Output:
* return int 0 - OK.
* 1 - Error.
*/
static int p_getline(char *reply, int nmax, FILE *fd)
{
char *cptr; /* Pointer into reply[] */
/*
* Read as much of the next line as will fit in the buffer.
*/
if(fgets(reply, nmax, fd) == NULL)
return 1;
/*
* Check for '\n'.
*/
cptr = strchr(reply, '\n');
/*
* If no '\n' was found, then the line has been truncated. Read to the
* start of the next line so that the next fgets() starts at the right
* place.
*/
if(cptr==NULL) {
int c;
while((c=getc(fd)) != '\n' && c != EOF);
}
/*
* Remove trailing '\n' if present.
*/
else {
*cptr = '\0';
};
return 0;
}
/*.......................................................................
* Default user query function to be used if the user doesn't supply one.
*
* Output:
* return int 0 - Continue paging.
* 1 - Stop paging.
*/
static int p_query(void)
{
enum {MAXREPLY=2};
char reply[MAXREPLY+1]; /* Buffer to receive reply string */
/*
* Prompt the user.
*/
fprintf(stdout, "Press return for the next page, Q to quit, or P for external pager.\n#");
/*
* Read user's selection.
*/
if(p_getline(reply, MAXREPLY, stdin)==0) {
char *cptr=reply;
/*
* Skip white space.
*/
while(isspace((int)*cptr))
cptr++;
/*
* Nothing typed?
*/
if(*cptr=='\0')
return 0; /* Keep paging */
/*
* External pager requested?
*/
if(tolower(*cptr)=='p')
return 2;
};
return 1; /* Stop paging */
}
/*.......................................................................
* With the internal pager this sets a premature end for the first
* displayed page, thus giving the opportunity via the prompt to
* switch to an external pager after displaying only a minimal header.
*
* Input:
* page Pager * The pager descriptor.
*/
void page_mark(Pager *page)
{
page->headlen = page->line_no;
}
|
672405.c | /*-------------------------------------------------------------------------
*
* polar_parallel_bgwriter.c
* Parallel background writer process manager.
*
* Copyright (c) 2019, Alibaba Group Holding Limited
* 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.*
*
* IDENTIFICATION
* src/backend/postmaster/polar_parallel_bgwriter.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <unistd.h>
#include "miscadmin.h"
#include "pgstat.h"
#include "access/xlog.h"
#include "libpq/pqsignal.h"
#include "postmaster/bgworker.h"
#include "postmaster/bgwriter.h"
#include "postmaster/polar_parallel_bgwriter.h"
#include "storage/buf_internals.h"
#include "storage/condition_variable.h"
#include "storage/ipc.h"
#include "storage/latch.h"
#include "storage/polar_bufmgr.h"
#include "storage/polar_fd.h"
#include "storage/polar_flushlist.h"
#include "storage/procsignal.h"
#include "utils/guc.h"
#include "utils/memutils.h"
#include "utils/timestamp.h"
#define HIBERNATE_FACTOR 50
#define ILLEGAL_GENERATION 0
#define ILLEGAL_SLOT -1
static int check_running_bgwriter_workers(void);
static bool parallel_sync_buffer(WritebackContext *wb_context);
static int find_one_unused_handle_slot(void);
static int find_one_used_handle_slot(void);
static void reset_bgwriter_handle(ParallelBgwriterHandle *handle);
static bool handle_is_used(ParallelBgwriterHandle *handle);
static bool handle_is_unused(ParallelBgwriterHandle *handle);
static void worker_sighup_handler(SIGNAL_ARGS);
static void worker_sigterm_handler(SIGNAL_ARGS);
static void worker_sigusr1_handler(SIGNAL_ARGS);
static void worker_quit_handler(SIGNAL_ARGS);
/* Flags set by signal handlers */
static volatile sig_atomic_t got_sighup = false;
static volatile sig_atomic_t shutdown_requested = false;
ParallelBgwriterInfo *polar_parallel_bgwriter_info = NULL;
/*
* Initialize parallel bgwriter manager.
*
* This is called once during shared-memory initialization (either in the
* postmaster, or in a standalone backend).
*/
void
polar_init_parallel_bgwriter(void)
{
bool found;
int i;
if (!polar_parallel_bgwriter_enabled())
return;
polar_parallel_bgwriter_info = (ParallelBgwriterInfo *) ShmemInitStruct(
"Parallel bgwriter info",
sizeof(ParallelBgwriterInfo),
&found);
if (!found)
{
/* Init background worker handle */
for (i = 0; i < MAX_NUM_OF_PARALLEL_BGWRITER; i++)
reset_bgwriter_handle(&polar_parallel_bgwriter_info->handles[i]);
pg_atomic_init_u32(&polar_parallel_bgwriter_info->current_workers, 0);
}
}
Size
polar_parallel_bgwriter_shmem_size(void)
{
Size size = 0;
if (!polar_parallel_bgwriter_enabled())
return size;
size = add_size(size, sizeof(ParallelBgwriterInfo));
return size;
}
/* Start parallel background writer workers. */
void
polar_launch_parallel_bgwriter_workers(void)
{
uint32 current_workers;
int running_workers;
int launch_workers = 0;
int guc_workers;
bool update = false;
/*
* Now, only master launch parallel background writers. If we want replica
* or standby to launch them, please DO NOT forget to change the worker's
* bgw_start_time.
*/
if (!polar_parallel_bgwriter_enabled() || polar_in_replica_mode() ||
polar_is_standby())
return;
current_workers = CURRENT_PARALLEL_WORKERS;
running_workers = check_running_bgwriter_workers();
guc_workers = polar_parallel_bgwriter_workers;
Assert(running_workers <= current_workers);
/* polar_parallel_bgwriter_workers is greater than #current_workers */
if (current_workers < guc_workers)
{
launch_workers = guc_workers - current_workers;
update = true;
}
else if (current_workers > POLAR_MAX_BGWRITER_WORKERS)
{
launch_workers = POLAR_MAX_BGWRITER_WORKERS - current_workers;
elog(LOG,
"Current parallel background workers %d is greater than the max %d, try to stop %d worker.",
current_workers, POLAR_MAX_BGWRITER_WORKERS, abs(launch_workers));
}
/* Some workers are stopped, it is time to start new */
else if (current_workers > running_workers)
launch_workers = current_workers - running_workers;
if (launch_workers > 0)
polar_register_parallel_bgwriter_workers(launch_workers, update);
else if (launch_workers < 0)
polar_shutdown_parallel_bgwriter_workers(abs(launch_workers));
}
static int
check_running_bgwriter_workers(void)
{
int i;
ParallelBgwriterHandle *handle;
BgwHandleStatus status;
pid_t pid;
int workers = 0;
for(i = 0; i < MAX_NUM_OF_PARALLEL_BGWRITER; i++)
{
handle = &polar_parallel_bgwriter_info->handles[i];
if (handle_is_unused(handle))
continue;
status = GetBackgroundWorkerPid((BackgroundWorkerHandle *)handle, &pid);
/* Already stopped */
if (status == BGWH_STOPPED)
reset_bgwriter_handle(handle);
else
workers++;
}
return workers;
}
/* Register #workers background writer workers. */
void
polar_register_parallel_bgwriter_workers(int workers, bool update_workers)
{
BackgroundWorker worker;
uint32 current_workers;
int slot;
int i;
Assert(polar_parallel_bgwriter_enabled());
memset(&worker, 0, sizeof(BackgroundWorker));
worker.bgw_flags = BGWORKER_SHMEM_ACCESS;
worker.bgw_start_time = BgWorkerStart_RecoveryFinished;
worker.bgw_restart_time = BGW_NEVER_RESTART;
sprintf(worker.bgw_library_name, "postgres");
sprintf(worker.bgw_function_name, "polar_parallel_bgwriter_worker_main");
snprintf(worker.bgw_name, BGW_MAXLEN, "polar parallel bgwriter");
snprintf(worker.bgw_type, BGW_MAXLEN, "polar parallel bgwriter");
worker.bgw_notify_pid = MyProcPid;
current_workers = CURRENT_PARALLEL_WORKERS;
/* Start workers */
for (i = 0; i < workers; i++)
{
BackgroundWorkerHandle *worker_handle;
/* Check the total number of parallel background workers. */
if (current_workers >= POLAR_MAX_BGWRITER_WORKERS)
{
ereport(WARNING,
(errmsg(
"Can not start new parallel background workers, current workers: %d, at most workers %d",
current_workers,
POLAR_MAX_BGWRITER_WORKERS)));
break;
}
/* Find an empty handle slot to register one background writer. */
slot = find_one_unused_handle_slot();
if (slot == -1)
{
ereport(WARNING,
(errmsg(
"Can not find an empty background worker handle slot to register a worker, total number of workers is %d",
current_workers)));
break;
}
if (RegisterDynamicBackgroundWorker(&worker, &worker_handle))
{
polar_set_parallel_bgwriter_handle(worker_handle,
&polar_parallel_bgwriter_info->handles[slot]);
current_workers++;
pfree(worker_handle);
}
else
{
ereport(WARNING,
(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
errmsg("could not register background process"),
errhint("You may need to increase max_worker_processes.")));
continue;
}
if (polar_enable_debug)
ereport(LOG,
(errmsg(
"Register one background writer worker, its handle slot index is %d",
slot)));
}
/* Set current parallel workers */
if (update_workers)
pg_atomic_write_u32(&polar_parallel_bgwriter_info->current_workers, current_workers);
}
/*
* polar_parallel_bgwriter_worker_main - main entry point for the parallel
* bgwriter worker.
*
* Based on BackgroundWriterMain.
*/
void
polar_parallel_bgwriter_worker_main(Datum main_arg)
{
sigjmp_buf local_sigjmp_buf;
MemoryContext bgwriter_context;
bool prev_hibernate;
WritebackContext wb_context;
/*
* Properly accept or ignore signals the postmaster might send us.
*
* bgwriter doesn't participate in ProcSignal signalling, but a SIGUSR1
* handler is still needed for latch wakeups.
*/
pqsignal(SIGHUP, worker_sighup_handler); /* set flag to read config file */
pqsignal(SIGINT, SIG_IGN);
pqsignal(SIGTERM, worker_sigterm_handler); /* shutdown */
pqsignal(SIGQUIT, worker_quit_handler); /* hard crash time */
pqsignal(SIGALRM, SIG_IGN);
pqsignal(SIGPIPE, SIG_IGN);
pqsignal(SIGUSR1, worker_sigusr1_handler);
pqsignal(SIGUSR2, SIG_IGN);
/*
* Reset some signals that are accepted by postmaster but not here
*/
pqsignal(SIGCHLD, SIG_DFL);
pqsignal(SIGTTIN, SIG_DFL);
pqsignal(SIGTTOU, SIG_DFL);
pqsignal(SIGCONT, SIG_DFL);
pqsignal(SIGWINCH, SIG_DFL);
/* We allow SIGQUIT (quickdie) at all times */
sigdelset(&BlockSig, SIGQUIT);
/*
* Create a resource owner to keep track of our resources (currently only
* buffer pins).
*/
CurrentResourceOwner = ResourceOwnerCreate(NULL, "Parallel Background Writer");
/*
* Create a memory context that we will do all our work in. We do this so
* that we can reset the context during error recovery and thereby avoid
* possible memory leaks. Formerly this code just ran in
* TopMemoryContext, but resetting that would be a really bad idea.
*/
bgwriter_context = AllocSetContextCreate(TopMemoryContext,
"Parallel Background Writer",
ALLOCSET_DEFAULT_SIZES);
MemoryContextSwitchTo(bgwriter_context);
WritebackContextInit(&wb_context, &bgwriter_flush_after);
/*
* If an exception is encountered, processing resumes here.
*
* See notes in postgres.c about the design of this coding.
*/
if (sigsetjmp(local_sigjmp_buf, 1) != 0)
{
/* Since not using PG_TRY, must reset error stack by hand */
error_context_stack = NULL;
/* Prevent interrupts while cleaning up */
HOLD_INTERRUPTS();
/* Report the error to the server log */
EmitErrorReport();
/*
* These operations are really just a minimal subset of
* AbortTransaction(). We don't have very many resources to worry
* about in bgwriter, but we do have LWLocks, buffers, and temp files.
*/
LWLockReleaseAll();
ConditionVariableCancelSleep();
AbortBufferIO();
UnlockBuffers();
/* buffer pins are released here: */
ResourceOwnerRelease(CurrentResourceOwner,
RESOURCE_RELEASE_BEFORE_LOCKS,
false, true);
/* we needn't bother with the other ResourceOwnerRelease phases */
AtEOXact_Buffers(false);
AtEOXact_SMgr();
AtEOXact_Files(false);
AtEOXact_HashTables(false);
/*
* Now return to normal top-level context and clear ErrorContext for
* next time.
*/
MemoryContextSwitchTo(bgwriter_context);
FlushErrorState();
/* Flush any leaked data in the top-level context */
MemoryContextResetAndDeleteChildren(bgwriter_context);
/* re-initialize to avoid repeated errors causing problems */
WritebackContextInit(&wb_context, &bgwriter_flush_after);
/* Now we can allow interrupts again */
RESUME_INTERRUPTS();
/*
* Sleep at least 1 second after any error. A write error is likely
* to be repeated, and we don't want to be filling the error logs as
* fast as we can.
*/
pg_usleep(1000000L);
/*
* Close all open files after any error. This is helpful on Windows,
* where holding deleted files open causes various strange errors.
* It's not clear we need it elsewhere, but shouldn't hurt.
*/
smgrcloseall();
/* Report wait end here, when there is no further possibility of wait */
pgstat_report_wait_end();
}
/* We can now handle ereport(ERROR) */
PG_exception_stack = &local_sigjmp_buf;
/*
* Unblock signals (they were blocked when the postmaster forked us)
*/
PG_SETMASK(&UnBlockSig);
/*
* Reset hibernation state after any error.
*/
prev_hibernate = false;
/*
* Loop forever
*/
for (;;)
{
bool can_hibernate;
int rc;
/* Clear any already-pending wakeups */
ResetLatch(MyLatch);
if (got_sighup)
{
got_sighup = false;
ProcessConfigFile(PGC_SIGHUP);
}
if (shutdown_requested)
{
/*
* From here on, elog(ERROR) should end with exit(1), not send
* control back to the sigsetjmp block above
*/
ExitOnAnyError = true;
/* Normal exit from the bgwriter is here */
proc_exit(0); /* done */
}
/*
* Do one cycle of dirty-buffer writing.
*/
can_hibernate = parallel_sync_buffer(&wb_context);
/*
* Send off activity statistics to the stats collector
*/
pgstat_send_bgwriter();
if (FirstCallSinceLastCheckpoint())
{
/*
* After any checkpoint, close all smgr files. This is so we
* won't hang onto smgr references to deleted files indefinitely.
*/
smgrcloseall();
}
/*
* Sleep until we are signaled or BgWriterDelay has elapsed.
*/
rc = WaitLatch(MyLatch,
WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
polar_parallel_bgwriter_delay /* ms */ ,
WAIT_EVENT_BGWRITER_MAIN);
if (rc == WL_TIMEOUT && can_hibernate && prev_hibernate)
rc = WaitLatch(MyLatch,
WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
polar_parallel_bgwriter_delay * HIBERNATE_FACTOR,
WAIT_EVENT_BGWRITER_HIBERNATE);
/*
* Emergency bailout if postmaster has died. This is to avoid the
* necessity for manual cleanup of all postmaster children.
*/
if (rc & WL_POSTMASTER_DEATH)
exit(1);
prev_hibernate = can_hibernate;
}
}
/*
* Parallel background writer only flush buffer from flush list, do not flush
* buffer from copy buffer and do not update the consistent lsn, only the normal
* bgwriter does these.
*/
static bool
parallel_sync_buffer(WritebackContext *wb_context)
{
XLogRecPtr consistent_lsn = InvalidXLogRecPtr;
return polar_buffer_sync(wb_context, &consistent_lsn, false, 0);
}
/* Shut down #workers parallel background workers. */
void
polar_shutdown_parallel_bgwriter_workers(int workers)
{
int used_slot;
int i;
ParallelBgwriterHandle *handle;
Assert(polar_parallel_bgwriter_enabled());
for (i = 0; i < workers; i++)
{
used_slot = find_one_used_handle_slot();
if (used_slot == -1)
{
ereport(WARNING,
(errmsg(
"Can not find a used background worker handle slot to shutdown a worker, total number of workers is %d",
CURRENT_PARALLEL_WORKERS)));
break;
}
handle = &polar_parallel_bgwriter_info->handles[used_slot];
TerminateBackgroundWorker((BackgroundWorkerHandle *) handle);
reset_bgwriter_handle(handle);
pg_atomic_fetch_sub_u32(&polar_parallel_bgwriter_info->current_workers, 1);
if (polar_enable_debug)
{
ereport(DEBUG1,
(errmsg(
"Shut down one background writer worker, its handle slot index is %d",
used_slot)));
}
}
}
/* Check the parallel background writers, if some writers are stopped, start some. */
void
polar_check_parallel_bgwriter_worker(void)
{
static TimestampTz last_check_ts = 0;
TimestampTz timeout = 0;
TimestampTz now;
if (!polar_parallel_bgwriter_enabled() ||
polar_in_replica_mode())
return;
if (last_check_ts == 0)
{
last_check_ts = GetCurrentTimestamp();
return;
}
now = GetCurrentTimestamp();
timeout = TimestampTzPlusMilliseconds(last_check_ts,
polar_parallel_bgwriter_check_interval * 1000L);
if (now >= timeout)
{
polar_launch_parallel_bgwriter_workers();
last_check_ts = now;
}
}
static int
find_one_unused_handle_slot(void)
{
int i;
for (i = 0; i < MAX_NUM_OF_PARALLEL_BGWRITER; i++)
{
if (handle_is_unused(&polar_parallel_bgwriter_info->handles[i]))
return i;
}
/* Return an illegal value. */
return -1;
}
static int
find_one_used_handle_slot(void)
{
int i;
for (i = 0; i < MAX_NUM_OF_PARALLEL_BGWRITER; i++)
{
if (handle_is_used(&polar_parallel_bgwriter_info->handles[i]))
return i;
}
/* Return an illegal value. */
return -1;
}
static bool
handle_is_unused(ParallelBgwriterHandle *handle)
{
bool res = handle->slot == ILLEGAL_SLOT ||
handle->generation == ILLEGAL_GENERATION;
if (res)
{
Assert(handle->slot == ILLEGAL_SLOT);
Assert(handle->generation == ILLEGAL_GENERATION);
}
return res;
}
static bool
handle_is_used(ParallelBgwriterHandle *handle)
{
return handle->slot != ILLEGAL_SLOT &&
handle->generation != ILLEGAL_GENERATION;
}
static void
reset_bgwriter_handle(ParallelBgwriterHandle *handle)
{
handle->slot = ILLEGAL_SLOT;
handle->generation = ILLEGAL_GENERATION;
}
/* Signal handler for SIGTERM */
static void
worker_sigterm_handler(SIGNAL_ARGS)
{
int save_errno = errno;
shutdown_requested = true;
SetLatch(MyLatch);
errno = save_errno;
}
/* Signal handler for SIGHUP */
static void
worker_sighup_handler(SIGNAL_ARGS)
{
int save_errno = errno;
got_sighup = true;
SetLatch(MyLatch);
errno = save_errno;
}
/* SIGUSR1: used for latch wakeups */
static void
worker_sigusr1_handler(SIGNAL_ARGS)
{
int save_errno = errno;
latch_sigusr1_handler();
errno = save_errno;
}
static void
worker_quit_handler(SIGNAL_ARGS)
{
_exit(2);
}
|
432657.c | /*BHEADER**********************************************************************
* (c) 1997 The Regents of the University of California
*
* See the file COPYRIGHT_and_DISCLAIMER for a complete copyright
* notice, contact person, and disclaimer.
*
* $Revision$
*********************************************************************EHEADER*/
/******************************************************************************
*
* Constructors and destructors for stencil structure.
*
*****************************************************************************/
#include "headers.h"
/*--------------------------------------------------------------------------
* hypre_StructStencilCreate
*--------------------------------------------------------------------------*/
hypre_StructStencil *
hypre_StructStencilCreate( int dim,
int size,
hypre_Index *shape )
{
hypre_StructStencil *stencil;
int abs_offset;
int max_offset;
int s, d;
stencil = hypre_TAlloc(hypre_StructStencil, 1);
hypre_StructStencilShape(stencil) = shape;
hypre_StructStencilSize(stencil) = size;
hypre_StructStencilDim(stencil) = dim;
hypre_StructStencilRefCount(stencil) = 1;
/* compute max_offset */
max_offset = 0;
for (s = 0; s < size; s++)
{
for (d = 0; d < 3; d++)
{
abs_offset = hypre_IndexD(shape[s], d);
abs_offset = (abs_offset < 0) ? -abs_offset : abs_offset;
max_offset = hypre_max(abs_offset, max_offset);
}
}
hypre_StructStencilMaxOffset(stencil) = max_offset;
return stencil;
}
/*--------------------------------------------------------------------------
* hypre_StructStencilRef
*--------------------------------------------------------------------------*/
hypre_StructStencil *
hypre_StructStencilRef( hypre_StructStencil *stencil )
{
hypre_StructStencilRefCount(stencil) ++;
return stencil;
}
/*--------------------------------------------------------------------------
* hypre_StructStencilDestroy
*--------------------------------------------------------------------------*/
int
hypre_StructStencilDestroy( hypre_StructStencil *stencil )
{
int ierr = 0;
if (stencil)
{
hypre_StructStencilRefCount(stencil) --;
if (hypre_StructStencilRefCount(stencil) == 0)
{
hypre_TFree(hypre_StructStencilShape(stencil));
hypre_TFree(stencil);
}
}
return ierr;
}
/*--------------------------------------------------------------------------
* hypre_StructStencilElementRank
* Returns the rank of the `stencil_element' in `stencil'.
* If the element is not found, a -1 is returned.
*--------------------------------------------------------------------------*/
int
hypre_StructStencilElementRank( hypre_StructStencil *stencil,
hypre_Index stencil_element )
{
hypre_Index *stencil_shape;
int rank;
int i;
rank = -1;
stencil_shape = hypre_StructStencilShape(stencil);
for (i = 0; i < hypre_StructStencilSize(stencil); i++)
{
if ((hypre_IndexX(stencil_shape[i]) == hypre_IndexX(stencil_element)) &&
(hypre_IndexY(stencil_shape[i]) == hypre_IndexY(stencil_element)) &&
(hypre_IndexZ(stencil_shape[i]) == hypre_IndexZ(stencil_element)) )
{
rank = i;
break;
}
}
return rank;
}
/*--------------------------------------------------------------------------
* hypre_StructStencilSymmetrize:
* Computes a new "symmetrized" stencil.
*
* An integer array called `symm_elements' is also set up. A non-negative
* value of `symm_elements[i]' indicates that the `i'th stencil element
* is a "symmetric element". That is, this stencil element is the
* transpose element of an element that is not a "symmetric element".
*--------------------------------------------------------------------------*/
int
hypre_StructStencilSymmetrize( hypre_StructStencil *stencil,
hypre_StructStencil **symm_stencil_ptr,
int **symm_elements_ptr )
{
hypre_Index *stencil_shape = hypre_StructStencilShape(stencil);
int stencil_size = hypre_StructStencilSize(stencil);
hypre_StructStencil *symm_stencil;
hypre_Index *symm_stencil_shape;
int symm_stencil_size;
int *symm_elements;
int no_symmetric_stencil_element;
int i, j, d;
int ierr = 0;
/*------------------------------------------------------
* Copy stencil elements into `symm_stencil_shape'
*------------------------------------------------------*/
symm_stencil_shape = hypre_CTAlloc(hypre_Index, 2*stencil_size);
for (i = 0; i < stencil_size; i++)
{
hypre_CopyIndex(stencil_shape[i], symm_stencil_shape[i]);
}
/*------------------------------------------------------
* Create symmetric stencil elements and `symm_elements'
*------------------------------------------------------*/
symm_elements = hypre_CTAlloc(int, 2*stencil_size);
for (i = 0; i < 2*stencil_size; i++)
symm_elements[i] = -1;
symm_stencil_size = stencil_size;
for (i = 0; i < stencil_size; i++)
{
if (symm_elements[i] < 0)
{
/* note: start at i to handle "center" element correctly */
no_symmetric_stencil_element = 1;
for (j = i; j < stencil_size; j++)
{
if ( (hypre_IndexX(symm_stencil_shape[j]) ==
-hypre_IndexX(symm_stencil_shape[i]) ) &&
(hypre_IndexY(symm_stencil_shape[j]) ==
-hypre_IndexY(symm_stencil_shape[i]) ) &&
(hypre_IndexZ(symm_stencil_shape[j]) ==
-hypre_IndexZ(symm_stencil_shape[i]) ) )
{
/* only "off-center" elements have symmetric entries */
if (i != j)
symm_elements[j] = i;
no_symmetric_stencil_element = 0;
}
}
if (no_symmetric_stencil_element)
{
/* add symmetric stencil element to `symm_stencil' */
for (d = 0; d < 3; d++)
{
hypre_IndexD(symm_stencil_shape[symm_stencil_size], d) =
-hypre_IndexD(symm_stencil_shape[i], d);
}
symm_elements[symm_stencil_size] = i;
symm_stencil_size++;
}
}
}
symm_stencil = hypre_StructStencilCreate(hypre_StructStencilDim(stencil),
symm_stencil_size,
symm_stencil_shape);
*symm_stencil_ptr = symm_stencil;
*symm_elements_ptr = symm_elements;
return ierr;
}
|
415111.c |
/*
CF3
Copyright (c) 2015 ishiura-lab.
Released under the MIT license.
https://github.com/ishiura-compiler/CF3/MIT-LICENSE.md
*/
#include<stdio.h>
#include<stdint.h>
#include<stdlib.h>
#include"test1.h"
volatile uint8_t x2 = 5U;
int8_t x9 = INT8_MAX;
int32_t t2 = -1063;
static uint16_t x27 = 16945U;
int64_t x30 = 571960473552019477LL;
static int32_t x38 = -1;
static int32_t x39 = -1311;
static int64_t x40 = INT64_MAX;
uint16_t x43 = 1810U;
uint8_t x45 = 57U;
int32_t t11 = 421057772;
uint64_t x51 = UINT64_MAX;
uint64_t x55 = UINT64_MAX;
volatile int32_t t13 = 3;
int32_t x57 = INT32_MIN;
int32_t t14 = 1042366;
int16_t x72 = INT16_MIN;
volatile int32_t t19 = 32559507;
static int16_t x81 = INT16_MAX;
uint16_t x82 = 377U;
static int32_t t20 = 135676212;
uint8_t x87 = 1U;
int32_t t21 = 1;
int32_t x89 = -20041;
static volatile int32_t x92 = -6190;
int32_t t23 = -115150;
volatile int8_t x102 = INT8_MIN;
int64_t x106 = INT64_MIN;
int32_t x108 = INT32_MAX;
int8_t x109 = INT8_MAX;
uint32_t x110 = UINT32_MAX;
int32_t t27 = 507611;
int64_t x115 = -1LL;
volatile int32_t t28 = 439535975;
int16_t x119 = 4654;
int8_t x121 = -26;
int32_t x126 = INT32_MAX;
static int16_t x128 = INT16_MIN;
static int32_t x137 = -1;
uint8_t x139 = UINT8_MAX;
int64_t x141 = INT64_MIN;
uint64_t x142 = 455825LLU;
volatile int16_t x145 = INT16_MAX;
uint64_t x154 = 8710376239252LLU;
volatile int8_t x156 = INT8_MIN;
static int32_t t40 = -102222835;
int16_t x169 = INT16_MAX;
int64_t x171 = INT64_MIN;
int32_t t43 = -5179;
uint8_t x181 = 18U;
static int32_t x182 = INT32_MAX;
uint32_t x187 = 4U;
volatile int64_t x189 = INT64_MAX;
uint64_t x191 = 114857111002LLU;
uint64_t x199 = 175991958866LLU;
volatile uint8_t x201 = 0U;
static volatile int32_t x202 = -1;
static volatile int32_t t50 = -372724372;
volatile int16_t x207 = 154;
static uint16_t x208 = 0U;
uint64_t x210 = 13988431LLU;
int64_t x214 = 407510260082307032LL;
int16_t x218 = 4009;
static volatile int32_t t54 = 966981817;
volatile int32_t t59 = 53890423;
static int32_t t60 = 1560749;
int32_t t61 = 36107651;
int16_t x253 = -1;
int32_t t63 = 0;
int64_t x262 = 0LL;
int16_t x268 = INT16_MIN;
uint32_t x271 = UINT32_MAX;
int32_t x276 = 14;
int16_t x282 = -1;
volatile int16_t x283 = INT16_MAX;
int64_t x284 = 53LL;
static volatile int32_t t70 = 0;
static int16_t x287 = 0;
int32_t t71 = 3595467;
int32_t x289 = 18835;
int16_t x295 = -1;
volatile int16_t x296 = -1;
int8_t x298 = -1;
static int32_t x299 = 2;
volatile int8_t x302 = -47;
static int16_t x304 = INT16_MIN;
volatile int32_t t75 = -451;
int32_t t76 = -3803765;
static int16_t x312 = -53;
int32_t t78 = -70048421;
int64_t x322 = 918503090163048LL;
volatile int32_t x323 = 93241;
int16_t x328 = -994;
int32_t x332 = INT32_MIN;
int32_t x335 = 134862;
int32_t x339 = 1568;
int64_t x352 = 841148258LL;
int16_t x358 = INT16_MIN;
volatile int64_t x360 = -1LL;
uint16_t x364 = 25U;
int32_t t90 = -3;
static int32_t t91 = -5107;
int32_t x374 = -252081677;
int64_t x377 = INT64_MIN;
static int8_t x381 = -1;
uint8_t x382 = 0U;
uint16_t x387 = UINT16_MAX;
int32_t t99 = 165800579;
volatile int64_t x402 = -190100813783232LL;
uint64_t x404 = 2420724636207743LLU;
volatile int32_t t100 = 0;
volatile int32_t x406 = INT32_MIN;
int32_t x407 = -1;
int32_t x408 = INT32_MIN;
int64_t x411 = INT64_MIN;
volatile int32_t t103 = -1;
int32_t t104 = -22459;
volatile uint16_t x423 = 2U;
int16_t x426 = -1;
static int8_t x427 = INT8_MIN;
static int16_t x428 = INT16_MAX;
static volatile int32_t t106 = -64793;
int64_t x430 = INT64_MAX;
volatile int32_t t107 = -10871580;
uint16_t x436 = 9838U;
int32_t t108 = -227;
static uint16_t x438 = UINT16_MAX;
volatile int32_t t109 = -140731319;
int8_t x464 = -1;
volatile int32_t x467 = 154119046;
static int16_t x470 = 173;
int16_t x486 = INT16_MIN;
static int64_t x487 = -1LL;
int32_t t121 = 359757;
int32_t t122 = 0;
int64_t x499 = -1LL;
volatile int32_t t124 = -299;
int16_t x501 = INT16_MAX;
int16_t x507 = INT16_MIN;
int8_t x511 = INT8_MAX;
volatile int32_t t128 = -76;
volatile int16_t x527 = 1654;
uint32_t x531 = UINT32_MAX;
int64_t x540 = -159LL;
static int16_t x541 = -1;
int8_t x547 = 0;
static uint16_t x549 = 2963U;
uint32_t x552 = UINT32_MAX;
static volatile int32_t x560 = 31576;
int32_t t139 = -9;
uint8_t x561 = 2U;
int16_t x564 = -1;
int8_t x568 = INT8_MIN;
int32_t t141 = 24399;
int16_t x570 = INT16_MAX;
int64_t x571 = -61527LL;
int32_t t142 = -8424;
static int16_t x575 = -1;
int16_t x577 = -1;
volatile int32_t t144 = 817594;
volatile int32_t x588 = -1;
int16_t x591 = INT16_MIN;
static volatile int32_t t148 = 1415;
static uint64_t x597 = UINT64_MAX;
uint64_t x602 = 1287498358452LLU;
static volatile int16_t x604 = -1;
uint32_t x611 = UINT32_MAX;
int64_t x614 = INT64_MIN;
int16_t x618 = 3622;
int64_t x625 = -570LL;
volatile uint16_t x627 = UINT16_MAX;
volatile int32_t t156 = 21810;
volatile int8_t x635 = 3;
volatile int64_t x636 = INT64_MIN;
static int32_t t158 = -2948;
int64_t x637 = INT64_MIN;
int32_t t159 = 2834;
uint32_t x645 = UINT32_MAX;
int16_t x649 = 68;
static int32_t x653 = -16092782;
uint8_t x656 = 12U;
uint64_t x657 = UINT64_MAX;
int64_t x659 = INT64_MIN;
int16_t x667 = -1;
int32_t t166 = -1;
uint64_t x674 = 914LLU;
uint32_t x676 = UINT32_MAX;
static int32_t t169 = 1595;
static volatile int8_t x682 = 6;
static int32_t x684 = -1;
static uint64_t x686 = 176598643689LLU;
int32_t t171 = -1;
static int32_t x693 = 770;
int8_t x694 = -1;
volatile int32_t t175 = 185;
volatile int16_t x705 = INT16_MAX;
uint64_t x712 = 233942908LLU;
uint32_t x715 = 613U;
int16_t x716 = 473;
int64_t x722 = INT64_MIN;
volatile int32_t t181 = 23770830;
volatile uint16_t x753 = 1U;
volatile int8_t x763 = INT8_MAX;
static int32_t t191 = 897741;
static uint64_t x779 = 1684LLU;
static volatile uint64_t x781 = 189582087840932LLU;
int64_t x787 = 394483918954537LL;
volatile int32_t x791 = 102992062;
uint8_t x793 = 3U;
uint32_t x794 = 5639083U;
int16_t x798 = -5;
int32_t x799 = INT32_MIN;
uint64_t x800 = 1LLU;
void f0(void) {
int64_t x1 = -1LL;
volatile int16_t x3 = INT16_MIN;
volatile int64_t x4 = -1LL;
volatile int32_t t0 = -33447118;
t0 = ((x1<=x2)<=(x3|x4));
if (t0 != 0) { NG(); } else { ; }
}
void f1(void) {
static int8_t x5 = 2;
int32_t x6 = INT32_MAX;
uint64_t x7 = UINT64_MAX;
static uint32_t x8 = UINT32_MAX;
int32_t t1 = -53;
t1 = ((x5<=x6)<=(x7|x8));
if (t1 != 1) { NG(); } else { ; }
}
void f2(void) {
volatile int8_t x10 = -7;
volatile int8_t x11 = 11;
int8_t x12 = 55;
t2 = ((x9<=x10)<=(x11|x12));
if (t2 != 1) { NG(); } else { ; }
}
void f3(void) {
static uint32_t x13 = 3U;
static volatile int16_t x14 = INT16_MIN;
int64_t x15 = INT64_MIN;
int32_t x16 = -1;
static volatile int32_t t3 = 31250;
t3 = ((x13<=x14)<=(x15|x16));
if (t3 != 0) { NG(); } else { ; }
}
void f4(void) {
volatile int8_t x17 = INT8_MIN;
uint64_t x18 = 458509290509LLU;
static uint64_t x19 = UINT64_MAX;
uint32_t x20 = 358822242U;
static volatile int32_t t4 = -45841;
t4 = ((x17<=x18)<=(x19|x20));
if (t4 != 1) { NG(); } else { ; }
}
void f5(void) {
static volatile int32_t x21 = INT32_MAX;
uint32_t x22 = 2398U;
int64_t x23 = INT64_MAX;
volatile int16_t x24 = INT16_MIN;
int32_t t5 = 130171;
t5 = ((x21<=x22)<=(x23|x24));
if (t5 != 0) { NG(); } else { ; }
}
void f6(void) {
int8_t x25 = -29;
uint8_t x26 = UINT8_MAX;
static int32_t x28 = -215071;
volatile int32_t t6 = 4040774;
t6 = ((x25<=x26)<=(x27|x28));
if (t6 != 0) { NG(); } else { ; }
}
void f7(void) {
int8_t x29 = INT8_MAX;
int16_t x31 = INT16_MIN;
uint8_t x32 = 0U;
static volatile int32_t t7 = -5;
t7 = ((x29<=x30)<=(x31|x32));
if (t7 != 0) { NG(); } else { ; }
}
void f8(void) {
uint8_t x33 = 92U;
volatile uint16_t x34 = UINT16_MAX;
int16_t x35 = INT16_MIN;
int8_t x36 = INT8_MAX;
int32_t t8 = 155;
t8 = ((x33<=x34)<=(x35|x36));
if (t8 != 0) { NG(); } else { ; }
}
void f9(void) {
int8_t x37 = INT8_MIN;
int32_t t9 = -12;
t9 = ((x37<=x38)<=(x39|x40));
if (t9 != 0) { NG(); } else { ; }
}
void f10(void) {
int64_t x41 = -1LL;
int64_t x42 = -14545LL;
static int64_t x44 = -1LL;
volatile int32_t t10 = 0;
t10 = ((x41<=x42)<=(x43|x44));
if (t10 != 0) { NG(); } else { ; }
}
void f11(void) {
int32_t x46 = INT32_MIN;
uint16_t x47 = UINT16_MAX;
uint32_t x48 = 1980U;
t11 = ((x45<=x46)<=(x47|x48));
if (t11 != 1) { NG(); } else { ; }
}
void f12(void) {
int16_t x49 = INT16_MAX;
int32_t x50 = INT32_MIN;
int8_t x52 = -1;
volatile int32_t t12 = -9912561;
t12 = ((x49<=x50)<=(x51|x52));
if (t12 != 1) { NG(); } else { ; }
}
void f13(void) {
int8_t x53 = 5;
static int16_t x54 = INT16_MIN;
uint32_t x56 = 118198U;
t13 = ((x53<=x54)<=(x55|x56));
if (t13 != 1) { NG(); } else { ; }
}
void f14(void) {
int8_t x58 = INT8_MIN;
int16_t x59 = 21;
uint32_t x60 = 23423U;
t14 = ((x57<=x58)<=(x59|x60));
if (t14 != 1) { NG(); } else { ; }
}
void f15(void) {
int32_t x61 = -216000790;
int64_t x62 = -1LL;
volatile int32_t x63 = 54795;
int64_t x64 = INT64_MAX;
volatile int32_t t15 = 26033;
t15 = ((x61<=x62)<=(x63|x64));
if (t15 != 1) { NG(); } else { ; }
}
void f16(void) {
volatile uint16_t x65 = 66U;
static int64_t x66 = INT64_MAX;
static int64_t x67 = 41553890283LL;
static uint8_t x68 = 1U;
int32_t t16 = 0;
t16 = ((x65<=x66)<=(x67|x68));
if (t16 != 1) { NG(); } else { ; }
}
void f17(void) {
int64_t x69 = -1LL;
int16_t x70 = -585;
int16_t x71 = INT16_MIN;
volatile int32_t t17 = -4383;
t17 = ((x69<=x70)<=(x71|x72));
if (t17 != 0) { NG(); } else { ; }
}
void f18(void) {
uint8_t x73 = 9U;
volatile int16_t x74 = INT16_MIN;
int8_t x75 = INT8_MAX;
static int16_t x76 = INT16_MIN;
int32_t t18 = -41761761;
t18 = ((x73<=x74)<=(x75|x76));
if (t18 != 0) { NG(); } else { ; }
}
void f19(void) {
static int32_t x77 = -1;
volatile uint32_t x78 = 467379U;
int64_t x79 = -1LL;
uint8_t x80 = 0U;
t19 = ((x77<=x78)<=(x79|x80));
if (t19 != 0) { NG(); } else { ; }
}
void f20(void) {
int32_t x83 = INT32_MIN;
int64_t x84 = -1624LL;
t20 = ((x81<=x82)<=(x83|x84));
if (t20 != 0) { NG(); } else { ; }
}
void f21(void) {
volatile uint16_t x85 = 22557U;
uint32_t x86 = 32008465U;
int16_t x88 = -4;
t21 = ((x85<=x86)<=(x87|x88));
if (t21 != 0) { NG(); } else { ; }
}
void f22(void) {
static volatile int32_t x90 = INT32_MIN;
uint8_t x91 = UINT8_MAX;
int32_t t22 = 237340;
t22 = ((x89<=x90)<=(x91|x92));
if (t22 != 0) { NG(); } else { ; }
}
void f23(void) {
int16_t x93 = INT16_MIN;
static int16_t x94 = INT16_MIN;
static uint32_t x95 = 4017763U;
uint32_t x96 = UINT32_MAX;
t23 = ((x93<=x94)<=(x95|x96));
if (t23 != 1) { NG(); } else { ; }
}
void f24(void) {
volatile int64_t x97 = INT64_MIN;
uint32_t x98 = 339U;
int16_t x99 = -1;
int16_t x100 = INT16_MIN;
volatile int32_t t24 = -499776653;
t24 = ((x97<=x98)<=(x99|x100));
if (t24 != 0) { NG(); } else { ; }
}
void f25(void) {
uint8_t x101 = 87U;
int8_t x103 = -1;
int16_t x104 = -325;
int32_t t25 = -1860;
t25 = ((x101<=x102)<=(x103|x104));
if (t25 != 0) { NG(); } else { ; }
}
void f26(void) {
static int64_t x105 = -2134512636499LL;
static int16_t x107 = INT16_MAX;
int32_t t26 = 90755382;
t26 = ((x105<=x106)<=(x107|x108));
if (t26 != 1) { NG(); } else { ; }
}
void f27(void) {
volatile uint32_t x111 = UINT32_MAX;
int64_t x112 = -954408994LL;
t27 = ((x109<=x110)<=(x111|x112));
if (t27 != 0) { NG(); } else { ; }
}
void f28(void) {
volatile uint64_t x113 = 42960010748045981LLU;
static int8_t x114 = -1;
int32_t x116 = 87985340;
t28 = ((x113<=x114)<=(x115|x116));
if (t28 != 0) { NG(); } else { ; }
}
void f29(void) {
int16_t x117 = -1;
int16_t x118 = -1;
uint8_t x120 = 98U;
volatile int32_t t29 = 6310517;
t29 = ((x117<=x118)<=(x119|x120));
if (t29 != 1) { NG(); } else { ; }
}
void f30(void) {
uint16_t x122 = UINT16_MAX;
uint8_t x123 = UINT8_MAX;
int16_t x124 = INT16_MAX;
volatile int32_t t30 = -347;
t30 = ((x121<=x122)<=(x123|x124));
if (t30 != 1) { NG(); } else { ; }
}
void f31(void) {
static int32_t x125 = 6198;
volatile int32_t x127 = INT32_MIN;
int32_t t31 = 295398;
t31 = ((x125<=x126)<=(x127|x128));
if (t31 != 0) { NG(); } else { ; }
}
void f32(void) {
int32_t x129 = INT32_MIN;
int64_t x130 = 331LL;
int32_t x131 = -1;
static int64_t x132 = -57836411144398764LL;
int32_t t32 = 0;
t32 = ((x129<=x130)<=(x131|x132));
if (t32 != 0) { NG(); } else { ; }
}
void f33(void) {
int32_t x133 = INT32_MIN;
volatile int8_t x134 = 0;
int64_t x135 = INT64_MIN;
int8_t x136 = -1;
int32_t t33 = 3894685;
t33 = ((x133<=x134)<=(x135|x136));
if (t33 != 0) { NG(); } else { ; }
}
void f34(void) {
int16_t x138 = -1;
int8_t x140 = INT8_MAX;
int32_t t34 = -959523;
t34 = ((x137<=x138)<=(x139|x140));
if (t34 != 1) { NG(); } else { ; }
}
void f35(void) {
volatile int16_t x143 = 0;
int64_t x144 = -4794796453LL;
int32_t t35 = 22207;
t35 = ((x141<=x142)<=(x143|x144));
if (t35 != 0) { NG(); } else { ; }
}
void f36(void) {
static volatile int32_t x146 = INT32_MIN;
uint8_t x147 = 31U;
int32_t x148 = 1;
int32_t t36 = -3;
t36 = ((x145<=x146)<=(x147|x148));
if (t36 != 1) { NG(); } else { ; }
}
void f37(void) {
uint16_t x149 = UINT16_MAX;
int32_t x150 = -64513230;
static uint32_t x151 = 2049236U;
int8_t x152 = -1;
int32_t t37 = 58475867;
t37 = ((x149<=x150)<=(x151|x152));
if (t37 != 1) { NG(); } else { ; }
}
void f38(void) {
uint64_t x153 = 64456145033331299LLU;
static int8_t x155 = INT8_MIN;
int32_t t38 = -41916;
t38 = ((x153<=x154)<=(x155|x156));
if (t38 != 0) { NG(); } else { ; }
}
void f39(void) {
int16_t x157 = 127;
int16_t x158 = 1338;
uint16_t x159 = 2U;
int32_t x160 = INT32_MIN;
static int32_t t39 = 3511063;
t39 = ((x157<=x158)<=(x159|x160));
if (t39 != 0) { NG(); } else { ; }
}
void f40(void) {
int32_t x161 = INT32_MIN;
static volatile int8_t x162 = INT8_MAX;
volatile uint16_t x163 = 1U;
uint8_t x164 = 0U;
t40 = ((x161<=x162)<=(x163|x164));
if (t40 != 1) { NG(); } else { ; }
}
void f41(void) {
volatile uint64_t x165 = 7LLU;
uint8_t x166 = 1U;
int32_t x167 = INT32_MIN;
volatile int64_t x168 = INT64_MIN;
int32_t t41 = -947855;
t41 = ((x165<=x166)<=(x167|x168));
if (t41 != 0) { NG(); } else { ; }
}
void f42(void) {
int64_t x170 = INT64_MIN;
uint32_t x172 = 80369U;
int32_t t42 = 343640;
t42 = ((x169<=x170)<=(x171|x172));
if (t42 != 0) { NG(); } else { ; }
}
void f43(void) {
int8_t x173 = INT8_MAX;
static int32_t x174 = INT32_MIN;
int8_t x175 = -1;
static int16_t x176 = 7912;
t43 = ((x173<=x174)<=(x175|x176));
if (t43 != 0) { NG(); } else { ; }
}
void f44(void) {
int8_t x177 = INT8_MIN;
static int16_t x178 = -1;
uint16_t x179 = 1U;
int64_t x180 = INT64_MIN;
volatile int32_t t44 = 38117;
t44 = ((x177<=x178)<=(x179|x180));
if (t44 != 0) { NG(); } else { ; }
}
void f45(void) {
int32_t x183 = INT32_MAX;
volatile int32_t x184 = 258183;
volatile int32_t t45 = -1;
t45 = ((x181<=x182)<=(x183|x184));
if (t45 != 1) { NG(); } else { ; }
}
void f46(void) {
int16_t x185 = INT16_MIN;
int32_t x186 = INT32_MIN;
static int32_t x188 = -13;
volatile int32_t t46 = 117;
t46 = ((x185<=x186)<=(x187|x188));
if (t46 != 1) { NG(); } else { ; }
}
void f47(void) {
static uint32_t x190 = UINT32_MAX;
int16_t x192 = -2;
static volatile int32_t t47 = 15340;
t47 = ((x189<=x190)<=(x191|x192));
if (t47 != 1) { NG(); } else { ; }
}
void f48(void) {
uint16_t x193 = 0U;
int8_t x194 = 9;
uint16_t x195 = 309U;
int32_t x196 = -1;
int32_t t48 = -8142;
t48 = ((x193<=x194)<=(x195|x196));
if (t48 != 0) { NG(); } else { ; }
}
void f49(void) {
static volatile int64_t x197 = INT64_MIN;
uint16_t x198 = 136U;
int8_t x200 = INT8_MIN;
volatile int32_t t49 = -486;
t49 = ((x197<=x198)<=(x199|x200));
if (t49 != 1) { NG(); } else { ; }
}
void f50(void) {
int32_t x203 = INT32_MAX;
volatile int32_t x204 = -1;
t50 = ((x201<=x202)<=(x203|x204));
if (t50 != 0) { NG(); } else { ; }
}
void f51(void) {
int32_t x205 = INT32_MIN;
int32_t x206 = 3899127;
static volatile int32_t t51 = 1;
t51 = ((x205<=x206)<=(x207|x208));
if (t51 != 1) { NG(); } else { ; }
}
void f52(void) {
int8_t x209 = -5;
int32_t x211 = 952102883;
int64_t x212 = INT64_MIN;
int32_t t52 = -3510671;
t52 = ((x209<=x210)<=(x211|x212));
if (t52 != 0) { NG(); } else { ; }
}
void f53(void) {
uint64_t x213 = UINT64_MAX;
static int16_t x215 = INT16_MIN;
int64_t x216 = INT64_MAX;
volatile int32_t t53 = -1706928;
t53 = ((x213<=x214)<=(x215|x216));
if (t53 != 0) { NG(); } else { ; }
}
void f54(void) {
uint16_t x217 = 13U;
static int16_t x219 = 0;
int32_t x220 = -212;
t54 = ((x217<=x218)<=(x219|x220));
if (t54 != 0) { NG(); } else { ; }
}
void f55(void) {
static uint8_t x221 = 39U;
int8_t x222 = 1;
uint8_t x223 = 62U;
int8_t x224 = INT8_MAX;
volatile int32_t t55 = -5663498;
t55 = ((x221<=x222)<=(x223|x224));
if (t55 != 1) { NG(); } else { ; }
}
void f56(void) {
volatile uint32_t x225 = 6U;
uint16_t x226 = 1844U;
int32_t x227 = INT32_MIN;
uint64_t x228 = 11973850469698LLU;
int32_t t56 = -13088;
t56 = ((x225<=x226)<=(x227|x228));
if (t56 != 1) { NG(); } else { ; }
}
void f57(void) {
int64_t x229 = INT64_MIN;
static uint16_t x230 = 6318U;
uint16_t x231 = 6077U;
uint8_t x232 = 10U;
int32_t t57 = 160326524;
t57 = ((x229<=x230)<=(x231|x232));
if (t57 != 1) { NG(); } else { ; }
}
void f58(void) {
volatile int64_t x233 = INT64_MAX;
uint8_t x234 = 85U;
uint64_t x235 = 563515362627274LLU;
static int8_t x236 = INT8_MAX;
volatile int32_t t58 = 2905;
t58 = ((x233<=x234)<=(x235|x236));
if (t58 != 1) { NG(); } else { ; }
}
void f59(void) {
static uint8_t x237 = 94U;
uint16_t x238 = UINT16_MAX;
int16_t x239 = INT16_MIN;
int16_t x240 = INT16_MAX;
t59 = ((x237<=x238)<=(x239|x240));
if (t59 != 0) { NG(); } else { ; }
}
void f60(void) {
volatile int32_t x241 = INT32_MAX;
int8_t x242 = 23;
volatile uint16_t x243 = 1U;
uint32_t x244 = 61835611U;
t60 = ((x241<=x242)<=(x243|x244));
if (t60 != 1) { NG(); } else { ; }
}
void f61(void) {
int32_t x245 = -1;
uint32_t x246 = UINT32_MAX;
int64_t x247 = INT64_MIN;
static int32_t x248 = -1;
t61 = ((x245<=x246)<=(x247|x248));
if (t61 != 0) { NG(); } else { ; }
}
void f62(void) {
static int64_t x249 = -47078LL;
int64_t x250 = INT64_MIN;
int32_t x251 = -1;
int8_t x252 = 21;
int32_t t62 = -2;
t62 = ((x249<=x250)<=(x251|x252));
if (t62 != 0) { NG(); } else { ; }
}
void f63(void) {
uint8_t x254 = 3U;
volatile int16_t x255 = INT16_MIN;
volatile uint16_t x256 = 31U;
t63 = ((x253<=x254)<=(x255|x256));
if (t63 != 0) { NG(); } else { ; }
}
void f64(void) {
volatile int64_t x257 = -1LL;
volatile int64_t x258 = INT64_MIN;
int64_t x259 = -673556672441LL;
volatile uint32_t x260 = UINT32_MAX;
int32_t t64 = -1;
t64 = ((x257<=x258)<=(x259|x260));
if (t64 != 0) { NG(); } else { ; }
}
void f65(void) {
int32_t x261 = -1;
int8_t x263 = INT8_MIN;
static uint8_t x264 = 55U;
int32_t t65 = 845;
t65 = ((x261<=x262)<=(x263|x264));
if (t65 != 0) { NG(); } else { ; }
}
void f66(void) {
static volatile int64_t x265 = 11717577030469LL;
int16_t x266 = -1;
int32_t x267 = INT32_MAX;
static volatile int32_t t66 = -13536242;
t66 = ((x265<=x266)<=(x267|x268));
if (t66 != 0) { NG(); } else { ; }
}
void f67(void) {
volatile uint32_t x269 = UINT32_MAX;
static volatile int16_t x270 = INT16_MIN;
volatile uint64_t x272 = UINT64_MAX;
static int32_t t67 = -8;
t67 = ((x269<=x270)<=(x271|x272));
if (t67 != 1) { NG(); } else { ; }
}
void f68(void) {
int16_t x273 = INT16_MAX;
static int8_t x274 = -1;
static volatile uint16_t x275 = UINT16_MAX;
volatile int32_t t68 = -4917;
t68 = ((x273<=x274)<=(x275|x276));
if (t68 != 1) { NG(); } else { ; }
}
void f69(void) {
int16_t x277 = 2;
static int64_t x278 = INT64_MIN;
volatile int64_t x279 = -1397LL;
volatile uint32_t x280 = 102U;
volatile int32_t t69 = -1;
t69 = ((x277<=x278)<=(x279|x280));
if (t69 != 0) { NG(); } else { ; }
}
void f70(void) {
int16_t x281 = -1;
t70 = ((x281<=x282)<=(x283|x284));
if (t70 != 1) { NG(); } else { ; }
}
void f71(void) {
int8_t x285 = -1;
uint64_t x286 = 53336749497422299LLU;
volatile uint64_t x288 = UINT64_MAX;
t71 = ((x285<=x286)<=(x287|x288));
if (t71 != 1) { NG(); } else { ; }
}
void f72(void) {
uint16_t x290 = 5U;
static int16_t x291 = 155;
uint64_t x292 = 35632352234100LLU;
volatile int32_t t72 = -2222;
t72 = ((x289<=x290)<=(x291|x292));
if (t72 != 1) { NG(); } else { ; }
}
void f73(void) {
static int32_t x293 = -1;
int32_t x294 = 995347594;
volatile int32_t t73 = -65052;
t73 = ((x293<=x294)<=(x295|x296));
if (t73 != 0) { NG(); } else { ; }
}
void f74(void) {
static int64_t x297 = -508666025LL;
static int8_t x300 = INT8_MIN;
volatile int32_t t74 = 0;
t74 = ((x297<=x298)<=(x299|x300));
if (t74 != 0) { NG(); } else { ; }
}
void f75(void) {
int64_t x301 = INT64_MIN;
int64_t x303 = -1LL;
t75 = ((x301<=x302)<=(x303|x304));
if (t75 != 0) { NG(); } else { ; }
}
void f76(void) {
volatile int32_t x305 = INT32_MIN;
uint64_t x306 = UINT64_MAX;
int32_t x307 = 1243;
static uint32_t x308 = 27141295U;
t76 = ((x305<=x306)<=(x307|x308));
if (t76 != 1) { NG(); } else { ; }
}
void f77(void) {
int8_t x309 = INT8_MIN;
int64_t x310 = INT64_MAX;
int8_t x311 = 34;
static volatile int32_t t77 = -8726;
t77 = ((x309<=x310)<=(x311|x312));
if (t77 != 0) { NG(); } else { ; }
}
void f78(void) {
int64_t x313 = 1539289063749LL;
int32_t x314 = INT32_MIN;
int32_t x315 = INT32_MAX;
volatile int64_t x316 = INT64_MIN;
t78 = ((x313<=x314)<=(x315|x316));
if (t78 != 0) { NG(); } else { ; }
}
void f79(void) {
int64_t x317 = INT64_MIN;
static volatile uint32_t x318 = UINT32_MAX;
int8_t x319 = INT8_MIN;
int64_t x320 = INT64_MIN;
volatile int32_t t79 = -1;
t79 = ((x317<=x318)<=(x319|x320));
if (t79 != 0) { NG(); } else { ; }
}
void f80(void) {
static int64_t x321 = -1LL;
uint8_t x324 = 124U;
int32_t t80 = 57764;
t80 = ((x321<=x322)<=(x323|x324));
if (t80 != 1) { NG(); } else { ; }
}
void f81(void) {
uint8_t x325 = 1U;
uint32_t x326 = 22U;
uint32_t x327 = 17U;
volatile int32_t t81 = -1908874;
t81 = ((x325<=x326)<=(x327|x328));
if (t81 != 1) { NG(); } else { ; }
}
void f82(void) {
uint16_t x329 = 263U;
static int64_t x330 = 6892LL;
uint8_t x331 = 8U;
volatile int32_t t82 = -3755368;
t82 = ((x329<=x330)<=(x331|x332));
if (t82 != 0) { NG(); } else { ; }
}
void f83(void) {
int16_t x333 = INT16_MIN;
static volatile int16_t x334 = -6203;
int64_t x336 = INT64_MIN;
int32_t t83 = -32875;
t83 = ((x333<=x334)<=(x335|x336));
if (t83 != 0) { NG(); } else { ; }
}
void f84(void) {
volatile uint64_t x337 = UINT64_MAX;
int8_t x338 = INT8_MIN;
int64_t x340 = -1LL;
volatile int32_t t84 = 40;
t84 = ((x337<=x338)<=(x339|x340));
if (t84 != 0) { NG(); } else { ; }
}
void f85(void) {
uint64_t x341 = UINT64_MAX;
int32_t x342 = INT32_MIN;
uint16_t x343 = 3U;
int32_t x344 = INT32_MIN;
static volatile int32_t t85 = 0;
t85 = ((x341<=x342)<=(x343|x344));
if (t85 != 0) { NG(); } else { ; }
}
void f86(void) {
int8_t x345 = 7;
int8_t x346 = -9;
volatile int8_t x347 = INT8_MIN;
uint32_t x348 = 228196U;
int32_t t86 = 1;
t86 = ((x345<=x346)<=(x347|x348));
if (t86 != 1) { NG(); } else { ; }
}
void f87(void) {
int32_t x349 = INT32_MIN;
int64_t x350 = INT64_MIN;
int32_t x351 = 34391;
int32_t t87 = 0;
t87 = ((x349<=x350)<=(x351|x352));
if (t87 != 1) { NG(); } else { ; }
}
void f88(void) {
uint32_t x353 = 155U;
volatile int32_t x354 = -1;
uint64_t x355 = 5LLU;
static int64_t x356 = INT64_MIN;
volatile int32_t t88 = 10793;
t88 = ((x353<=x354)<=(x355|x356));
if (t88 != 1) { NG(); } else { ; }
}
void f89(void) {
int16_t x357 = INT16_MIN;
int8_t x359 = INT8_MIN;
int32_t t89 = -436385975;
t89 = ((x357<=x358)<=(x359|x360));
if (t89 != 0) { NG(); } else { ; }
}
void f90(void) {
static uint16_t x361 = UINT16_MAX;
int64_t x362 = -1LL;
int32_t x363 = 2;
t90 = ((x361<=x362)<=(x363|x364));
if (t90 != 1) { NG(); } else { ; }
}
void f91(void) {
static int16_t x365 = 1;
int8_t x366 = INT8_MIN;
static int32_t x367 = -1;
volatile int64_t x368 = INT64_MIN;
t91 = ((x365<=x366)<=(x367|x368));
if (t91 != 0) { NG(); } else { ; }
}
void f92(void) {
int32_t x369 = -1;
uint8_t x370 = UINT8_MAX;
volatile uint8_t x371 = 10U;
int8_t x372 = -1;
static int32_t t92 = 1;
t92 = ((x369<=x370)<=(x371|x372));
if (t92 != 0) { NG(); } else { ; }
}
void f93(void) {
int16_t x373 = -1;
int32_t x375 = -1;
int32_t x376 = -1;
int32_t t93 = -1043;
t93 = ((x373<=x374)<=(x375|x376));
if (t93 != 0) { NG(); } else { ; }
}
void f94(void) {
int8_t x378 = 62;
int8_t x379 = INT8_MIN;
uint8_t x380 = 91U;
int32_t t94 = 278462541;
t94 = ((x377<=x378)<=(x379|x380));
if (t94 != 0) { NG(); } else { ; }
}
void f95(void) {
int32_t x383 = 65404274;
int32_t x384 = INT32_MAX;
volatile int32_t t95 = -3;
t95 = ((x381<=x382)<=(x383|x384));
if (t95 != 1) { NG(); } else { ; }
}
void f96(void) {
volatile int16_t x385 = INT16_MAX;
int16_t x386 = INT16_MIN;
int64_t x388 = INT64_MAX;
volatile int32_t t96 = 806734;
t96 = ((x385<=x386)<=(x387|x388));
if (t96 != 1) { NG(); } else { ; }
}
void f97(void) {
int32_t x389 = INT32_MAX;
int8_t x390 = INT8_MAX;
static int32_t x391 = INT32_MIN;
int64_t x392 = -1LL;
int32_t t97 = 45001;
t97 = ((x389<=x390)<=(x391|x392));
if (t97 != 0) { NG(); } else { ; }
}
void f98(void) {
static uint16_t x393 = 2880U;
uint8_t x394 = UINT8_MAX;
uint8_t x395 = 7U;
int32_t x396 = INT32_MIN;
int32_t t98 = 26742;
t98 = ((x393<=x394)<=(x395|x396));
if (t98 != 0) { NG(); } else { ; }
}
void f99(void) {
int8_t x397 = -1;
static uint64_t x398 = 206912825LLU;
uint16_t x399 = 12359U;
uint8_t x400 = UINT8_MAX;
t99 = ((x397<=x398)<=(x399|x400));
if (t99 != 1) { NG(); } else { ; }
}
void f100(void) {
int16_t x401 = 0;
int16_t x403 = -107;
t100 = ((x401<=x402)<=(x403|x404));
if (t100 != 1) { NG(); } else { ; }
}
void f101(void) {
static int64_t x405 = -13943825121393363LL;
volatile int32_t t101 = 138672;
t101 = ((x405<=x406)<=(x407|x408));
if (t101 != 0) { NG(); } else { ; }
}
void f102(void) {
volatile int16_t x409 = INT16_MAX;
int32_t x410 = INT32_MIN;
int32_t x412 = -6;
volatile int32_t t102 = -1;
t102 = ((x409<=x410)<=(x411|x412));
if (t102 != 0) { NG(); } else { ; }
}
void f103(void) {
volatile int8_t x413 = INT8_MAX;
static uint32_t x414 = UINT32_MAX;
static int32_t x415 = INT32_MIN;
volatile int32_t x416 = INT32_MIN;
t103 = ((x413<=x414)<=(x415|x416));
if (t103 != 0) { NG(); } else { ; }
}
void f104(void) {
static uint64_t x417 = 98616540LLU;
static int16_t x418 = 871;
volatile int32_t x419 = INT32_MIN;
uint64_t x420 = 53570205LLU;
t104 = ((x417<=x418)<=(x419|x420));
if (t104 != 1) { NG(); } else { ; }
}
void f105(void) {
int64_t x421 = INT64_MIN;
volatile uint8_t x422 = 43U;
int32_t x424 = INT32_MIN;
static int32_t t105 = -74508087;
t105 = ((x421<=x422)<=(x423|x424));
if (t105 != 0) { NG(); } else { ; }
}
void f106(void) {
volatile int32_t x425 = -543;
t106 = ((x425<=x426)<=(x427|x428));
if (t106 != 0) { NG(); } else { ; }
}
void f107(void) {
volatile int16_t x429 = INT16_MIN;
int64_t x431 = INT64_MIN;
uint32_t x432 = UINT32_MAX;
t107 = ((x429<=x430)<=(x431|x432));
if (t107 != 0) { NG(); } else { ; }
}
void f108(void) {
uint8_t x433 = 119U;
volatile int16_t x434 = 274;
int64_t x435 = 0LL;
t108 = ((x433<=x434)<=(x435|x436));
if (t108 != 1) { NG(); } else { ; }
}
void f109(void) {
static volatile int8_t x437 = INT8_MIN;
int64_t x439 = INT64_MIN;
int8_t x440 = INT8_MAX;
t109 = ((x437<=x438)<=(x439|x440));
if (t109 != 0) { NG(); } else { ; }
}
void f110(void) {
int64_t x441 = -1LL;
int64_t x442 = INT64_MIN;
uint32_t x443 = UINT32_MAX;
volatile int64_t x444 = -1LL;
volatile int32_t t110 = 45833415;
t110 = ((x441<=x442)<=(x443|x444));
if (t110 != 0) { NG(); } else { ; }
}
void f111(void) {
int64_t x445 = 8575167640276997LL;
volatile int64_t x446 = INT64_MAX;
static int8_t x447 = INT8_MIN;
static volatile int8_t x448 = 17;
static volatile int32_t t111 = 244;
t111 = ((x445<=x446)<=(x447|x448));
if (t111 != 0) { NG(); } else { ; }
}
void f112(void) {
int32_t x449 = -1;
int16_t x450 = INT16_MIN;
int16_t x451 = 1;
uint16_t x452 = 131U;
int32_t t112 = 300790;
t112 = ((x449<=x450)<=(x451|x452));
if (t112 != 1) { NG(); } else { ; }
}
void f113(void) {
int64_t x453 = 206133396134442LL;
uint8_t x454 = 1U;
int64_t x455 = -1LL;
static int64_t x456 = 81295708238LL;
volatile int32_t t113 = 2021402;
t113 = ((x453<=x454)<=(x455|x456));
if (t113 != 0) { NG(); } else { ; }
}
void f114(void) {
static int64_t x457 = -1LL;
int64_t x458 = 100111803LL;
int16_t x459 = INT16_MIN;
volatile uint64_t x460 = 18LLU;
static volatile int32_t t114 = -14;
t114 = ((x457<=x458)<=(x459|x460));
if (t114 != 1) { NG(); } else { ; }
}
void f115(void) {
int32_t x461 = INT32_MAX;
uint64_t x462 = UINT64_MAX;
int16_t x463 = INT16_MIN;
volatile int32_t t115 = -30344;
t115 = ((x461<=x462)<=(x463|x464));
if (t115 != 0) { NG(); } else { ; }
}
void f116(void) {
int16_t x465 = INT16_MIN;
static volatile int8_t x466 = -1;
int32_t x468 = INT32_MAX;
int32_t t116 = -30700240;
t116 = ((x465<=x466)<=(x467|x468));
if (t116 != 1) { NG(); } else { ; }
}
void f117(void) {
volatile int16_t x469 = INT16_MAX;
int16_t x471 = 7131;
uint16_t x472 = UINT16_MAX;
int32_t t117 = 621099;
t117 = ((x469<=x470)<=(x471|x472));
if (t117 != 1) { NG(); } else { ; }
}
void f118(void) {
int32_t x473 = INT32_MIN;
volatile int8_t x474 = INT8_MIN;
int32_t x475 = INT32_MAX;
volatile int16_t x476 = INT16_MAX;
volatile int32_t t118 = 16430644;
t118 = ((x473<=x474)<=(x475|x476));
if (t118 != 1) { NG(); } else { ; }
}
void f119(void) {
static int64_t x477 = INT64_MIN;
int8_t x478 = -54;
static volatile uint16_t x479 = UINT16_MAX;
int32_t x480 = -13867;
volatile int32_t t119 = -406601;
t119 = ((x477<=x478)<=(x479|x480));
if (t119 != 0) { NG(); } else { ; }
}
void f120(void) {
static int16_t x481 = 15;
volatile uint16_t x482 = UINT16_MAX;
int64_t x483 = INT64_MIN;
static int8_t x484 = INT8_MIN;
volatile int32_t t120 = 963634;
t120 = ((x481<=x482)<=(x483|x484));
if (t120 != 0) { NG(); } else { ; }
}
void f121(void) {
volatile int64_t x485 = -219LL;
volatile int64_t x488 = INT64_MIN;
t121 = ((x485<=x486)<=(x487|x488));
if (t121 != 0) { NG(); } else { ; }
}
void f122(void) {
int32_t x489 = -10855;
int32_t x490 = 14;
uint64_t x491 = 265563571707880311LLU;
uint32_t x492 = 42312U;
t122 = ((x489<=x490)<=(x491|x492));
if (t122 != 1) { NG(); } else { ; }
}
void f123(void) {
uint16_t x493 = UINT16_MAX;
uint64_t x494 = 14LLU;
uint16_t x495 = 1714U;
uint64_t x496 = 267352213982161125LLU;
volatile int32_t t123 = -254701;
t123 = ((x493<=x494)<=(x495|x496));
if (t123 != 1) { NG(); } else { ; }
}
void f124(void) {
uint32_t x497 = 89186U;
int32_t x498 = INT32_MIN;
uint32_t x500 = 8374945U;
t124 = ((x497<=x498)<=(x499|x500));
if (t124 != 0) { NG(); } else { ; }
}
void f125(void) {
volatile uint8_t x502 = UINT8_MAX;
int32_t x503 = 563432;
volatile int64_t x504 = 133LL;
volatile int32_t t125 = -224;
t125 = ((x501<=x502)<=(x503|x504));
if (t125 != 1) { NG(); } else { ; }
}
void f126(void) {
uint16_t x505 = UINT16_MAX;
uint16_t x506 = UINT16_MAX;
int16_t x508 = 11612;
volatile int32_t t126 = 12892;
t126 = ((x505<=x506)<=(x507|x508));
if (t126 != 0) { NG(); } else { ; }
}
void f127(void) {
int16_t x509 = INT16_MIN;
int32_t x510 = INT32_MAX;
int8_t x512 = -1;
volatile int32_t t127 = -177;
t127 = ((x509<=x510)<=(x511|x512));
if (t127 != 0) { NG(); } else { ; }
}
void f128(void) {
int32_t x513 = INT32_MAX;
uint64_t x514 = 119027LLU;
uint32_t x515 = 1010276230U;
volatile int16_t x516 = 19;
t128 = ((x513<=x514)<=(x515|x516));
if (t128 != 1) { NG(); } else { ; }
}
void f129(void) {
volatile uint32_t x517 = 584911477U;
uint32_t x518 = 105666U;
int16_t x519 = INT16_MIN;
int16_t x520 = INT16_MIN;
volatile int32_t t129 = -1405580;
t129 = ((x517<=x518)<=(x519|x520));
if (t129 != 0) { NG(); } else { ; }
}
void f130(void) {
int32_t x521 = 1;
volatile int8_t x522 = INT8_MIN;
int8_t x523 = INT8_MIN;
uint64_t x524 = 1245764985330LLU;
volatile int32_t t130 = -215;
t130 = ((x521<=x522)<=(x523|x524));
if (t130 != 1) { NG(); } else { ; }
}
void f131(void) {
int32_t x525 = INT32_MIN;
static uint64_t x526 = 7301528087LLU;
static int32_t x528 = -8175238;
static volatile int32_t t131 = 0;
t131 = ((x525<=x526)<=(x527|x528));
if (t131 != 0) { NG(); } else { ; }
}
void f132(void) {
volatile int32_t x529 = INT32_MIN;
volatile int64_t x530 = INT64_MIN;
int16_t x532 = -2162;
int32_t t132 = 29;
t132 = ((x529<=x530)<=(x531|x532));
if (t132 != 1) { NG(); } else { ; }
}
void f133(void) {
uint64_t x533 = UINT64_MAX;
int64_t x534 = -1LL;
uint32_t x535 = 54462U;
static uint32_t x536 = UINT32_MAX;
static int32_t t133 = -693882;
t133 = ((x533<=x534)<=(x535|x536));
if (t133 != 1) { NG(); } else { ; }
}
void f134(void) {
uint32_t x537 = UINT32_MAX;
int64_t x538 = INT64_MIN;
int64_t x539 = -6657179LL;
int32_t t134 = 8;
t134 = ((x537<=x538)<=(x539|x540));
if (t134 != 0) { NG(); } else { ; }
}
void f135(void) {
int8_t x542 = 63;
static int64_t x543 = 8442442897574LL;
volatile uint64_t x544 = UINT64_MAX;
volatile int32_t t135 = -801;
t135 = ((x541<=x542)<=(x543|x544));
if (t135 != 1) { NG(); } else { ; }
}
void f136(void) {
int8_t x545 = 36;
int16_t x546 = -1;
static int16_t x548 = -6781;
int32_t t136 = 770187031;
t136 = ((x545<=x546)<=(x547|x548));
if (t136 != 0) { NG(); } else { ; }
}
void f137(void) {
int8_t x550 = INT8_MIN;
int8_t x551 = INT8_MIN;
static int32_t t137 = 11408768;
t137 = ((x549<=x550)<=(x551|x552));
if (t137 != 1) { NG(); } else { ; }
}
void f138(void) {
int16_t x553 = INT16_MAX;
volatile int32_t x554 = 2509;
volatile int32_t x555 = -1;
int16_t x556 = INT16_MIN;
int32_t t138 = 1;
t138 = ((x553<=x554)<=(x555|x556));
if (t138 != 0) { NG(); } else { ; }
}
void f139(void) {
int64_t x557 = INT64_MIN;
static int16_t x558 = INT16_MIN;
uint16_t x559 = UINT16_MAX;
t139 = ((x557<=x558)<=(x559|x560));
if (t139 != 1) { NG(); } else { ; }
}
void f140(void) {
uint64_t x562 = UINT64_MAX;
int16_t x563 = INT16_MIN;
volatile int32_t t140 = -783;
t140 = ((x561<=x562)<=(x563|x564));
if (t140 != 0) { NG(); } else { ; }
}
void f141(void) {
int8_t x565 = INT8_MIN;
volatile int16_t x566 = -1;
int8_t x567 = -1;
t141 = ((x565<=x566)<=(x567|x568));
if (t141 != 0) { NG(); } else { ; }
}
void f142(void) {
int64_t x569 = 56946611934345LL;
int32_t x572 = INT32_MAX;
t142 = ((x569<=x570)<=(x571|x572));
if (t142 != 0) { NG(); } else { ; }
}
void f143(void) {
volatile uint32_t x573 = 41U;
int64_t x574 = -1LL;
volatile uint32_t x576 = 2174247U;
int32_t t143 = 104;
t143 = ((x573<=x574)<=(x575|x576));
if (t143 != 1) { NG(); } else { ; }
}
void f144(void) {
volatile uint16_t x578 = 14U;
int32_t x579 = INT32_MAX;
int32_t x580 = INT32_MIN;
t144 = ((x577<=x578)<=(x579|x580));
if (t144 != 0) { NG(); } else { ; }
}
void f145(void) {
uint16_t x581 = 212U;
static volatile uint32_t x582 = 645U;
static volatile uint8_t x583 = UINT8_MAX;
int16_t x584 = INT16_MAX;
static volatile int32_t t145 = 153737553;
t145 = ((x581<=x582)<=(x583|x584));
if (t145 != 1) { NG(); } else { ; }
}
void f146(void) {
uint8_t x585 = 0U;
static uint16_t x586 = UINT16_MAX;
volatile int8_t x587 = -1;
static int32_t t146 = -303157;
t146 = ((x585<=x586)<=(x587|x588));
if (t146 != 0) { NG(); } else { ; }
}
void f147(void) {
uint32_t x589 = 620024421U;
uint64_t x590 = UINT64_MAX;
uint8_t x592 = 2U;
volatile int32_t t147 = -3;
t147 = ((x589<=x590)<=(x591|x592));
if (t147 != 0) { NG(); } else { ; }
}
void f148(void) {
static int8_t x593 = INT8_MAX;
int64_t x594 = INT64_MIN;
int16_t x595 = INT16_MIN;
static uint16_t x596 = 36U;
t148 = ((x593<=x594)<=(x595|x596));
if (t148 != 0) { NG(); } else { ; }
}
void f149(void) {
int32_t x598 = -1;
int8_t x599 = INT8_MAX;
int64_t x600 = INT64_MIN;
int32_t t149 = -19410;
t149 = ((x597<=x598)<=(x599|x600));
if (t149 != 0) { NG(); } else { ; }
}
void f150(void) {
static uint64_t x601 = 5LLU;
volatile uint32_t x603 = UINT32_MAX;
volatile int32_t t150 = 6152;
t150 = ((x601<=x602)<=(x603|x604));
if (t150 != 1) { NG(); } else { ; }
}
void f151(void) {
int32_t x605 = -1;
static uint64_t x606 = 14939404LLU;
uint32_t x607 = 408069617U;
int32_t x608 = INT32_MAX;
static int32_t t151 = -261530;
t151 = ((x605<=x606)<=(x607|x608));
if (t151 != 1) { NG(); } else { ; }
}
void f152(void) {
int8_t x609 = INT8_MIN;
static int64_t x610 = 144LL;
int64_t x612 = INT64_MIN;
int32_t t152 = -24975;
t152 = ((x609<=x610)<=(x611|x612));
if (t152 != 0) { NG(); } else { ; }
}
void f153(void) {
int32_t x613 = INT32_MAX;
int8_t x615 = 30;
volatile uint64_t x616 = 4752335651140236023LLU;
volatile int32_t t153 = -21;
t153 = ((x613<=x614)<=(x615|x616));
if (t153 != 1) { NG(); } else { ; }
}
void f154(void) {
volatile int16_t x617 = INT16_MIN;
uint64_t x619 = UINT64_MAX;
int32_t x620 = INT32_MIN;
int32_t t154 = -8113938;
t154 = ((x617<=x618)<=(x619|x620));
if (t154 != 1) { NG(); } else { ; }
}
void f155(void) {
int8_t x621 = 0;
uint64_t x622 = 1249593255729LLU;
int64_t x623 = INT64_MIN;
int8_t x624 = -1;
int32_t t155 = 130456005;
t155 = ((x621<=x622)<=(x623|x624));
if (t155 != 0) { NG(); } else { ; }
}
void f156(void) {
int16_t x626 = 11;
int32_t x628 = 54694639;
t156 = ((x625<=x626)<=(x627|x628));
if (t156 != 1) { NG(); } else { ; }
}
void f157(void) {
int8_t x629 = INT8_MIN;
uint64_t x630 = 12569758874LLU;
static uint16_t x631 = 2U;
static uint8_t x632 = 1U;
static int32_t t157 = -13;
t157 = ((x629<=x630)<=(x631|x632));
if (t157 != 1) { NG(); } else { ; }
}
void f158(void) {
int16_t x633 = -101;
volatile int8_t x634 = -8;
t158 = ((x633<=x634)<=(x635|x636));
if (t158 != 0) { NG(); } else { ; }
}
void f159(void) {
int32_t x638 = -1;
uint16_t x639 = 7U;
uint8_t x640 = 0U;
t159 = ((x637<=x638)<=(x639|x640));
if (t159 != 1) { NG(); } else { ; }
}
void f160(void) {
int16_t x641 = INT16_MIN;
volatile uint8_t x642 = UINT8_MAX;
uint64_t x643 = 1726706844LLU;
volatile int64_t x644 = INT64_MIN;
volatile int32_t t160 = 543990;
t160 = ((x641<=x642)<=(x643|x644));
if (t160 != 1) { NG(); } else { ; }
}
void f161(void) {
static volatile uint32_t x646 = UINT32_MAX;
int64_t x647 = INT64_MAX;
volatile int64_t x648 = 435247LL;
volatile int32_t t161 = -289338737;
t161 = ((x645<=x646)<=(x647|x648));
if (t161 != 1) { NG(); } else { ; }
}
void f162(void) {
int64_t x650 = INT64_MIN;
volatile uint16_t x651 = 10821U;
uint32_t x652 = 1110U;
volatile int32_t t162 = -330785;
t162 = ((x649<=x650)<=(x651|x652));
if (t162 != 1) { NG(); } else { ; }
}
void f163(void) {
int32_t x654 = 971270;
volatile int64_t x655 = -1LL;
volatile int32_t t163 = -1;
t163 = ((x653<=x654)<=(x655|x656));
if (t163 != 0) { NG(); } else { ; }
}
void f164(void) {
static int32_t x658 = INT32_MIN;
static int16_t x660 = INT16_MIN;
static int32_t t164 = 740;
t164 = ((x657<=x658)<=(x659|x660));
if (t164 != 0) { NG(); } else { ; }
}
void f165(void) {
int32_t x661 = INT32_MIN;
uint32_t x662 = UINT32_MAX;
int8_t x663 = INT8_MAX;
volatile uint8_t x664 = UINT8_MAX;
static volatile int32_t t165 = -73;
t165 = ((x661<=x662)<=(x663|x664));
if (t165 != 1) { NG(); } else { ; }
}
void f166(void) {
volatile int16_t x665 = 5;
volatile uint64_t x666 = 8593794571044LLU;
volatile int16_t x668 = INT16_MAX;
t166 = ((x665<=x666)<=(x667|x668));
if (t166 != 0) { NG(); } else { ; }
}
void f167(void) {
volatile int8_t x669 = INT8_MIN;
int64_t x670 = 6748653522787LL;
static volatile int16_t x671 = 1;
int16_t x672 = -224;
int32_t t167 = 14682;
t167 = ((x669<=x670)<=(x671|x672));
if (t167 != 0) { NG(); } else { ; }
}
void f168(void) {
static int32_t x673 = INT32_MIN;
int64_t x675 = -1LL;
int32_t t168 = 15993670;
t168 = ((x673<=x674)<=(x675|x676));
if (t168 != 0) { NG(); } else { ; }
}
void f169(void) {
int64_t x677 = INT64_MIN;
int8_t x678 = INT8_MAX;
int8_t x679 = INT8_MIN;
int32_t x680 = -6151;
t169 = ((x677<=x678)<=(x679|x680));
if (t169 != 0) { NG(); } else { ; }
}
void f170(void) {
int16_t x681 = 8420;
volatile int16_t x683 = 494;
static int32_t t170 = 13951;
t170 = ((x681<=x682)<=(x683|x684));
if (t170 != 0) { NG(); } else { ; }
}
void f171(void) {
static int16_t x685 = INT16_MIN;
uint16_t x687 = UINT16_MAX;
int16_t x688 = INT16_MIN;
t171 = ((x685<=x686)<=(x687|x688));
if (t171 != 0) { NG(); } else { ; }
}
void f172(void) {
int8_t x689 = INT8_MIN;
volatile int32_t x690 = -22;
static volatile int16_t x691 = INT16_MIN;
uint64_t x692 = 574633265039733425LLU;
volatile int32_t t172 = 98607;
t172 = ((x689<=x690)<=(x691|x692));
if (t172 != 1) { NG(); } else { ; }
}
void f173(void) {
uint64_t x695 = 64502692035676LLU;
static int32_t x696 = 25763;
int32_t t173 = 3480;
t173 = ((x693<=x694)<=(x695|x696));
if (t173 != 1) { NG(); } else { ; }
}
void f174(void) {
static uint8_t x697 = 1U;
uint8_t x698 = UINT8_MAX;
uint16_t x699 = 45U;
volatile uint16_t x700 = 40U;
int32_t t174 = 4;
t174 = ((x697<=x698)<=(x699|x700));
if (t174 != 1) { NG(); } else { ; }
}
void f175(void) {
static int32_t x701 = INT32_MIN;
uint16_t x702 = 273U;
int64_t x703 = INT64_MIN;
int8_t x704 = -1;
t175 = ((x701<=x702)<=(x703|x704));
if (t175 != 0) { NG(); } else { ; }
}
void f176(void) {
int64_t x706 = INT64_MIN;
static int8_t x707 = INT8_MAX;
uint64_t x708 = 64617365594LLU;
volatile int32_t t176 = 1;
t176 = ((x705<=x706)<=(x707|x708));
if (t176 != 1) { NG(); } else { ; }
}
void f177(void) {
uint8_t x709 = 11U;
int16_t x710 = INT16_MAX;
int32_t x711 = INT32_MIN;
int32_t t177 = 1;
t177 = ((x709<=x710)<=(x711|x712));
if (t177 != 1) { NG(); } else { ; }
}
void f178(void) {
uint16_t x713 = 8568U;
uint64_t x714 = 7073LLU;
volatile int32_t t178 = 2;
t178 = ((x713<=x714)<=(x715|x716));
if (t178 != 1) { NG(); } else { ; }
}
void f179(void) {
static volatile int8_t x717 = INT8_MIN;
int16_t x718 = INT16_MAX;
volatile uint64_t x719 = UINT64_MAX;
int32_t x720 = 5418585;
static int32_t t179 = -1;
t179 = ((x717<=x718)<=(x719|x720));
if (t179 != 1) { NG(); } else { ; }
}
void f180(void) {
static uint16_t x721 = UINT16_MAX;
volatile uint16_t x723 = 3918U;
static uint16_t x724 = 28U;
int32_t t180 = 239456;
t180 = ((x721<=x722)<=(x723|x724));
if (t180 != 1) { NG(); } else { ; }
}
void f181(void) {
int16_t x725 = INT16_MIN;
int32_t x726 = INT32_MIN;
int32_t x727 = INT32_MIN;
static int32_t x728 = 6;
t181 = ((x725<=x726)<=(x727|x728));
if (t181 != 0) { NG(); } else { ; }
}
void f182(void) {
static int32_t x729 = INT32_MIN;
static uint16_t x730 = UINT16_MAX;
int32_t x731 = -394360404;
int32_t x732 = -107;
int32_t t182 = -706683412;
t182 = ((x729<=x730)<=(x731|x732));
if (t182 != 0) { NG(); } else { ; }
}
void f183(void) {
static uint16_t x733 = UINT16_MAX;
int16_t x734 = INT16_MAX;
uint8_t x735 = UINT8_MAX;
int32_t x736 = 861936832;
int32_t t183 = 92677;
t183 = ((x733<=x734)<=(x735|x736));
if (t183 != 1) { NG(); } else { ; }
}
void f184(void) {
uint64_t x737 = 1227784456793775337LLU;
int64_t x738 = INT64_MIN;
int64_t x739 = INT64_MAX;
int8_t x740 = INT8_MAX;
volatile int32_t t184 = -7;
t184 = ((x737<=x738)<=(x739|x740));
if (t184 != 1) { NG(); } else { ; }
}
void f185(void) {
static volatile int16_t x741 = INT16_MIN;
static volatile int64_t x742 = -111452093LL;
volatile uint16_t x743 = 11646U;
int8_t x744 = -8;
volatile int32_t t185 = -294810595;
t185 = ((x741<=x742)<=(x743|x744));
if (t185 != 0) { NG(); } else { ; }
}
void f186(void) {
int64_t x745 = INT64_MAX;
int64_t x746 = -198841LL;
int16_t x747 = INT16_MAX;
uint64_t x748 = 3213739LLU;
volatile int32_t t186 = 7474;
t186 = ((x745<=x746)<=(x747|x748));
if (t186 != 1) { NG(); } else { ; }
}
void f187(void) {
uint32_t x749 = UINT32_MAX;
uint16_t x750 = UINT16_MAX;
int32_t x751 = -882;
static volatile uint16_t x752 = 4751U;
int32_t t187 = 54079;
t187 = ((x749<=x750)<=(x751|x752));
if (t187 != 0) { NG(); } else { ; }
}
void f188(void) {
uint64_t x754 = UINT64_MAX;
uint32_t x755 = 47U;
int8_t x756 = INT8_MIN;
int32_t t188 = 2234785;
t188 = ((x753<=x754)<=(x755|x756));
if (t188 != 1) { NG(); } else { ; }
}
void f189(void) {
volatile uint64_t x757 = 116LLU;
uint32_t x758 = 26839768U;
uint32_t x759 = 1U;
uint64_t x760 = UINT64_MAX;
static int32_t t189 = 0;
t189 = ((x757<=x758)<=(x759|x760));
if (t189 != 1) { NG(); } else { ; }
}
void f190(void) {
static int8_t x761 = 1;
uint32_t x762 = 2U;
volatile uint32_t x764 = 29031567U;
int32_t t190 = 0;
t190 = ((x761<=x762)<=(x763|x764));
if (t190 != 1) { NG(); } else { ; }
}
void f191(void) {
int32_t x765 = -1;
int16_t x766 = INT16_MIN;
int16_t x767 = 1;
uint16_t x768 = 2U;
t191 = ((x765<=x766)<=(x767|x768));
if (t191 != 1) { NG(); } else { ; }
}
void f192(void) {
volatile int32_t x769 = INT32_MIN;
uint64_t x770 = UINT64_MAX;
int32_t x771 = -52351;
volatile int8_t x772 = 2;
volatile int32_t t192 = -878;
t192 = ((x769<=x770)<=(x771|x772));
if (t192 != 0) { NG(); } else { ; }
}
void f193(void) {
static int64_t x773 = -18943179LL;
static uint16_t x774 = 7257U;
volatile int8_t x775 = 0;
int64_t x776 = -663805086319176433LL;
int32_t t193 = -3059;
t193 = ((x773<=x774)<=(x775|x776));
if (t193 != 0) { NG(); } else { ; }
}
void f194(void) {
int16_t x777 = INT16_MIN;
volatile uint8_t x778 = 1U;
volatile uint8_t x780 = UINT8_MAX;
int32_t t194 = 476;
t194 = ((x777<=x778)<=(x779|x780));
if (t194 != 1) { NG(); } else { ; }
}
void f195(void) {
static int32_t x782 = INT32_MAX;
int64_t x783 = -118790706547157061LL;
uint32_t x784 = 46U;
volatile int32_t t195 = -197524364;
t195 = ((x781<=x782)<=(x783|x784));
if (t195 != 0) { NG(); } else { ; }
}
void f196(void) {
int8_t x785 = -1;
volatile int8_t x786 = -1;
int16_t x788 = INT16_MAX;
static volatile int32_t t196 = 28694147;
t196 = ((x785<=x786)<=(x787|x788));
if (t196 != 1) { NG(); } else { ; }
}
void f197(void) {
uint8_t x789 = UINT8_MAX;
int64_t x790 = INT64_MIN;
static int8_t x792 = INT8_MIN;
volatile int32_t t197 = -5;
t197 = ((x789<=x790)<=(x791|x792));
if (t197 != 0) { NG(); } else { ; }
}
void f198(void) {
static uint16_t x795 = UINT16_MAX;
volatile int32_t x796 = -205816766;
volatile int32_t t198 = 1;
t198 = ((x793<=x794)<=(x795|x796));
if (t198 != 0) { NG(); } else { ; }
}
void f199(void) {
int64_t x797 = INT64_MIN;
volatile int32_t t199 = 2;
t199 = ((x797<=x798)<=(x799|x800));
if (t199 != 1) { NG(); } else { ; }
}
int main(void) {
f0();
f1();
f2();
f3();
f4();
f5();
f6();
f7();
f8();
f9();
f10();
f11();
f12();
f13();
f14();
f15();
f16();
f17();
f18();
f19();
f20();
f21();
f22();
f23();
f24();
f25();
f26();
f27();
f28();
f29();
f30();
f31();
f32();
f33();
f34();
f35();
f36();
f37();
f38();
f39();
f40();
f41();
f42();
f43();
f44();
f45();
f46();
f47();
f48();
f49();
f50();
f51();
f52();
f53();
f54();
f55();
f56();
f57();
f58();
f59();
f60();
f61();
f62();
f63();
f64();
f65();
f66();
f67();
f68();
f69();
f70();
f71();
f72();
f73();
f74();
f75();
f76();
f77();
f78();
f79();
f80();
f81();
f82();
f83();
f84();
f85();
f86();
f87();
f88();
f89();
f90();
f91();
f92();
f93();
f94();
f95();
f96();
f97();
f98();
f99();
f100();
f101();
f102();
f103();
f104();
f105();
f106();
f107();
f108();
f109();
f110();
f111();
f112();
f113();
f114();
f115();
f116();
f117();
f118();
f119();
f120();
f121();
f122();
f123();
f124();
f125();
f126();
f127();
f128();
f129();
f130();
f131();
f132();
f133();
f134();
f135();
f136();
f137();
f138();
f139();
f140();
f141();
f142();
f143();
f144();
f145();
f146();
f147();
f148();
f149();
f150();
f151();
f152();
f153();
f154();
f155();
f156();
f157();
f158();
f159();
f160();
f161();
f162();
f163();
f164();
f165();
f166();
f167();
f168();
f169();
f170();
f171();
f172();
f173();
f174();
f175();
f176();
f177();
f178();
f179();
f180();
f181();
f182();
f183();
f184();
f185();
f186();
f187();
f188();
f189();
f190();
f191();
f192();
f193();
f194();
f195();
f196();
f197();
f198();
f199();
return 0;
}
|
980569.c | //this file was generated by ../../../../../scripts/onnx_generator/OperatorStubs.py
#include "operators/onnx/operator__onnx__transpose__1.h"
operator_status
operator__onnx__transpose__1__T_tensor_int8(
node_context *ctx
)
{
return OP_ENOSYS;
} |
234129.c | // RUN: %check -e %s
// this mostly checks we don't segfault on a null .sym in the expr's identifier bits
_Static_assert(sizeof(struct A { int *p; }){ ¬_declared }.p == 3, ""); // CHECK: error: undeclared identifier "not_declared"
|
323398.c |
#include "../headers/rpdb.h"
/*
* Copyright <2012> <Vincent Le Guilloux,Peter Schmidtke, Pierre Tuffery>
* Copyright <2013-2018> <Peter Schmidtke, Vincent Le Guilloux>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
## ----- GENERAL INFORMATIONS
##
## FILE rpdb.c
## AUTHORS P. Schmidtke and V. Le Guilloux
## LAST MODIFIED 01-04-08
##
## ----- SPECIFICATIONS
## ----- MODIFICATIONS HISTORY
##
## 15-09-08 (p) Modifications on allocation (casting made C++ compiler compatible)
## 01-04-08 (v) Added template for comments and creation of history
## 01-01-08 (vp) Created (random date...)
##
## ----- TODO or SUGGESTIONS
##
*/
/**
A list of HETATM to keep in each case!
REF Peter? no ref...
*/
static const char *ST_keep_hetatm[] = {
"HEA", "HBI", "BIO", "CFM", "CLP", "FES", "F3S", "FS3", "FS4", "BPH",
"BPB", "BCL", "BCB", "COB", "ZN", "FEA", "FEO", "H4B", "BH4", "BHS",
"HBL", "THB", "DDH", "DHE", "HAS", "HDD", "HDM", "HEB", "HEC", "HEO",
"HES", "HEV", "MHM", "SRM", "VER", "1FH", "2FH", "HC0", "HC1", "HF3",
"HF5", "NFS", "OMO", "PHF", "SF3", "SF4", "CFM", "CFN", "CLF", "CLP",
"CN1", "CNB", "CNF", "CUB", "CUM", "CUN", "CUO", "F3S", "FES", "FS2",
"FS3", "FS4", "FSO", "FSX", "PHO", "BH1", "CHL", "CL1", "CL2", "CLA",
"CCH", "CFO", "FE2", "FCI", "FCO", "FDC", "FEA", "FEO", "FNE", "HIF",
"OFO", "PFC", "HE5", "BAZ", "BOZ", "FE", "HEM", "HCO", "1CP", "CLN",
"COH", "CP3", "DEU", "FDD", "FDE", "FEC", "FMI", "HE5", "HEG", "HIF",
"HNI", "MMP", "MNH", "MNR", "MP1", "PC3", "PCU", "PNI", "POR", "PP9",
"MSE", "HIE", "HID", "HIP", "ACE", "FAD", "OEH", "NME", "PTH", "NDP",
"NAD", "004", "00B", "00C", "00E", "00O", "01N", "01W", "02A", "02I", "02K", "02L", "02O", "02V", "02Y", "037", "03E", "03Y", "04R", "04U", "04V", "04X", "05N", "060", "07O", "08M", "08P", "0A", "0A0", "0A1", "0A2", "0A8", "0A9", "0AA", "0AB", "0AC", "0AD", "0AF", "0AH", "0AK", "0AM", "0AP", "0AR", "0AU", "0AV", "0AZ", "0BN", "0C", "0CS", "0DA", "0DC", "0DG", "0DT", "0E5", "0EA", "0EH", "0FL", "0G", "0G5", "0GG", "0KZ", "0LF", "0QL", "0QZ", "0R8", "0RJ", "0SP", "0TD", "0TH", "0TS", "0U", "0U1", "0UH", "0UZ", "0W6", "0WZ", "0X9", "0XL", "0XO", "0XQ", "0Y8", "0Y9", "10C", "11Q", "11W", "125", "126", "127", "128", "12A", "12L", "12X", "12Y", "13E", "143", "175", "18M", "18Q", "192", "193", "19W", "1AC", "1AP", "1C3", "1CC", "1DP", "1E3", "1FC", "1G2", "1G3", "1G8", "1JM", "1L1", "1MA", "1ME", "1MG", "1MH", "1OP", "1PA", "1PI", "1PR", "1RN", "1SC", "1TL", "1TQ", "1TW", "1TX", "1TY", "1U8", "1VR", "1W5", "1WA", "1X6", "1XW", "200", "22G", "23F", "23P", "23S", "28J", "28X", "2AD", "2AG", "2AO", "2AR", "2AS", "2AT", "2AU", "2BD", "2BT", "2BU", "2CO", "2DA", "2DF", "2DM", "2DO", "2DT", "2EG", "2FE", "2FI", "2FM", "2GF", "2GT", "2HF", "2IA", "2JC", "2JF", "2JG", "2JH", "2JJ", "2JN", "2JU", "2JV", "2KK", "2KP", "2KZ", "2L5", "2L6", "2L8", "2L9", "2LA", "2LF", "2LT", "2LU", "2MA", "2MG", "2ML", "2MR", "2MT", "2MU", "2NT", "2OM", "2OR", "2OT", "2P0", "2PI", "2PR", "2QD", "2QY", "2QZ", "2R1", "2R3", "2RA", "2RX", "2SA", "2SG", "2SI", "2SO", "2ST", "2TL", "2TY", "2VA", "2XA", "2YC", "2YF", "2YG", "2YH", "2YJ", "2ZC", "30F", "30V", "31H", "31M", "31Q", "32L", "32S", "32T", "33S", "33W", "33X", "34E", "35Y", "3A5", "3AH", "3AR", "3AU", "3BY", "3CF", "3CT", "3DA", "3DR", "3EG", "3FG", "3GA", "3GL", "3K4", "3MD", "3ME", "3MU", "3MY", "3NF", "3O3", "3PM", "3PX", "3QN", "3TD", "3TY", "3WS", "3X9", "3XH", "3YM", "3ZH", "3ZL", "3ZO", "41H", "41Q", "432", "45W", "47C", "4AC", "4AF", "4AK", "4AR", "4AW", "4BF", "4CF", "4CG", "4CY", "4D4", "4DB", "4DP", "4DU", "4F3", "4FB", "4FW", "4GC", "4GJ", "4HH", "4HJ", "4HL", "4HT", "4IK", "4IN", "4J2", "4KY", "4L0", "4L8", "4LZ", "4M8", "4MF", "4NT", "4NU", "4OC", "4OP", "4OU", "4OV", "4PC", "4PD", "4PE", "4PH", "4SC", "4SU", "4TA", "4U3", "4U7", "4WQ", "50L", "50N", "56A", "574", "5A6", "5AA", "5AB", "5AT", "5BU", "5CF", "5CG", "5CM", "5CS", "5CW", "5DW", "5FA", "5FC", "5FQ", "5FU", "5GG", "5HC", "5HM", "5HP", "5HT", "5HU", "5IC", "5IT", "5IU", "5JO", "5MC", "5MD", "5MU", "5NC", "5OC", "5OH", "5PC", "5PG", "5PY", "5R5", "5SE", "5UA", "5X8", "5XU", "5ZA", "62H", "63G", "63H", "64T", "68Z", "6CL", "6CT", "6CW", "6E4", "6FC", "6FL", "6FU", "6GL", "6HA", "6HB", "6HC", "6HG", "6HN", "6HT", "6IA", "6MA", "6MC", "6MI", "6MT", "6MZ", "6OG", "6PO", "70U", "7AT", "7BG", "7DA", "7GU", "7HA", "7JA", "7MG", "7MN", "81R", "81S", "823", "8AG", "8AN", "8AZ", "8FG", "8MG", "8OG", "8SP", "999", "9AT", "9DN", "9DS", "9NE", "9NF", "9NR", "9NV", "A", "A1P", "A23", "A2L", "A2M", "A34", "A35", "A38", "A39", "A3A", "A3P", "A40", "A43", "A44", "A47", "A5L", "A5M", "A5N", "A5O", "A66", "A6A", "A6C", "A6G", "A6U", "A7E", "A8E", "A9D", "A9Z", "AA3", "AA4", "AA6", "AAB", "AAR", "AB7", "ABA", "ABR", "ABS", "ABT", "AC5", "ACA", "ACB", "ACL", "AD2", "ADD", "ADX", "AE5", "AEA", "AEI", "AET", "AF2", "AFA", "AFF", "AFG", "AGD", "AGM", "AGQ", "AGT", "AHB", "AHH", "AHO", "AHP", "AIB", "AJE", "AKL", "ALA", "ALC", "ALM", "ALN", "ALO", "ALS", "ALT", "ALY", "AN6", "AN8", "AP7", "APH", "API", "APK", "APM", "APO", "APP", "AR2", "AR4", "ARG", "ARM", "ARO", "ARV", "AS", "AS2", "AS7", "AS9", "ASA", "ASB", "ASI", "ASK", "ASL", "ASM", "ASN", "ASP", "ASQ", "ASU", "ASX", "ATD", "ATL", "ATM", "AVC", "AVN", "AYA", "AYG", "AZH", "AZK", "AZS", "AZY", "B1F", "B1P", "B2N", "B3A", "B3E", "B3K", "B3L", "B3M", "B3Q", "B3S", "B3T", "B3U", "B3X", "B3Y", "B7C", "BB6", "BB7", "BB8", "BB9", "BBC", "BCS", "BCX", "BE2", "BFD", "BG1", "BGM", "BH2", "BHD", "BIF", "BIL", "BIU", "BJH", "BL2", "BMN", "BMP", "BMQ", "BMT", "BNN", "BOE", "BP5", "BPE", "BRU", "BSE", "BT5", "BTA", "BTC", "BTK", "BTR", "BUC", "BUG", "BYR", "BZG", "C", "C12", "C1T", "C1X", "C22", "C25", "C2L", "C2N", "C2S", "C31", "C32", "C34", "C36", "C37", "C38", "C3Y", "C42", "C43", "C45", "C46", "C49", "C4R", "C4S", "C5C", "C5L", "C66", "C6C", "C6G", "C99", "CAB", "CAF", "CAR", "CAS", "CAY", "CB2", "CBR", "CBV", "CCC", "CCL", "CCS", "CCY", "CDE", "CDV", "CDW", "CEA", "CFL", "CFY", "CFZ", "CG1", "CGA", "CGH", "CGU", "CGV", "CH", "CH6", "CH7", "CHG", "CHP", "CIR", "CJO", "CLB", "CLD", "CLE", "CLG", "CLH", "CLV", "CM0", "CME", "CMH", "CML", "CMR", "CMT", "CNG", "CNU", "CP1", "CPC", "CPI", "CQ1", "CQ2", "CQR", "CR0", "CR2", "CR5", "CR7", "CR8", "CRF", "CRG", "CRK", "CRO", "CRQ", "CRU", "CRW", "CRX", "CS0", "CS1", "CS3", "CS4", "CS8", "CSA", "CSB", "CSD", "CSE", "CSF", "CSH", "CSJ", "CSK", "CSL", "CSM", "CSO", "CSP", "CSR", "CSS", "CSU", "CSW", "CSX", "CSY", "CSZ", "CTE", "CTG", "CTH", "CTT", "CUC", "CUD", "CVC", "CWD", "CWR", "CX2", "CXM", "CY0", "CY1", "CY3", "CY4", "CYA", "CYF", "CYG", "CYJ", "CYM", "CYQ", "CYR", "CYS", "CYW", "CZ2", "CZO", "CZZ", "D00", "D11", "D1P", "D2T", "D3", "D33", "D3N", "D3P", "D4M", "D4P", "DA", "DA2", "DAB", "DAH", "DAL", "DAM", "DAR", "DAS", "DBB", "DBM", "DBS", "DBU", "DBY", "DBZ", "DC", "DC2", "DCG", "DCT", "DCY", "DDE", "DDG", "DDN", "DDX", "DDZ", "DFC", "DFF", "DFG", "DFI", "DFO", "DFT", "DG", "DG8", "DGH", "DGI", "DGL", "DGN", "DGP", "DHA", "DHI", "DHL", "DHN", "DHP", "DHU", "DHV", "DI", "DI7", "DI8", "DIL", "DIR", "DIV", "DJF", "DLE", "DLS", "DLY", "DM0", "DMH", "DMK", "DMT", "DN", "DNE", "DNG", "DNL", "DNP", "DNR", "DNS", "DNW", "DO2", "DOA", "DOC", "DOH", "DON", "DPB", "DPL", "DPN", "DPP", "DPQ", "DPR", "DPY", "DRM", "DRP", "DRT", "DRZ", "DSE", "DSG", "DSN", "DSP", "DT", "DTH", "DTR", "DTY", "DU", "DUZ", "DVA", "DXD", "DXN", "DYA", "DYG", "DYL", "DYS", "DZM", "E", "E1X", "ECC", "ECX", "EDA", "EDC", "EDI", "EFC", "EHG", "EHP", "EIT", "ELY", "EME", "ENA", "ENP", "ENQ", "ESB", "ESC", "EXC", "EXY", "EYG", "EYS", "F2F", "F2Y", "F3H", "F3M", "F3N", "F3O", "F3T", "F4H", "F5H", "F6H", "FA2", "FA5", "FAG", "FAI", "FAK", "FAX", "FB5", "FB6", "FCL", "FDG", "FDL", "FFD", "FFM", "FGA", "FGL", "FGP", "FH7", "FHL", "FHO", "FHU", "FIO", "FLA", "FLE", "FLT", "FME", "FMG", "FMU", "FNU", "FOE", "FOX", "FP9", "FPK", "FPR", "FRD", "FT6", "FTR", "FTY", "FVA", "FZN", "G", "G25", "G2L", "G2S", "G31", "G32", "G33", "G35", "G36", "G38", "G42", "G46", "G47", "G48", "G49", "G4P", "G7M", "G8M", "GAO", "GAU", "GCK", "GCM", "GDO", "GDP", "GDR", "GEE", "GF2", "GFL", "GFT", "GGL", "GH3", "GHC", "GHG", "GHP", "GHW", "GL3", "GLH", "GLJ", "GLM", "GLN", "GLQ", "GLU", "GLX", "GLY", "GLZ", "GMA", "GME", "GMS", "GMU", "GN7", "GNC", "GND", "GNE", "GOM", "GPL", "GRB", "GS", "GSC", "GSR", "GSS", "GSU", "GT9", "GU0", "GU1", "GU2", "GU4", "GU5", "GU8", "GU9", "GVL", "GX1", "GYC", "GYS", "H14", "H2U", "H5M", "HAC", "HAR", "HBN", "HCL", "HCM", "HCS", "HDP", "HEU", "HFA", "HG7", "HGL", "HGM", "HGY", "HHI", "HHK", "HIA", "HIC", "HIP", "HIQ", "HIS", "HIX", "HL2", "HLU", "HLX", "HM8", "HM9", "HMF", "HMR", "HN0", "HN1", "HNC", "HOL", "HOX", "HPC", "HPE", "HPQ", "HQA", "HR7", "HRG", "HRP", "HS8", "HS9", "HSE", "HSK", "HSL", "HSO", "HSV", "HT7", "HTI", "HTN", "HTR", "HTY", "HV5", "HVA", "HY3", "HYP", "HZP", "I", "I2M", "I4G", "I58", "I5C", "IAM", "IAR", "IAS", "IC", "ICY", "IEL", "IEY", "IG", "IGL", "IGU", "IIC", "IIL", "ILE", "ILG", "ILX", "IMC", "IML", "IOR", "IOY", "IPG", "IPN", "IRN", "IT1", "IU", "IYR", "IYT", "IZO", "JDT", "JJJ", "JJK", "JJL", "JLN", "JW5", "K1R", "KAG", "KBE", "KCR", "KCX", "KCY", "KFP", "KGC", "KNB", "KOR", "KPF", "KPI", "KPY", "KST", "KWS", "KYN", "KYQ", "L2A", "L3O", "L5P", "LA2", "LAA", "LAG", "LAL", "LAY", "LBY", "LC", "LCA", "LCC", "LCG", "LCH", "LCK", "LCX", "LDH", "LE1", "LED", "LEF", "LEH", "LEI", "LEM", "LET", "LEU", "LG", "LGP", "LGY", "LHC", "LHO", "LHU", "LKC", "LLO", "LLP", "LLY", "LLZ", "LM2", "LME", "LMF", "LMQ", "LMS", "LNE", "LNM", "LP6", "LPD", "LPG", "LPH", "LPL", "LPS", "LRK", "LSO", "LTA", "LTP", "LTR", "LVG", "LVN", "LWM", "LYF", "LYH", "LYM", "LYN", "LYO", "LYR", "LYS", "LYU", "LYV", "LYX", "LYZ", "M0H", "M1G", "M2G", "M2L", "M2S", "M30", "M3L", "M3O", "M4C", "M5M", "MA6", "MA7", "MAA", "MAD", "MAI", "MBQ", "MBZ", "MC1", "MCG", "MCL", "MCS", "MCY", "MD0", "MD3", "MD5", "MD6", "MDF", "MDH", "MDJ", "MDK", "MDO", "MDQ", "MDR", "MDU", "MDV", "ME0", "ME6", "MEA", "MED", "MEG", "MEN", "MEP", "MEQ", "MET", "MEU", "MF3", "MF7", "MFC", "MFT", "MG1", "MGG", "MGN", "MGQ", "MGV", "MGY", "MH1", "MH6", "MH8", "MHL", "MHO", "MHS", "MHU", "MHV", "MHW", "MIA", "MIR", "MIS", "MK8", "MKD", "ML3", "MLE", "MLL", "MLU", "MLY", "MLZ", "MM7", "MME", "MMO", "MMT", "MND", "MNL", "MNU", "MNV", "MOD", "MOZ", "MP4", "MP8", "MPH", "MPJ", "MPQ", "MRG", "MSA", "MSE", "MSL", "MSO", "MSP", "MT2", "MTR", "MTU", "MTY", "MV9", "MVA", "MYK", "MYN", "N", "N10", "N2C", "N4S", "N5I", "N5M", "N6G", "N7P", "N80", "N8P", "NA8", "NAL", "NAM", "NB8", "NBQ", "NC1", "NCB", "NCU", "NCX", "NCY", "NDF", "NDN", "NDU", "NEM", "NEP", "NF2", "NFA", "NHL", "NIY", "NKS", "NLB", "NLE", "NLN", "NLO", "NLP", "NLQ", "NLY", "NMC", "NMM", "NMS", "NMT", "NNH", "NOT", "NP3", "NPH", "NPI", "NR1", "NRG", "NRI", "NRP", "NRQ", "NSK", "NTR", "NTT", "NTY", "NVA", "NWD", "NYB", "NYC", "NYG", "NYM", "NYS", "NZC", "NZH", "O12", "O2C", "O2G", "OAD", "OAS", "OBF", "OBS", "OCS", "OCY", "ODP", "OEM", "OFM", "OGX", "OHI", "OHS", "OHU", "OIC", "OIM", "OIP", "OLD", "OLE", "OLT", "OLZ", "OMC", "OMG", "OMH", "OMT", "OMU", "OMX", "OMY", "OMZ", "ONE", "ONH", "ONL", "ORD", "ORN", "ORQ", "OSE", "OTB", "OTH", "OTY", "OXX", "OYL", "P", "P0A", "P1L", "P1P", "P2Q", "P2T", "P2U", "P2Y", "P3Q", "P4E", "P4F", "P5P", "P9G", "PAQ", "PAS", "PAT", "PBB", "PBF", "PBT", "PCA", "PCC", "PCE", "PCS", "PDD", "PDL", "PDU", "PDW", "PE1", "PEC", "PF5", "PFF", "PG1", "PG7", "PG9", "PGN", "PGP", "PGY", "PH6", "PH8", "PHA", "PHD", "PHE", "PHI", "PHL", "PIA", "PIV", "PLJ", "PM3", "PMT", "POM", "PPN", "PPU", "PPW", "PQ1", "PR3", "PR4", "PR5", "PR7", "PR9", "PRJ", "PRK", "PRN", "PRO", "PRQ", "PRR", "PRS", "PRV", "PSH", "PST", "PSU", "PSW", "PTH", "PTM", "PTR", "PU", "PUY", "PVH", "PVL", "PVX", "PXU", "PYA", "PYH", "PYL", "PYO", "PYX", "PYY", "QAC", "QBT", "QCS", "QDS", "QFG", "QIL", "QLG", "QMM", "QPA", "QPH", "QUO", "QV4", "R", "R1A", "R2P", "R2T", "R4K", "RBD", "RC7", "RCE", "RDG", "RE0", "RE3", "RGL", "RIA", "RMP", "RON", "RPC", "RSP", "RSQ", "RT", "RT0", "RTP", "RUS", "RVX", "RZ4", "S12", "S1H", "S2C", "S2D", "S2M", "S2P", "S4A", "S4C", "S4G", "S4U", "S6G", "S8M", "SAC", "SAH", "SAR", "SAY", "SBD", "SBL", "SC", "SCH", "SCS", "SCY", "SD2", "SD4", "SDE", "SDG", "SDH", "SDP", "SE7", "SEB", "SEC", "SEE", "SEG", "SEL", "SEM", "SEN", "SEP", "SER", "SET", "SFE", "SGB", "SHC", "SHP", "SHR", "SIB", "SIC", "SLL", "SLR", "SLZ", "SMC", "SME", "SMF", "SMP", "SMT", "SNC", "SNN", "SOC", "SOS", "SOY", "SPT", "SRA", "SRZ", "SSU", "STY", "SUB", "SUI", "SUN", "SUR", "SUS", "SVA", "SVV", "SVW", "SVX", "SVY", "SVZ", "SWG", "SXE", "SYS", "T", "T0I", "T0T", "T11", "T23", "T2S", "T2T", "T31", "T32", "T36", "T37", "T38", "T39", "T3P", "T41", "T48", "T49", "T4S", "T5O", "T5S", "T64", "T66", "T6A", "TA3", "TA4", "TAF", "TAL", "TAV", "TBG", "TBM", "TC1", "TCP", "TCQ", "TCR", "TCY", "TDD", "TDF", "TDY", "TED", "TEF", "TFE", "TFF", "TFO", "TFQ", "TFR", "TFT", "TGP", "TH5", "TH6", "THC", "THO", "THP", "THR", "THX", "THZ", "TIH", "TIS", "TLB", "TLC", "TLN", "TLY", "TMB", "TMD", "TNB", "TNR", "TNY", "TOQ", "TOX", "TP1", "TPC", "TPG", "TPH", "TPJ", "TPK", "TPL", "TPO", "TPQ", "TQI", "TQQ", "TQZ", "TRF", "TRG", "TRN", "TRO", "TRP", "TRQ", "TRW", "TRX", "TRY", "TS", "TS9", "TST", "TSY", "TT", "TTD", "TTI", "TTM", "TTQ", "TTS", "TX2", "TXY", "TY1", "TY2", "TY3", "TY5", "TY8", "TY9", "TYB", "TYI", "TYJ", "TYN", "TYO", "TYQ", "TYR", "TYS", "TYT", "TYU", "TYX", "TYY", "TZB", "TZO", "U", "U25", "U2L", "U2N", "U2P", "U2X", "U31", "U33", "U34", "U36", "U37", "U3X", "U8U", "UAL", "UAR", "UBD", "UBI", "UBR", "UCL", "UD5", "UDP", "UDS", "UF0", "UF2", "UFP", "UFR", "UFT", "UGY", "UM1", "UM2", "UMA", "UMS", "UMX", "UN1", "UN2", "UNK", "UOX", "UPE", "UPS", "UPV", "UR3", "URD", "URU", "URX", "US1", "US2", "US3", "US4", "US5", "USM", "UU4", "UU5", "UVX", "V3L", "VAD", "VAF", "VAH", "VAL", "VB1", "VDL", "VET", "VH0", "VLL", "VLM", "VMS", "VOL", "VR0", "WCR", "WFP", "WLU", "WPA", "WRP", "WVL", "X", "X2W", "X4A", "X9Q", "XAD", "XAE", "XAL", "XAR", "XCL", "XCN", "XCR", "XCS", "XCT", "XCY", "XDT", "XGA", "XGL", "XGR", "XGU", "XPB", "XPL", "XPR", "XSN", "XTF", "XTH", "XTL", "XTR", "XTS", "XTY", "XUA", "XUG", "XW1", "XX1", "XXA", "XXY", "XYG", "Y", "Y28", "Y5P", "YCM", "YCO", "YCP", "YG", "YNM", "YOF", "YPR", "YPZ", "YRR", "YTH", "YYA", "YYG", "Z", "Z01", "Z3E", "Z70", "ZAD", "ZAE", "ZAL", "ZBC", "ZBU", "ZBZ", "ZCL", "ZCY", "ZDU", "ZFB", "ZGL", "ZGU", "ZHP", "ZTH", "ZU0", "ZUK", "ZYJ", "ZYK", "ZZD", "ZZJ", "ZZU"
};
static const int ST_nb_keep_hetatm = 1961; //121
/**
## FUNCTION:
rpdb_extract_pdb_atom
## SPECIFICATION:
Extract all information given in a pdb ATOM or HETATM line, and store them
in given pointers. User must therefore provide enough memory in parameter.
PDB last known standart:
COLUMNS DATA TYPE FIELD DEFINITION
1 - 6 Record name "ATOM "
7 - 11 Integer serial Atom serial number.
13 - 16 Atom name Atom name.
17 Character altLoc Alternate location indicator.
18 - 20 Residue name resName Residue name.
22 Character chainID Chain identifier.
23 - 26 Integer resSeq Residue sequence number.
27 AChar iCode Code for insertion of residues.
31 - 38 Real(8.3) x Orthogonal coordinates for X in
Angstroms
39 - 46 Real(8.3) y Orthogonal coordinates for Y in
Angstroms
47 - 54 Real(8.3) z Orthogonal coordinates for Z in
Angstroms
55 - 60 Real(6.2) occupancy Occupancy.
61 - 66 Real(6.2) tempFactor Temperature factor.
77 - 78 LString(2) element Element symbol, right-justified.
79 - 80 LString(2) charge Charge on the atom.
## PARAMETRES:
@ char *pdb_line : The PDB line containings info
@ int *atm_id : Pointer to atom ID
@ char *name : Pointer to atom name
@ char *res_name : Pointer to residue name
@ char *chain : Pointer to chain name
@ char *seg_name : Pointer to segment
@ int *res_id : Pointer to residue ID
@ char *insert : Pointer to insertion code
@ char *alt_loc : Pointer to alternate location
@ char *elem_symbol : Pointer to element symbol
@ float *x, *y, *z : Pointer to coordinates
@ float *occ : Pointer to occupency
@ float *bfactor : Pointer to b-factor
@ char *symbol : Pointer to symbol
@ float *bfactor : Pointer to charge
@ int guess_flag : Flag if elements were guessed
## RETURN:
void
*/
static const s_mm_atom_type_a mm_atom_type_ST[9] = {
// Generic type VdWradius Well depth
{ "C", 1.908, 0.086},
{ "F", 1.75, 0.061},
{ "Cl", 1.948, 0.061},
{ "Br", 2.22, 0.320},
{ "I", 2.35, 0.4},
{ "N", 1.824, 0.17},
{ "O", 1.6612, 0.21},
{ "P", 2.1, 0.2},
{ "S", 2.0, 0.25}
};
static const s_mm_atom_charge_a mm_atom_charge_ST[9] = {
// Generic type VdWradius Well depth
{ "C", 0.0},
{ "Nd", 0.2},
{ "Na", -0.2},
{ "Nc", 0.333},
{ "Oa", -0.2},
{ "Od", 0.2},
{ "Oc", -0.333},
{ "S", 0.0}
};
short get_mm_type_from_element(char *symbol) {
int i;
int cur_type = -1;
for (i = 0; i < NB_MM_TYPES; i++) {
if (mm_atom_type_ST[i].name[0] == symbol[0]) {
if (cur_type < 0) cur_type = i;
if (symbol[1] != '\0') {
if (mm_atom_type_ST[i].name[1] == symbol[1]) {
return (i);
}
}
}
}
return (cur_type);
}
s_min_max_coords *float_get_min_max_from_pdb(s_pdb *pdb) {
if (pdb) {
int z;
float minx = 50000., maxx = -50000., miny = 50000., maxy = -50000., minz = 50000., maxz = -50000.;
int n = pdb->natoms;
/*if there a no vertices in m before, first allocate some space*/
for (z = 0; z < n; z++) { /*loop over all vertices*/
/*store the positions and radius of the vertices*/
if (minx > pdb->latoms[z].x) minx = pdb->latoms[z].x;
else if (maxx < pdb->latoms[z].x)maxx = pdb->latoms[z].x;
if (miny > pdb->latoms[z].y) miny = pdb->latoms[z].y;
else if (maxy < pdb->latoms[z].y)maxy = pdb->latoms[z].y;
if (minz > pdb->latoms[z].z) minz = pdb->latoms[z].z;
else if (maxz < pdb->latoms[z].z)maxz = pdb->latoms[z].z;
}
s_min_max_coords *r = (s_min_max_coords *) my_malloc(sizeof (s_min_max_coords));
r->maxx = maxx;
r->maxy = maxy;
r->maxz = maxz;
r->minx = minx;
r->miny = miny;
r->minz = minz;
return (r);
}
return (NULL);
}
s_atom_ptr_list *init_atom_ptr_list() {
s_atom_ptr_list *ret = my_malloc(sizeof (s_atom_ptr_list));
ret->natoms = 0;
ret->latoms = (s_atm **) my_malloc(sizeof (s_atm *));
return (ret);
}
void create_coord_grid(s_pdb *pdb) {
init_coord_grid(pdb);
fill_coord_grid(pdb);
}
void fill_coord_grid(s_pdb *pdb) {
// void update_md_grid(s_mdgrid *g, s_mdgrid *refg, c_lst_pockets *pockets, s_mdparams *par) {
int xidx = 0, yidx = 0, zidx = 0; /*direct indices of the positions in the grid*/
float vx, vy, vz;
int i = 0;
s_pdb_grid *g = pdb->grid;
short n_max = 25;
/*loop over all known vertices and CALCULATE the grid positions and increment grid values by 1*/
/*important : no distance calculations are done here, thus this routine is very fast*/
for (i = 0; i < pdb->natoms; i++) {
vx = pdb->latoms[i].x;
vy = pdb->latoms[i].y;
vz = pdb->latoms[i].z;
xidx = (int) roundf((vx - g->origin[0]) / g->resolution); /*calculate the nearest grid point internal coordinates*/
yidx = (int) roundf((vy - g->origin[1]) / g->resolution);
zidx = (int) roundf((vz - g->origin[2]) / g->resolution);
//fprintf(stdout,"here %d:%d %d:%d %d:%d\n",xidx,g->nx,yidx,g->ny,zidx,g->nz);
fflush(stdout);
if (g->atom_ptr[xidx][yidx][zidx].natoms == 0) {/*TODO : continue here !! */
g->atom_ptr[xidx][yidx][zidx].latoms = (s_atm **) my_malloc(sizeof (s_atm *) * n_max);
g->atom_ptr[xidx][yidx][zidx].latoms[0] = pdb->latoms_p[i];
g->atom_ptr[xidx][yidx][zidx].natoms = 1;
} else {
// fprintf(stdout,"NUmber of atoms per coord grid point : %d\n",g->atom_ptr[xidx][yidx][zidx].natoms);
// fflush(stdout);
if (g->atom_ptr[xidx][yidx][zidx].natoms < n_max) {
fflush(stdout);
*(g->atom_ptr[xidx][yidx][zidx].latoms + g->atom_ptr[xidx][yidx][zidx].natoms) = *(pdb->latoms_p + i);
} else fprintf(stderr, "exceeding memory size for each grid element");
g->atom_ptr[xidx][yidx][zidx].natoms += 1;
}
}
}
void init_coord_grid(s_pdb *pdb) {
s_pdb_grid *g = (s_pdb_grid *) my_malloc(sizeof (s_pdb_grid));
float resolution = 5.0; //fixed for now
s_min_max_coords *mm;
mm = float_get_min_max_from_pdb(pdb);
float xmax = mm->maxx;
float ymax = mm->maxy;
float zmax = mm->maxz;
float xmin = mm->minx;
float ymin = mm->miny;
float zmin = mm->minz;
my_free(mm);
int cx, cy, cz;
float span = 5.0;
g->resolution = resolution;
g->nx = 1 + (int) (xmax + 30. * span - xmin) / (g->resolution);
g->ny = 1 + (int) (ymax + 30. * span - ymin) / (g->resolution);
g->nz = 1 + (int) (zmax + 30. * span - zmin) / (g->resolution);
g->atom_ptr = (s_atom_ptr_list ***) my_malloc(sizeof (s_atom_ptr_list **) * g->nx);
for (cx = 0; cx < g->nx; cx++) {
g->atom_ptr[cx] = (s_atom_ptr_list **) my_malloc(sizeof (s_atom_ptr_list *) * g->ny);
for (cy = 0; cy < g->ny; cy++) {
g->atom_ptr[cx][cy] = (s_atom_ptr_list *) my_malloc(sizeof (s_atom_ptr_list) * g->nz);
for (cz = 0; cz < g->nz; cz++) {
g->atom_ptr[cx][cy][cz] = *init_atom_ptr_list();
}
}
}
g->origin = (float *) my_malloc(sizeof (float) *3);
g->origin[0] = xmin - 15. * span;
g->origin[1] = ymin - 15. * span;
g->origin[2] = zmin - 15. * span;
pdb->grid = g;
}
void rpdb_extract_pdb_atom(char *pdb_line, char *type, int *atm_id, char *name,
char *alt_loc, char *res_name, char *chain,
int *res_id, char *insert,
float *x, float *y, float *z, float *occ,
float *bfactor, char *symbol, int *charge, int *guess_flag) {
/* Position: 1 2 3 4 5 6 */
/* Position: 123456789012345678901234567890123456789012345678901234567890 */
/* Record: ATOM 145 N VAL A 25 32.433 16.336 57.540 1.00 */
/* Position: 6 7 8 */
/* Position: 012345678901234567890 */
/* Record: 0 11.92 N */
int rlen = strlen(pdb_line);
char *prt,
ctmp;
/* Record type */
strncpy(type, pdb_line, 6);
/* Atom ID */
prt = pdb_line + 6;
ctmp = pdb_line[11];
pdb_line[11] = '\0';
*atm_id = atoi(prt);
pdb_line[11] = ctmp;
/* Atom name */
strncpy(name, pdb_line + 12, 4);
name[4] = '\0';
str_trim(name);
/* Alternate location identifier */
*alt_loc = pdb_line[16];
/* Residue name */
rpdb_extract_atm_resname(pdb_line, res_name);
/* Chain name */
chain[0] = pdb_line[21];
chain[1] = '\0';
/* Residue id number */
prt = pdb_line + 22;
ctmp = pdb_line[26];
pdb_line[26] = '\0';
*res_id = atoi(prt);
pdb_line[26] = ctmp;
/* Insertion code */
*insert = pdb_line[26];
/* x, y, and z coordinates, occupancy and b-factor */
rpdb_extract_atom_values(pdb_line, x, y, z, occ, bfactor);
/* Atomic element symbol (if does not exists, guess it based on
* atom name */
if (rlen >= 77) {
strncpy(symbol, pdb_line + 76, 2);
symbol[2] = '\0';
str_trim(symbol); /* remove spaces */
if (strlen(symbol) < 1) {
guess_element(name, symbol, res_name);
*guess_flag += 1;
}
} else {
guess_element(name, symbol, res_name);
*guess_flag += 1;
}
str_trim(symbol); /* remove spaces */
/* Charge */
if (rlen >= 79) {
char buf[4] = " ";
if ((pdb_line[78] == ' ' && pdb_line[79] == ' ') || pdb_line[78] == '\n') {
*charge = 0;
} else {
buf[0] = pdb_line[78];
buf[1] = pdb_line[79];
buf[2] = '\0';
*charge = (int) atoi(buf);
}
} else *charge = 0;
}
int element_in_kept_res(char *res_name) {
int i;
for (i = 0; i < ST_nb_keep_hetatm; i++) {
if (!strncmp(res_name, ST_keep_hetatm[i], 3)) return 1;
}
return 0;
}
/**
## FUNCTION:
guess_element
## SPECIFICATION:
Guess the element of the atom based on atom name. The pattern matched here
have been taken from the MOE PDB reader.
## PARAMETRES:
@ char *atom_name : The atom name
@ char *res_name : OUTPUT the element guessed
## RETURN:
void (element is the output)
*/
void guess_element(char *aname, char *element, char *res_name) {
/* Use a temporary variable for atomname, mainly to remove spaces */
char tmp[strlen(aname) + 1];
strcpy(tmp, aname);
str_trim(tmp);
char *ptmp = tmp;
/* Move to the second caracter if we find a number */
if (isdigit(tmp[0])) ptmp = ptmp + 1;
if (element_in_std_res(res_name)) {
/* Check if its a valid element for standard residues in proteins */
int index = is_valid_prot_element(ptmp, 1);
if (index != -1) {
element[0] = ptmp[0];
element[1] = '\0';
//element[2] = '\0';
return;
}
} else if (element_in_nucl_acid(res_name)) {
int index = is_valid_nucl_acid_element(ptmp, 1);
if (index != -1) {
element[0] = ptmp[0];
element[1] = '\0';
//element[2] = '\0';
return;
}
} else {
int index = is_valid_element(ptmp, 1);
if (index != -1) {
strcpy(element, ptmp);
return;
}
}
/* Here we have a special case... So take the first and second */
element[0] = ptmp[0];
element[1] = ptmp[1];
element[2] = '\0';
}
int is_N(char *aname) { /* N:'[A-G,I-L,N-Z]N#*' */
if (aname[0] == 'N' && isdigit(aname[1])) return 1;
if (aname[0] != 'H' && aname[0] != 'M' && aname[1] == 'N'
&& str_is_number(aname, 0)) return 1;
return 0;
}
int is_O(char *aname) {
/*
O:['[A-B,D-G,I-L,N-Z]O*','OP[A-C]#','CO[A-Z,0-9]*','OE##']
*/
if (aname[0] == 'O') {
/* TESTING 'OP[A-C]#' */
if (aname[1] == 'P' && (aname[2] == 'A' || aname[2] == 'B' || aname[2] == 'C')
&& isdigit(aname[3])) {
return 1;
}
/* TESTING 'OE##' */
if (aname[1] == 'E' && isdigit(aname[2]) && isdigit(aname[3])) return 1;
} else {
/* TESTING '[A-B,D-G,I-L,N-Z]O*' */
if (aname[0] != 'C' && aname[0] != 'H' && aname[0] != 'M' && aname[1] == 'O')
return 1;
/* TESTING 'CO[A-Z,0-9]*' */
if (aname[0] == 'C' && aname[1] == 'O' && aname[2] != ' ' && aname[3] != ' ')
return 1;
}
return 0;
}
/**
## FUNCTION:
rpdb_extract_atm_resname
## SPECIFICATION:
Extract the residu name for an ATOM or HETATM pdb record. To remember:
COLUMNS DATA TYPE FIELD DEFINITION
18 - 20 Residue name resName Residue name.
The memory to store the name has to be provided by the user.
## PARAMETRES:
@ char *pdb_line : The PDB line containings info
@ char *res_name : Pointer to residue name
## RETURN:
void
*/
void rpdb_extract_atm_resname(char *pdb_line, char *res_name) {
/* Position: 1 2 3 4 5 6 */
/* Position: 123456789012345678901234567890123456789012345678901234567890 */
/* Record: ATOM 145 N VAL A 25 32.433 16.336 57.540 1.00 */
/* Position: 6 7 8 */
/* Position: 012345678901234567890 */
/* Record: 0 11.92 N */
/* Residue name */
strncpy(res_name, pdb_line + 17, 4);
res_name[4] = '\0';
str_trim(res_name);
}
/**
## FUNCTION:
rpdb_extract_atm_resumber
## SPECIFICATION:
Extract the residu number for an ATOM or HETATM pdb record. To remember:
COLUMNS DATA TYPE FIELD DEFINITION
23 - 26 Residue number resSeq Residue number.
The memory to store the name has to be provided by the user.
## PARAMETRES:
@ char *pdb_line : The PDB line containings info
@ char *res_name : Pointer to residue name
## RETURN:
void
*/
int rpdb_extract_atm_resumber(char *pdb_line){
char *prt,
ctmp;
int res_id;
/* Residue id number */
prt = pdb_line + 22;
ctmp = pdb_line[26];
pdb_line[26] = '\0';
res_id = atoi(prt);
pdb_line[26] = ctmp;
return(res_id);
}
/**
## FUNCTION:
rpdb_extract_atom_values
## SPECIFICATION:
Extract coordinates, occupancy and bfactor values from a pdb ATOM or HETATM
line, and store them in given pointers.
## PARAMETRES:
@ char *pdb_line : The PDB line containings info
@ float *x, *y, *z : Pointer to coordinates
@ float *occ : Pointer to occupency
@ float *bfactor : Pointer to b-factor
## RETURN: void
*/
/**
* @description extract atom coordinates to xyz parameters from pdb_line
* @param pdb_line
* @param x
* @param y
* @param z
*/
void rpdb_extract_atom_coordinates(char *pdb_line, float *x, float *y, float *z) {
/* Position: 1 2 3 4 5 6 */
/* Position: 123456789012345678901234567890123456789012345678901234567890 */
/* Record: ATOM 145 N VAL A 25 32.433 16.336 57.540 1.00 */
/* Position: 6 7 8 */
/* Position: 012345678901234567890 */
/* Record: 0 11.92 N */
char *ptr,
ctmp;
ptr = pdb_line + 30;
ctmp = pdb_line[38];
pdb_line[38] = '\0';
*x = (float) atof(ptr);
pdb_line[38] = ctmp;
ptr = pdb_line + 38;
ctmp = pdb_line[46];
pdb_line[46] = '\0';
*y = (float) atof(ptr);
pdb_line[46] = ctmp;
ptr = pdb_line + 46;
ctmp = pdb_line[54];
pdb_line[54] = '\0';
*z = (float) atof(ptr);
pdb_line[54] = ctmp;
}
/**
## FUNCTION:
rpdb_extract_atom_values
## SPECIFICATION:
Extract coordinates, occupancy and bfactor values from a pdb ATOM or HETATM
line, and store them in given pointers.
## PARAMETRES:
@ char *pdb_line : The PDB line containings info
@ float *x, *y, *z : Pointer to coordinates
@ float *occ : Pointer to occupency
@ float *bfactor : Pointer to b-factor
## RETURN: void
*/
void rpdb_extract_atom_values(char *pdb_line, float *x, float *y, float *z,
float *occ, float *bfactor) {
/* Position: 1 2 3 4 5 6 */
/* Position: 123456789012345678901234567890123456789012345678901234567890 */
/* Record: ATOM 145 N VAL A 25 32.433 16.336 57.540 1.00 */
/* Position: 6 7 8 */
/* Position: 012345678901234567890 */
/* Record: 0 11.92 N */
char *ptr,
ctmp;
ptr = pdb_line + 30;
ctmp = pdb_line[38];
pdb_line[38] = '\0';
*x = (float) atof(ptr);
pdb_line[38] = ctmp;
ptr = pdb_line + 38;
ctmp = pdb_line[46];
pdb_line[46] = '\0';
*y = (float) atof(ptr);
pdb_line[46] = ctmp;
ptr = pdb_line + 46;
ctmp = pdb_line[54];
pdb_line[54] = '\0';
*z = (float) atof(ptr);
pdb_line[54] = ctmp;
ptr = pdb_line + 54;
ctmp = pdb_line[60];
pdb_line[60] = '\0';
*occ = (float) atof(ptr);
pdb_line[60] = ctmp;
ptr = pdb_line + 60;
ctmp = pdb_line[66];
pdb_line[66] = '\0';
*bfactor = (float) atof(ptr);
pdb_line[66] = ctmp;
}
/**
## FUNCTION:
rpdb_extract_cryst1
## SPECIFICATION:
Extract information on a box size from a pdb CRYSTL line, and store them
in given pointers.
## PARAMETRES:
@ char *pdb_line : The PDB line containings info
@ float *alpha, *beta, *gamma : Pointer to angles
@ float *A, B, C : Pointer sides length
## RETURN: void
*/
void rpdb_extract_cryst1(char *pdb_line, float *alpha, float *beta, float *gamma,
float *a, float *b, float *c) {
/* Position: 1 2 3 4 5 6 */
/* Position: 123456789012345678901234567890123456789012345678901234567890 */
/* Record: ATOM 145 N VAL A 25 32.433 16.336 57.540 1.00 */
/* Position: 6 7 8 */
/* Position: 012345678901234567890 */
/* Record: 0 11.92 N */
char ch, *s;
s = pdb_line + 6;
ch = pdb_line[15];
pdb_line[15] = '\0';
*a = (float) atof(s);
s = pdb_line + 15;
*s = ch;
ch = pdb_line[24];
pdb_line[24] = '\0';
*b = (float) atof(s);
s = pdb_line + 24;
*s = ch;
ch = pdb_line[33];
pdb_line[33] = '\0';
*c = (float) atof(s);
s = pdb_line + 33;
*s = ch;
ch = pdb_line[40];
pdb_line[40] = '\0';
*alpha = (float) atof(s);
s = pdb_line + 40;
*s = ch;
ch = pdb_line[47];
pdb_line[47] = '\0';
*beta = (float) atof(s);
s = pdb_line + 47;
*s = ch;
ch = pdb_line[54];
pdb_line[54] = '\0';
*gamma = (float) atof(s);
}
/**
## FUNCTION:
rpdb_open
## SPECIFICATION:
Open a PDB file, alloc memory for all information on this pdb, and store
several information like the number of atoms, the header, the remark...
This first reading of PDB rewinds the FILE* pointer. No coordinates are
actually read.
Hydrogens are conserved.
All HETATM are removed, except the given ligand if we have to keep it, and
important HETATM listed in the static structure at the top of this file.
## PARAMETRES:
@ const char *fpath : The pdb path.
@ const char *ligan : Ligand resname.
@ const char *keep_lig : Keep the given ligand or not?
## RETURN:
s_pdb: data containing PDB info.
*/
s_pdb* rpdb_open(char *fpath, const char *ligan, const int keep_lig, int model_number, s_fparams *par) {
s_pdb *pdb = NULL;
char buf[M_PDB_BUF_LEN],
resb[5]; //, chainb[5];
int nhetatm = 0,
natoms = 0,
natm_lig = 0;
int i;
float x, y, z;
int resnbuf=0;
int model_flag = 0; /*by default we consider that no particular model is read*/
int model_read = 0; /*flag tracking the status if a current line is read or not*/
int cur_model_count = 0; /*when reading NMR models, then count on which model you currently are*/
pdb = (s_pdb *) my_malloc(sizeof (s_pdb));
;
pdb->n_xlig_atoms = 0;
pdb->xlig_x = NULL;
pdb->xlig_y = NULL;
pdb->xlig_z = NULL;
/* Open the PDB file in read-only mode */
pdb->fpdb = fopen_pdb_check_case(fpath, "r");
if (!pdb->fpdb) {
my_free(pdb);
fprintf(stderr, "! File %s does not exist\n", fpath);
return NULL;
}
//printf("Model Number : %d\n",model_number);
if (model_number > 0) model_flag = 1; /*here we indicate that a particular model should be read only*/
while (fgets(buf, M_PDB_LINE_LEN + 2, pdb->fpdb)) {
if (!strncmp(buf, "MODEL", 5) && model_number > 0) {
cur_model_count++;
//printf("model : %d\n",cur_model_count);
if (cur_model_count == model_number) model_read = 1;
}
if (model_flag == 0 || model_read == 1) {
if (!strncmp(buf, "ATOM ", 5)) {
/* Check if this is the first occurence of this atom*/
rpdb_extract_atm_resname(buf, resb);
rpdb_extract_atom_coordinates(buf, &x, &y, &z); /*extract and double check coordinates to avoid issues with wrong coordinates*/
resnbuf=rpdb_extract_atm_resumber(buf);
if ((buf[16] == ' ' || buf[16] == 'A') && x < 9990 && y < 9990 && z < 9990) {
/* Atom entry: check if there is a ligand in there (just in case)... */
if (ligan && strlen(ligan) > 1 && ligan[0] == resb[0] && ligan[1] == resb[1]
&& ligan[2] == resb[2]) {
if (keep_lig) {
natm_lig++;
natoms++;
}
} else if (ligan && strlen(ligan) == 1 && buf[21] == ligan[0]) { /*here we have a protein chain defined as ligand...a bit more complex then*/
if (keep_lig) {
natm_lig++;
natoms++;
}
} else {
natoms++;
}
/*handle explicit ligand input here*/
if (par->xlig_resnumber>-1) {
// if (resb[0] == par->xlig_resname[0] && resb[1] == par->xlig_resname[1] && resb[2] == par->xlig_resname[2]) {
//fprintf(stdout,"%s\t%s\n",buf[16],par->xlig_chain_code);
if (buf[21] == par->xlig_chain_code[0] && resnbuf == par->xlig_resnumber && par->xlig_resname[0] == resb[0] && par->xlig_resname[1] == resb[1] && par->xlig_resname[2] == resb[2]) {
pdb->n_xlig_atoms++;
fprintf(stdout,"%d\n",pdb->n_xlig_atoms);
}
}
}
} else if (!strncmp(buf, "HETATM", 6)) {
/*Check again for the first occurence*/
rpdb_extract_atom_coordinates(buf, &x, &y, &z); /*extract and double check coordinates to avoid issues with wrong coordinates*/
resnbuf=rpdb_extract_atm_resumber(buf);
if ((buf[16] == ' ' || buf[16] == 'A') && x < 9990 && y < 9990 && z < 9990) {
/* Hetatom entry: check if there is a ligand in there too... */
rpdb_extract_atm_resname(buf, resb);
if (ligan && strlen(ligan) > 1 && keep_lig && ligan[0] == resb[0] && ligan[1] == resb[1]
&& ligan[2] == resb[2]) {
natm_lig++;
natoms++;
} else if (ligan && strlen(ligan) == 1 && ligan[0] == buf[21]) {
if (keep_lig) natm_lig++;
natoms++;
} else {
/* Keep specific HETATM given in the static list ST_keep_hetatm */
if (keep_lig && !ligan && strncmp(resb, "HOH", 3) && strncmp(resb, "WAT", 3) && strncmp(resb, "TIP", 3)) {
natoms++;
nhetatm++;
} else {
for (i = 0; i < ST_nb_keep_hetatm; i++) {
if (ST_keep_hetatm[i][0] == resb[0] && ST_keep_hetatm[i][1]
== resb[1] && ST_keep_hetatm[i][2] == resb[2]) {
nhetatm++;
natoms++;
break;
}
}
}
}
/*handle explicit ligand input here*/
if (par->xlig_resnumber>-1) {
if (buf[21] == par->xlig_chain_code[0] && resnbuf == par->xlig_resnumber && par->xlig_resname[0] == resb[0] && par->xlig_resname[1] == resb[1] && par->xlig_resname[2] == resb[2]) {
pdb->n_xlig_atoms++;
}
}
}
}/*
else if (!strncmp(buf, "HEADER", 6))
strncpy(pdb->header, buf, M_PDB_BUF_LEN) ;
*/
else if (model_read == 1 && !strncmp(buf, "ENDMDL", 6)) model_read = 0;
else if (model_number == 0 && !strncmp(buf, "END", 3)) break;
}
}
if (pdb->n_xlig_atoms) {
pdb->xlig_x = (float *) my_malloc(sizeof (float )*pdb->n_xlig_atoms);
pdb->xlig_y = (float *)my_malloc(sizeof (float )*pdb->n_xlig_atoms);
pdb->xlig_z = (float *)my_malloc(sizeof (float )*pdb->n_xlig_atoms);
}
if (natoms == 0) {
fprintf(stderr, "! File '%s' contains no atoms...\n", fpath);
my_free(pdb);
return NULL;
}
/* Alloc needed memory */
pdb->latoms = (s_atm*) my_calloc(natoms, sizeof (s_atm));
pdb->latoms_p = (s_atm**) my_calloc(natoms, sizeof (s_atm*));
if (nhetatm > 0) pdb->lhetatm = (s_atm**) my_calloc(nhetatm, sizeof (s_atm*));
else pdb->lhetatm = NULL;
if (natm_lig > 0) pdb->latm_lig = (s_atm**) my_calloc(natm_lig, sizeof (s_atm*));
else pdb->latm_lig = NULL;
pdb->natoms = natoms;
pdb->nhetatm = nhetatm;
pdb->natm_lig = natm_lig;
strcpy(pdb->fname, fpath);
rewind(pdb->fpdb);
return pdb;
}
int get_number_of_h_atoms(s_pdb *pdb) {
int i, nb_h = 0;
s_atm *ca = NULL;
for (i = 0; i < pdb->natoms; i++) {
ca = (pdb->latoms) + i;
if (strcmp(ca->symbol, "H") == 0) nb_h++;
}
return (nb_h);
}
/**
## FUNCTION:
rpdb_read
## SPECIFICATION:
Read and store information on atoms for a pdb file.
Curently:
- Hydrogens present in the PDB are kept
- HETATM are ignored except for specific cofactor, small molecule...
listed in ST_keep_hetatm variable, and for a given ligand, defined by
its resname.
- Solvent molecules are ignored
## PARAMETRES:
@ s_pdb *pdb : The structure to fill
@ const char *ligand : The ligand resname
@ const char *keep_lig : Keep the given ligand or not?
## RETURN:
*/
void rpdb_read(s_pdb *pdb, const char *ligan, const int keep_lig, int model_number, s_fparams *params) {
int i,
iatoms,
ihetatm,
iatm_lig,
ligfound;
char pdb_line[M_PDB_BUF_LEN],
resb[5]; /* Buffer for the current residue name */
int model_flag = 0; /*by default we consider that no particular model is read*/
int model_read = 0; /*flag tracking the status if a current line is read or not*/
int cur_model_count = 0; /*when reading NMR models, then count on which model you currently are*/
s_atm *atom = NULL;
s_atm *atoms = pdb->latoms;
s_atm **atoms_p = pdb->latoms_p;
s_atm **atm_lig = pdb->latm_lig;
int guess_flag = 0;
iatoms = 0;
int i_explicit_ligand_atom = 0; //counter to know on which atom of the ligand we are to define an explicit pocket
ihetatm = 0;
iatm_lig = 0;
ligfound = 0;
int resnbuf=0;
float tmpx, tmpy, tmpz;
/* Loop over the pdb file */
if (model_number > 0) model_flag = 1; /*here we indicate that a particular model should be read only*/
while (fgets(pdb_line, M_PDB_LINE_LEN + 2, pdb->fpdb)) {
if (!strncmp(pdb_line, "MODEL", 5) && model_number > 0) {
cur_model_count++;
if (cur_model_count == model_number) model_read = 1;
}
if (model_flag == 0 || model_read == 1) {
if (strncmp(pdb_line, "ATOM ", 5) == 0) {
rpdb_extract_atom_coordinates(pdb_line, &tmpx, &tmpy, &tmpz); /*extract and double check coordinates to avoid issues with wrong coordinates*/
if ((pdb_line[16] == ' ' || pdb_line[16] == 'A') && tmpx < 9990 && tmpy < 9990 && tmpz < 9990) { /*if within first occurence*/
/* Store ATOM entry */
rpdb_extract_atm_resname(pdb_line, resb);
resnbuf=rpdb_extract_atm_resumber(pdb_line);
if (pdb->n_xlig_atoms) {
if (pdb_line[21] == params->xlig_chain_code[0] && resnbuf == params->xlig_resnumber && params->xlig_resname[0] == resb[0] && params->xlig_resname[1] == resb[1] && params->xlig_resname[2] == resb[2]) {
rpdb_extract_atom_coordinates(pdb_line,(pdb->xlig_x+i_explicit_ligand_atom),(pdb->xlig_y+i_explicit_ligand_atom),(pdb->xlig_z+i_explicit_ligand_atom));
i_explicit_ligand_atom++;
}
}
/* Check if the desired ligand is in such an entry */
if (ligan && strlen(ligan) > 1 && ligan[0] == resb[0] && ligan[1] == resb[1]
&& ligan[2] == resb[2]) {
if (keep_lig) {
atom = atoms + iatoms;
/* Read atom information */
rpdb_extract_pdb_atom(pdb_line, atom->type, &(atom->id),
atom->name, &(atom->pdb_aloc), atom->res_name,
atom->chain, &(atom->res_id), &(atom->pdb_insert),
&(atom->x), &(atom->y), &(atom->z),
&(atom->occupancy), &(atom->bfactor), atom->symbol,
&(atom->charge), &guess_flag);
/* Store additional information not given in the pdb */
atom->mass = pte_get_mass(atom->symbol);
atom->radius = pte_get_vdw_ray(atom->symbol);
atom->electroneg = pte_get_enegativity(atom->symbol);
atom->sort_x = -1;
atoms_p[iatoms] = atom;
iatoms++;
atm_lig[iatm_lig] = atom;
iatm_lig++;
ligfound = 1;
}
} else if (ligan && strlen(ligan) == 1 && pdb_line[21] == ligan[0]) { /*here we have a protein chain defined as ligand...a bit more complex then*/
if (keep_lig) {
atom = atoms + iatoms;
/* Read atom information */
rpdb_extract_pdb_atom(pdb_line, atom->type, &(atom->id),
atom->name, &(atom->pdb_aloc), atom->res_name,
atom->chain, &(atom->res_id), &(atom->pdb_insert),
&(atom->x), &(atom->y), &(atom->z),
&(atom->occupancy), &(atom->bfactor), atom->symbol,
&(atom->charge), &guess_flag);
/* Store additional information not given in the pdb */
atom->mass = pte_get_mass(atom->symbol);
atom->radius = pte_get_vdw_ray(atom->symbol);
atom->electroneg = pte_get_enegativity(atom->symbol);
atom->sort_x = -1;
atoms_p[iatoms] = atom;
iatoms++;
atm_lig[iatm_lig] = atom;
iatm_lig++;
ligfound = 1;
}
} else {
/* A simple atom not supposed to be stored as a ligand */
atom = atoms + iatoms;
rpdb_extract_pdb_atom(pdb_line, atom->type, &(atom->id),
atom->name, &(atom->pdb_aloc), atom->res_name,
atom->chain, &(atom->res_id), &(atom->pdb_insert),
&(atom->x), &(atom->y), &(atom->z), &(atom->occupancy),
&(atom->bfactor), atom->symbol, &(atom->charge), &guess_flag);
/* Store additional information not given in the pdb */
atom->mass = pte_get_mass(atom->symbol);
atom->radius = pte_get_vdw_ray(atom->symbol);
atom->electroneg = pte_get_enegativity(atom->symbol);
atom->sort_x = -1;
atoms_p[iatoms] = atom;
iatoms++;
}
}
} else if (strncmp(pdb_line, "HETATM", 6) == 0) {
rpdb_extract_atom_coordinates(pdb_line, &tmpx, &tmpy, &tmpz); /*extract and double check coordinates to avoid issues with wrong coordinates*/
if ((pdb_line[16] == ' ' || pdb_line[16] == 'A') && tmpx < 9990 && tmpy < 9990 && tmpz < 9990) {/*first occurence*/
/* Check HETATM entry */
rpdb_extract_atm_resname(pdb_line, resb);
resnbuf=rpdb_extract_atm_resumber(pdb_line);
if (pdb->n_xlig_atoms) {
if (pdb_line[21] == params->xlig_chain_code[0] && resnbuf == params->xlig_resnumber && params->xlig_resname[0] == resb[0] && params->xlig_resname[1] == resb[1] && params->xlig_resname[2] == resb[2]) {
//if (params->xlig_resname[0] == resb[0] && params->xlig_resname[1] == resb[1] && params->xlig_resname[2] == resb[2]) {
rpdb_extract_atom_coordinates(pdb_line,(pdb->xlig_x+i_explicit_ligand_atom),(pdb->xlig_y+i_explicit_ligand_atom),(pdb->xlig_z+i_explicit_ligand_atom));
i_explicit_ligand_atom++;
}
}
//fflush(stdout);
/* Check if the desired ligand is in HETATM entry */
if (ligan && strlen(ligan) > 1 && keep_lig && ligan[0] == resb[0] && ligan[1] == resb[1]
&& ligan[2] == resb[2]) {
atom = atoms + iatoms;
rpdb_extract_pdb_atom(pdb_line, atom->type, &(atom->id),
atom->name, &(atom->pdb_aloc), atom->res_name,
atom->chain, &(atom->res_id), &(atom->pdb_insert),
&(atom->x), &(atom->y), &(atom->z), &(atom->occupancy),
&(atom->bfactor), atom->symbol, &(atom->charge), &guess_flag);
/* Store additional information not given in the pdb */
atom->mass = pte_get_mass(atom->symbol);
atom->radius = pte_get_vdw_ray(atom->symbol);
atom->electroneg = pte_get_enegativity(atom->symbol);
atom->sort_x = -1;
atoms_p[iatoms] = atom;
atm_lig[iatm_lig] = atom;
iatm_lig++;
iatoms++;
ligfound = 1;
} else if (ligan && strlen(ligan) == 1 && ligan[0] == pdb_line[21]) {
if (keep_lig) {
atom = atoms + iatoms;
rpdb_extract_pdb_atom(pdb_line, atom->type, &(atom->id),
atom->name, &(atom->pdb_aloc), atom->res_name,
atom->chain, &(atom->res_id), &(atom->pdb_insert),
&(atom->x), &(atom->y), &(atom->z), &(atom->occupancy),
&(atom->bfactor), atom->symbol, &(atom->charge), &guess_flag);
/* Store additional information not given in the pdb */
atom->mass = pte_get_mass(atom->symbol);
atom->radius = pte_get_vdw_ray(atom->symbol);
atom->electroneg = pte_get_enegativity(atom->symbol);
atom->sort_x = -1;
atoms_p[iatoms] = atom;
atm_lig[iatm_lig] = atom;
iatm_lig++;
iatoms++;
ligfound = 1;
}
} else if (pdb->lhetatm) {
/* Keep specific HETATM given in the static list ST_keep_hetatm. */
if (keep_lig && !ligan && strncmp(resb, "HOH", 3) && strncmp(resb, "WAT", 3) && strncmp(resb, "TIP", 3)) {
atom = atoms + iatoms;
rpdb_extract_pdb_atom(pdb_line, atom->type, &(atom->id),
atom->name, &(atom->pdb_aloc), atom->res_name,
atom->chain, &(atom->res_id), &(atom->pdb_insert),
&(atom->x), &(atom->y), &(atom->z),
&(atom->occupancy), &(atom->bfactor),
atom->symbol, &(atom->charge), &guess_flag);
/* Store additional information not given in the pdb */
atom->mass = pte_get_mass(atom->symbol);
atom->radius = pte_get_vdw_ray(atom->symbol);
atom->electroneg = pte_get_enegativity(atom->symbol);
atom->sort_x = -1;
atoms_p[iatoms] = atom;
pdb->lhetatm[ihetatm] = atom;
ihetatm++;
iatoms++;
} else {
for (i = 0; i < ST_nb_keep_hetatm; i++) {
if (ST_keep_hetatm[i][0] == resb[0] && ST_keep_hetatm[i][1]
== resb[1] && ST_keep_hetatm[i][2] == resb[2]) {
atom = atoms + iatoms;
rpdb_extract_pdb_atom(pdb_line, atom->type, &(atom->id),
atom->name, &(atom->pdb_aloc), atom->res_name,
atom->chain, &(atom->res_id), &(atom->pdb_insert),
&(atom->x), &(atom->y), &(atom->z),
&(atom->occupancy), &(atom->bfactor),
atom->symbol, &(atom->charge), &guess_flag);
/* Store additional information not given in the pdb */
atom->mass = pte_get_mass(atom->symbol);
atom->radius = pte_get_vdw_ray(atom->symbol);
atom->electroneg = pte_get_enegativity(atom->symbol);
atom->sort_x = -1;
atoms_p[iatoms] = atom;
pdb->lhetatm[ihetatm] = atom;
ihetatm++;
iatoms++;
break;
}
}
}
}
}
} else if (strncmp(pdb_line, "CRYST1", 6) == 0) {
rpdb_extract_cryst1(pdb_line, &(pdb->alpha), &(pdb->beta), &(pdb->gamma),
&(pdb->A), &(pdb->B), &(pdb->C));
} else if (model_read == 1 && !strncmp(pdb_line, "ENDMDL", 6)) model_read = 0;
else if (model_number == 0 && !strncmp(pdb_line, "END ", 3)) break;
}
}
pdb->avg_bfactor = 0.0;
for (i = 0; i < iatoms; i++) {
atom = atoms + i;
atom->a0 = 0.0;
atom->dA = 0.0;
atom->abpa_sourrounding_prob = 0.0;
atom->abpa = 0;
pdb->avg_bfactor += atom->bfactor;
atom->ff_charge = 0.0;
atom->ff_mass = 0.0;
atom->ff_radius = 0.0;
atom->ff_well_depth = 0.0;
atom->ff_well_depth_set = 0;
}
int num_h_atoms = get_number_of_h_atoms(pdb);
pdb->avg_bfactor /= (iatoms - num_h_atoms);
// pdb->avg_bfactor=0.0;
/*if(guess_flag>0) {
fprintf(stderr, ">! Warning: You did not provide a standard PDB file.\nElements were guessed by fpocket, because not provided in the PDB file. \nThere is no guarantee on the results!\n");
}*/
if (ligan && keep_lig && (ligfound == 0 || pdb->natm_lig <= 0)) {
fprintf(stderr, ">! Warning: ligand '%s' not found in the pdb...\n", ligan);
if (pdb->latm_lig) fprintf(stderr, "! Ligand list is not NULL however...\n");
if (ligfound == 1) fprintf(stderr, "! And ligfound == 1!! :-/\n");
} else if (ligfound == 1 && iatm_lig <= 0) {
fprintf(stderr, ">! Warning: ligand '%s' has been detected but no atoms \
has been stored!\n", ligan);
} else if ((ligfound == 1 && pdb->natm_lig <= 0) || (pdb->natm_lig <= 0
&& iatm_lig > 0)) {
fprintf(stderr, ">! Warning: ligand '%s' has been detected in rpdb_read \
but not in rpdb_open!\n", ligan);
}
}
void rpdb_print(s_pdb * pdb) {
int i;
fprintf(stdout, "PDB file path: %s\n", pdb->fname);
fprintf(stdout, "Number of atoms : %d\n", pdb->natoms);
fprintf(stdout, "NUmber of HETATMS : %d\n", pdb->nhetatm);
fprintf(stdout, "Number of ligand atoms : %d\n", pdb->natm_lig);
for (i = 0; i < pdb->natoms; i++) {
fprintf(stdout, "Atom %d: %f %f %f\t", pdb->latoms[i].id, pdb->latoms[i].x, pdb->latoms[i].y, pdb->latoms[i].z);
}
}
/**
## FUNCTION:
free_pdb_atoms
## SPECIFICATION:
Free memory for s_pdb structure
## PARAMETRES:
@ s_pdb *pdb: pdb struct to free
## RETURN:
void
*/
void free_pdb_atoms(s_pdb * pdb) {
if (pdb) {
if (pdb->lhetatm) {
my_free(pdb->lhetatm);
pdb->lhetatm = NULL;
}
if (pdb->latoms) {
my_free(pdb->latoms);
pdb->latoms = NULL;
}
if (pdb->latm_lig) {
my_free(pdb->latm_lig);
pdb->latm_lig = NULL;
}
if (pdb->fpdb) {
fclose(pdb->fpdb);
pdb->fpdb = NULL;
}
if (pdb->latoms_p) {
my_free(pdb->latoms_p);
pdb->latoms_p = NULL;
}
my_free(pdb);
}
}
|
182704.c | // SPDX-License-Identifier: BSD-2-Clause
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*/
#include "tomcrypt_private.h"
#ifdef LTC_MDH
/**
Import a DH key from a binary packet
@param in The packet to read
@param inlen The length of the input packet
@param key [out] Where to import the key to
@return CRYPT_OK if successful, on error all allocated memory is freed automatically
*/
int dh_import(const unsigned char *in, unsigned long inlen, dh_key *key)
{
unsigned char flags[1];
int err;
unsigned long version;
LTC_ARGCHK(in != NULL);
LTC_ARGCHK(key != NULL);
/* init */
if ((err = mp_init_multi(&key->x, &key->y, &key->base, &key->prime, NULL)) != CRYPT_OK) {
return err;
}
/* find out what type of key it is */
err = der_decode_sequence_multi(in, inlen,
LTC_ASN1_SHORT_INTEGER, 1UL, &version,
LTC_ASN1_BIT_STRING, 1UL, &flags,
LTC_ASN1_EOL, 0UL, NULL);
if (err != CRYPT_OK && err != CRYPT_INPUT_TOO_LONG) {
goto error;
}
if (version == 0) {
if (flags[0] == 1) {
key->type = PK_PRIVATE;
if ((err = der_decode_sequence_multi(in, inlen,
LTC_ASN1_SHORT_INTEGER, 1UL, &version,
LTC_ASN1_BIT_STRING, 1UL, flags,
LTC_ASN1_INTEGER, 1UL, key->prime,
LTC_ASN1_INTEGER, 1UL, key->base,
LTC_ASN1_INTEGER, 1UL, key->x,
LTC_ASN1_EOL, 0UL, NULL)) != CRYPT_OK) {
goto error;
}
/* compute public key: y = (base ^ x) mod prime */
if ((err = mp_exptmod(key->base, key->x, key->prime, key->y)) != CRYPT_OK) {
goto error;
}
}
else if (flags[0] == 0) {
key->type = PK_PUBLIC;
if ((err = der_decode_sequence_multi(in, inlen,
LTC_ASN1_SHORT_INTEGER, 1UL, &version,
LTC_ASN1_BIT_STRING, 1UL, flags,
LTC_ASN1_INTEGER, 1UL, key->prime,
LTC_ASN1_INTEGER, 1UL, key->base,
LTC_ASN1_INTEGER, 1UL, key->y,
LTC_ASN1_EOL, 0UL, NULL)) != CRYPT_OK) {
goto error;
}
}
else {
err = CRYPT_INVALID_PACKET;
goto error;
}
}
else {
err = CRYPT_INVALID_PACKET;
goto error;
}
/* check public key */
if ((err = dh_check_pubkey(key)) != CRYPT_OK) {
goto error;
}
return CRYPT_OK;
error:
dh_free(key);
return err;
}
#endif /* LTC_MDH */
/* ref: $Format:%D$ */
/* git commit: $Format:%H$ */
/* commit time: $Format:%ai$ */
|
958625.c | #include QMK_KEYBOARD_H
// Helpful defines
const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = {
[0] = LAYOUT
(KC_GESC, KC_Q, KC_W, KC_E, KC_R, KC_T, KC_Y, KC_U, KC_I, KC_O, KC_P, KC_BSPC,
LT(1,KC_TAB), KC_A, KC_S, KC_D, KC_F, KC_G, KC_H, KC_J, KC_K, KC_L, KC_SCLN, LT(1,KC_QUOT),
KC_LSPO, KC_Z, KC_X, KC_C, KC_V, KC_B, KC_N, KC_M, KC_COMM, KC_DOT, KC_SLSH, KC_RSPC,
KC_LCTL, KC_LALT, KC_LGUI, KC_ENT, KC_SPC, TG(2), LT(3,KC_APP), KC_DEL),
[1] = LAYOUT
(KC_CAPS, KC_PGUP, KC_UP, KC_PGDN, KC_INS, KC_HOME, KC_UNDS, KC_P7, KC_P8, KC_P9, KC_EQL, KC_TRNS,
KC_TRNS, KC_LEFT, KC_DOWN, KC_RGHT, KC_DEL, KC_END, KC_PMNS, KC_P4, KC_P5, KC_P6, KC_PPLS, KC_TRNS,
KC_MUTE, KC_VOLD, KC_VOLU, KC_MPLY, KC_MPRV, KC_MNXT, KC_PAST, KC_P1, KC_P2, KC_P3, KC_PSLS, KC_NLCK,
KC_TRNS, KC_TRNS, KC_MSTP, KC_PENT, KC_P0, KC_PDOT, KC_APP, KC_TRNS),
[2] = LAYOUT
(KC_TRNS, KC_F1, KC_F2, KC_F3, KC_F4, KC_F5, KC_F6, KC_F7, KC_F8, KC_F9, KC_F10, KC_TRNS,
KC_TRNS, KC_1, KC_2, KC_3, KC_4, KC_5, KC_6, KC_7, KC_8, KC_9, KC_0, KC_TRNS,
KC_TILD, KC_EXLM, KC_AT, KC_HASH, KC_DLR, KC_PERC, KC_CIRC, KC_AMPR, KC_ASTR, KC_LPRN, KC_RPRN, KC_TRNS,
KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_F11, KC_F12),
[3] = LAYOUT
(KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_LCBR, KC_RCBR, KC_TRNS,
KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_LBRC, KC_RBRC, KC_PIPE,
KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, KC_LPRN, KC_RPRN, KC_TRNS,
BL_TOGG, BL_DEC, BL_INC, KC_TRNS, KC_TRNS, KC_TRNS, KC_TRNS, RESET)
};
|
851650.c | /***************************************************************************//**
* @file
* @brief CMSIS Compatible EFM32GG startup file in C for IAR EWARM
* @version 5.8.0
*******************************************************************************
* # License
* <b>Copyright 2019 Silicon Laboratories Inc. www.silabs.com</b>
*******************************************************************************
*
* SPDX-License-Identifier: Zlib
*
* The licensor of this software is Silicon Laboratories Inc.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*
******************************************************************************/
#include <stdbool.h>
#include "em_device.h" /* The correct device header file. */
#pragma language=extended
#pragma segment="CSTACK"
/* IAR start function */
extern void __iar_program_start(void);
/* CMSIS init function */
extern void SystemInit(void);
/* Auto defined by linker */
extern unsigned char CSTACK$$Limit;
__weak void Reset_Handler(void)
{
SystemInit();
__iar_program_start();
}
/* Provide a dummy value for the sl_app_properties symbol. */
void sl_app_properties(void); /* Prototype to please MISRA checkers. */
__weak void sl_app_properties(void)
{
}
__weak void NMI_Handler(void)
{
while (true) {
}
}
__weak void HardFault_Handler(void)
{
while (true) {
}
}
__weak void MemManage_Handler(void)
{
while (true) {
}
}
__weak void BusFault_Handler(void)
{
while (true) {
}
}
__weak void UsageFault_Handler(void)
{
while (true) {
}
}
__weak void SVC_Handler(void)
{
while (true) {
}
}
__weak void DebugMon_Handler(void)
{
while (true) {
}
}
__weak void PendSV_Handler(void)
{
while (true) {
}
}
__weak void SysTick_Handler(void)
{
while (true) {
}
}
__weak void DMA_IRQHandler(void)
{
while (true) {
}
}
__weak void GPIO_EVEN_IRQHandler(void)
{
while (true) {
}
}
__weak void TIMER0_IRQHandler(void)
{
while (true) {
}
}
__weak void USART0_RX_IRQHandler(void)
{
while (true) {
}
}
__weak void USART0_TX_IRQHandler(void)
{
while (true) {
}
}
__weak void USB_IRQHandler(void)
{
while (true) {
}
}
__weak void ACMP0_IRQHandler(void)
{
while (true) {
}
}
__weak void ADC0_IRQHandler(void)
{
while (true) {
}
}
__weak void DAC0_IRQHandler(void)
{
while (true) {
}
}
__weak void I2C0_IRQHandler(void)
{
while (true) {
}
}
__weak void I2C1_IRQHandler(void)
{
while (true) {
}
}
__weak void GPIO_ODD_IRQHandler(void)
{
while (true) {
}
}
__weak void TIMER1_IRQHandler(void)
{
while (true) {
}
}
__weak void TIMER2_IRQHandler(void)
{
while (true) {
}
}
__weak void TIMER3_IRQHandler(void)
{
while (true) {
}
}
__weak void USART1_RX_IRQHandler(void)
{
while (true) {
}
}
__weak void USART1_TX_IRQHandler(void)
{
while (true) {
}
}
__weak void LESENSE_IRQHandler(void)
{
while (true) {
}
}
__weak void USART2_RX_IRQHandler(void)
{
while (true) {
}
}
__weak void USART2_TX_IRQHandler(void)
{
while (true) {
}
}
__weak void UART0_RX_IRQHandler(void)
{
while (true) {
}
}
__weak void UART0_TX_IRQHandler(void)
{
while (true) {
}
}
__weak void UART1_RX_IRQHandler(void)
{
while (true) {
}
}
__weak void UART1_TX_IRQHandler(void)
{
while (true) {
}
}
__weak void LEUART0_IRQHandler(void)
{
while (true) {
}
}
__weak void LEUART1_IRQHandler(void)
{
while (true) {
}
}
__weak void LETIMER0_IRQHandler(void)
{
while (true) {
}
}
__weak void PCNT0_IRQHandler(void)
{
while (true) {
}
}
__weak void PCNT1_IRQHandler(void)
{
while (true) {
}
}
__weak void PCNT2_IRQHandler(void)
{
while (true) {
}
}
__weak void RTC_IRQHandler(void)
{
while (true) {
}
}
__weak void BURTC_IRQHandler(void)
{
while (true) {
}
}
__weak void CMU_IRQHandler(void)
{
while (true) {
}
}
__weak void VCMP_IRQHandler(void)
{
while (true) {
}
}
__weak void LCD_IRQHandler(void)
{
while (true) {
}
}
__weak void MSC_IRQHandler(void)
{
while (true) {
}
}
__weak void AES_IRQHandler(void)
{
while (true) {
}
}
__weak void EBI_IRQHandler(void)
{
while (true) {
}
}
__weak void EMU_IRQHandler(void)
{
while (true) {
}
}
typedef union {
void (*pFunc)(void);
void *topOfStack;
} tVectorEntry;
extern const tVectorEntry __vector_table[];
#pragma data_alignment=256
#pragma location = ".intvec"
const tVectorEntry __vector_table[] = {
{ .topOfStack = &CSTACK$$Limit }, /* With IAR, the CSTACK is defined via */
/* project options settings */
{ Reset_Handler },
{ NMI_Handler },
{ HardFault_Handler },
{ MemManage_Handler },
{ BusFault_Handler },
{ UsageFault_Handler },
{ 0 },
{ 0 },
{ 0 },
{ 0 },
{ SVC_Handler },
{ DebugMon_Handler },
{ sl_app_properties },
{ PendSV_Handler },
{ SysTick_Handler },
{ DMA_IRQHandler }, /* 0 */
{ GPIO_EVEN_IRQHandler }, /* 1 */
{ TIMER0_IRQHandler }, /* 2 */
{ USART0_RX_IRQHandler }, /* 3 */
{ USART0_TX_IRQHandler }, /* 4 */
{ USB_IRQHandler }, /* 5 */
{ ACMP0_IRQHandler }, /* 6 */
{ ADC0_IRQHandler }, /* 7 */
{ DAC0_IRQHandler }, /* 8 */
{ I2C0_IRQHandler }, /* 9 */
{ I2C1_IRQHandler }, /* 10 */
{ GPIO_ODD_IRQHandler }, /* 11 */
{ TIMER1_IRQHandler }, /* 12 */
{ TIMER2_IRQHandler }, /* 13 */
{ TIMER3_IRQHandler }, /* 14 */
{ USART1_RX_IRQHandler }, /* 15 */
{ USART1_TX_IRQHandler }, /* 16 */
{ LESENSE_IRQHandler }, /* 17 */
{ USART2_RX_IRQHandler }, /* 18 */
{ USART2_TX_IRQHandler }, /* 19 */
{ UART0_RX_IRQHandler }, /* 20 */
{ UART0_TX_IRQHandler }, /* 21 */
{ UART1_RX_IRQHandler }, /* 22 */
{ UART1_TX_IRQHandler }, /* 23 */
{ LEUART0_IRQHandler }, /* 24 */
{ LEUART1_IRQHandler }, /* 25 */
{ LETIMER0_IRQHandler }, /* 26 */
{ PCNT0_IRQHandler }, /* 27 */
{ PCNT1_IRQHandler }, /* 28 */
{ PCNT2_IRQHandler }, /* 29 */
{ RTC_IRQHandler }, /* 30 */
{ BURTC_IRQHandler }, /* 31 */
{ CMU_IRQHandler }, /* 32 */
{ VCMP_IRQHandler }, /* 33 */
{ LCD_IRQHandler }, /* 34 */
{ MSC_IRQHandler }, /* 35 */
{ AES_IRQHandler }, /* 36 */
{ EBI_IRQHandler }, /* 37 */
{ EMU_IRQHandler }, /* 38 */
};
|
876116.c | /* Compressed section support (intended for debug sections).
Copyright 2008, 2010, 2011, 2012
Free Software Foundation, Inc.
This file is part of BFD, the Binary File Descriptor library.
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., 51 Franklin Street - Fifth Floor, Boston,
MA 02110-1301, USA. */
#include "sysdep.h"
#include "bfd.h"
#include "libbfd.h"
#ifdef HAVE_ZLIB_H
#include <zlib.h>
#endif
#ifdef HAVE_ZLIB_H
static bfd_boolean
decompress_contents (bfd_byte *compressed_buffer,
bfd_size_type compressed_size,
bfd_byte *uncompressed_buffer,
bfd_size_type uncompressed_size)
{
z_stream strm;
int rc;
/* It is possible the section consists of several compressed
buffers concatenated together, so we uncompress in a loop. */
strm.zalloc = NULL;
strm.zfree = NULL;
strm.opaque = NULL;
strm.avail_in = compressed_size - 12;
strm.next_in = (Bytef*) compressed_buffer + 12;
strm.avail_out = uncompressed_size;
BFD_ASSERT (Z_OK == 0);
rc = inflateInit (&strm);
while (strm.avail_in > 0 && strm.avail_out > 0)
{
if (rc != Z_OK)
break;
strm.next_out = ((Bytef*) uncompressed_buffer
+ (uncompressed_size - strm.avail_out));
rc = inflate (&strm, Z_FINISH);
if (rc != Z_STREAM_END)
break;
rc = inflateReset (&strm);
}
rc |= inflateEnd (&strm);
return rc == Z_OK && strm.avail_out == 0;
}
#endif
/*
FUNCTION
bfd_compress_section_contents
SYNOPSIS
bfd_boolean bfd_compress_section_contents
(bfd *abfd, asection *section, bfd_byte *uncompressed_buffer,
bfd_size_type uncompressed_size);
DESCRIPTION
Compress data of the size specified in @var{uncompressed_size}
and pointed to by @var{uncompressed_buffer} using zlib and store
as the contents field. This function assumes the contents
field was allocated using bfd_malloc() or equivalent. If zlib
is not installed on this machine, the input is unmodified.
Return @code{TRUE} if the full section contents is compressed
successfully.
*/
bfd_boolean
bfd_compress_section_contents (bfd *abfd ATTRIBUTE_UNUSED,
sec_ptr sec ATTRIBUTE_UNUSED,
bfd_byte *uncompressed_buffer ATTRIBUTE_UNUSED,
bfd_size_type uncompressed_size ATTRIBUTE_UNUSED)
{
#ifndef HAVE_ZLIB_H
bfd_set_error (bfd_error_invalid_operation);
return FALSE;
#else
uLong compressed_size;
bfd_byte *compressed_buffer;
compressed_size = compressBound (uncompressed_size) + 12;
compressed_buffer = (bfd_byte *) bfd_malloc (compressed_size);
if (compressed_buffer == NULL)
return FALSE;
if (compress ((Bytef*) compressed_buffer + 12,
&compressed_size,
(const Bytef*) uncompressed_buffer,
uncompressed_size) != Z_OK)
{
free (compressed_buffer);
bfd_set_error (bfd_error_bad_value);
return FALSE;
}
/* Write the zlib header. In this case, it should be "ZLIB" followed
by the uncompressed section size, 8 bytes in big-endian order. */
memcpy (compressed_buffer, "ZLIB", 4);
compressed_buffer[11] = uncompressed_size; uncompressed_size >>= 8;
compressed_buffer[10] = uncompressed_size; uncompressed_size >>= 8;
compressed_buffer[9] = uncompressed_size; uncompressed_size >>= 8;
compressed_buffer[8] = uncompressed_size; uncompressed_size >>= 8;
compressed_buffer[7] = uncompressed_size; uncompressed_size >>= 8;
compressed_buffer[6] = uncompressed_size; uncompressed_size >>= 8;
compressed_buffer[5] = uncompressed_size; uncompressed_size >>= 8;
compressed_buffer[4] = uncompressed_size;
compressed_size += 12;
/* Free the uncompressed contents if we compress in place. */
if (uncompressed_buffer == sec->contents)
free (uncompressed_buffer);
sec->contents = compressed_buffer;
sec->size = compressed_size;
sec->compress_status = COMPRESS_SECTION_DONE;
return TRUE;
#endif /* HAVE_ZLIB_H */
}
/*
FUNCTION
bfd_get_full_section_contents
SYNOPSIS
bfd_boolean bfd_get_full_section_contents
(bfd *abfd, asection *section, bfd_byte **ptr);
DESCRIPTION
Read all data from @var{section} in BFD @var{abfd}, decompress
if needed, and store in @var{*ptr}. If @var{*ptr} is NULL,
return @var{*ptr} with memory malloc'd by this function.
Return @code{TRUE} if the full section contents is retrieved
successfully.
*/
bfd_boolean
bfd_get_full_section_contents (bfd *abfd, sec_ptr sec, bfd_byte **ptr)
{
bfd_size_type sz;
bfd_byte *p = *ptr;
#ifdef HAVE_ZLIB_H
bfd_boolean ret;
bfd_size_type save_size;
bfd_size_type save_rawsize;
bfd_byte *compressed_buffer;
#endif
if (abfd->direction != write_direction && sec->rawsize != 0)
sz = sec->rawsize;
else
sz = sec->size;
if (sz == 0)
return TRUE;
switch (sec->compress_status)
{
case COMPRESS_SECTION_NONE:
if (p == NULL)
{
p = (bfd_byte *) bfd_malloc (sz);
if (p == NULL)
return FALSE;
}
if (!bfd_get_section_contents (abfd, sec, p, 0, sz))
{
if (*ptr != p)
free (p);
return FALSE;
}
*ptr = p;
return TRUE;
case DECOMPRESS_SECTION_SIZED:
#ifndef HAVE_ZLIB_H
bfd_set_error (bfd_error_invalid_operation);
return FALSE;
#else
/* Read in the full compressed section contents. */
compressed_buffer = (bfd_byte *) bfd_malloc (sec->compressed_size);
if (compressed_buffer == NULL)
return FALSE;
save_rawsize = sec->rawsize;
save_size = sec->size;
/* Clear rawsize, set size to compressed size and set compress_status
to COMPRESS_SECTION_NONE. If the compressed size is bigger than
the uncompressed size, bfd_get_section_contents will fail. */
sec->rawsize = 0;
sec->size = sec->compressed_size;
sec->compress_status = COMPRESS_SECTION_NONE;
ret = bfd_get_section_contents (abfd, sec, compressed_buffer,
0, sec->compressed_size);
/* Restore rawsize and size. */
sec->rawsize = save_rawsize;
sec->size = save_size;
sec->compress_status = DECOMPRESS_SECTION_SIZED;
if (!ret)
goto fail_compressed;
if (p == NULL)
p = (bfd_byte *) bfd_malloc (sz);
if (p == NULL)
goto fail_compressed;
if (!decompress_contents (compressed_buffer, sec->compressed_size, p, sz))
{
bfd_set_error (bfd_error_bad_value);
if (p != *ptr)
free (p);
fail_compressed:
free (compressed_buffer);
return FALSE;
}
free (compressed_buffer);
*ptr = p;
return TRUE;
#endif
case COMPRESS_SECTION_DONE:
if (p == NULL)
{
p = (bfd_byte *) bfd_malloc (sz);
if (p == NULL)
return FALSE;
*ptr = p;
}
memcpy (p, sec->contents, sz);
return TRUE;
default:
abort ();
}
}
/*
FUNCTION
bfd_cache_section_contents
SYNOPSIS
void bfd_cache_section_contents
(asection *sec, void *contents);
DESCRIPTION
Stash @var(contents) so any following reads of @var(sec) do
not need to decompress again.
*/
void
bfd_cache_section_contents (asection *sec, void *contents)
{
if (sec->compress_status == DECOMPRESS_SECTION_SIZED)
sec->compress_status = COMPRESS_SECTION_DONE;
sec->contents = contents;
sec->flags |= SEC_IN_MEMORY;
}
/*
FUNCTION
bfd_is_section_compressed
SYNOPSIS
bfd_boolean bfd_is_section_compressed
(bfd *abfd, asection *section);
DESCRIPTION
Return @code{TRUE} if @var{section} is compressed.
*/
bfd_boolean
bfd_is_section_compressed (bfd *abfd, sec_ptr sec)
{
bfd_byte compressed_buffer [12];
unsigned int saved = sec->compress_status;
bfd_boolean compressed;
/* Don't decompress the section. */
sec->compress_status = COMPRESS_SECTION_NONE;
/* Read the zlib header. In this case, it should be "ZLIB" followed
by the uncompressed section size, 8 bytes in big-endian order. */
compressed = (bfd_get_section_contents (abfd, sec, compressed_buffer, 0, 12)
&& CONST_STRNEQ ((char*) compressed_buffer, "ZLIB"));
/* Restore compress_status. */
sec->compress_status = saved;
return compressed;
}
/*
FUNCTION
bfd_init_section_decompress_status
SYNOPSIS
bfd_boolean bfd_init_section_decompress_status
(bfd *abfd, asection *section);
DESCRIPTION
Record compressed section size, update section size with
decompressed size and set compress_status to
DECOMPRESS_SECTION_SIZED.
Return @code{FALSE} if the section is not a valid compressed
section or zlib is not installed on this machine. Otherwise,
return @code{TRUE}.
*/
bfd_boolean
bfd_init_section_decompress_status (bfd *abfd ATTRIBUTE_UNUSED,
sec_ptr sec ATTRIBUTE_UNUSED)
{
#ifndef HAVE_ZLIB_H
bfd_set_error (bfd_error_invalid_operation);
return FALSE;
#else
bfd_byte compressed_buffer [12];
bfd_size_type uncompressed_size;
if (sec->rawsize != 0
|| sec->contents != NULL
|| sec->compress_status != COMPRESS_SECTION_NONE
|| !bfd_get_section_contents (abfd, sec, compressed_buffer, 0, 12))
{
bfd_set_error (bfd_error_invalid_operation);
return FALSE;
}
/* Read the zlib header. In this case, it should be "ZLIB" followed
by the uncompressed section size, 8 bytes in big-endian order. */
if (! CONST_STRNEQ ((char*) compressed_buffer, "ZLIB"))
{
bfd_set_error (bfd_error_wrong_format);
return FALSE;
}
uncompressed_size = compressed_buffer[4]; uncompressed_size <<= 8;
uncompressed_size += compressed_buffer[5]; uncompressed_size <<= 8;
uncompressed_size += compressed_buffer[6]; uncompressed_size <<= 8;
uncompressed_size += compressed_buffer[7]; uncompressed_size <<= 8;
uncompressed_size += compressed_buffer[8]; uncompressed_size <<= 8;
uncompressed_size += compressed_buffer[9]; uncompressed_size <<= 8;
uncompressed_size += compressed_buffer[10]; uncompressed_size <<= 8;
uncompressed_size += compressed_buffer[11];
sec->compressed_size = sec->size;
sec->size = uncompressed_size;
sec->compress_status = DECOMPRESS_SECTION_SIZED;
return TRUE;
#endif
}
/*
FUNCTION
bfd_init_section_compress_status
SYNOPSIS
bfd_boolean bfd_init_section_compress_status
(bfd *abfd, asection *section);
DESCRIPTION
If open for read, compress section, update section size with
compressed size and set compress_status to COMPRESS_SECTION_DONE.
Return @code{FALSE} if the section is not a valid compressed
section or zlib is not installed on this machine. Otherwise,
return @code{TRUE}.
*/
bfd_boolean
bfd_init_section_compress_status (bfd *abfd ATTRIBUTE_UNUSED,
sec_ptr sec ATTRIBUTE_UNUSED)
{
#ifndef HAVE_ZLIB_H
bfd_set_error (bfd_error_invalid_operation);
return FALSE;
#else
bfd_size_type uncompressed_size;
bfd_byte *uncompressed_buffer;
bfd_boolean ret;
/* Error if not opened for read. */
if (abfd->direction != read_direction
|| sec->size == 0
|| sec->rawsize != 0
|| sec->contents != NULL
|| sec->compress_status != COMPRESS_SECTION_NONE)
{
bfd_set_error (bfd_error_invalid_operation);
return FALSE;
}
/* Read in the full section contents and compress it. */
uncompressed_size = sec->size;
uncompressed_buffer = (bfd_byte *) bfd_malloc (uncompressed_size);
if (!bfd_get_section_contents (abfd, sec, uncompressed_buffer,
0, uncompressed_size))
ret = FALSE;
else
ret = bfd_compress_section_contents (abfd, sec,
uncompressed_buffer,
uncompressed_size);
free (uncompressed_buffer);
return ret;
#endif
}
|
52496.c | /*
* RFKILL support for ath5k
*
* Copyright (c) 2009 Tobias Doerffel <[email protected]>
* Lightly modified for gPXE, Sep 2008 by Joshua Oreman <[email protected]>
*
* 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,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
* redistribution must be conditioned upon including a substantially
* similar Disclaimer requirement for further binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* NO WARRANTY
* 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 NONINFRINGEMENT, MERCHANTIBILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES.
*/
FILE_LICENCE ( MIT );
#include "base.h"
static inline void ath5k_rfkill_disable(struct ath5k_softc *sc)
{
DBG("ath5k: rfkill disable (gpio:%d polarity:%d)\n",
sc->rf_kill.gpio, sc->rf_kill.polarity);
ath5k_hw_set_gpio_output(sc->ah, sc->rf_kill.gpio);
ath5k_hw_set_gpio(sc->ah, sc->rf_kill.gpio, !sc->rf_kill.polarity);
}
static inline void ath5k_rfkill_enable(struct ath5k_softc *sc)
{
DBG("ath5k: rfkill enable (gpio:%d polarity:%d)\n",
sc->rf_kill.gpio, sc->rf_kill.polarity);
ath5k_hw_set_gpio_output(sc->ah, sc->rf_kill.gpio);
ath5k_hw_set_gpio(sc->ah, sc->rf_kill.gpio, sc->rf_kill.polarity);
}
static inline void ath5k_rfkill_set_intr(struct ath5k_softc *sc, int enable)
{
struct ath5k_hw *ah = sc->ah;
u32 curval;
ath5k_hw_set_gpio_input(ah, sc->rf_kill.gpio);
curval = ath5k_hw_get_gpio(ah, sc->rf_kill.gpio);
ath5k_hw_set_gpio_intr(ah, sc->rf_kill.gpio, enable ?
!!curval : !curval);
}
static int __unused
ath5k_is_rfkill_set(struct ath5k_softc *sc)
{
/* configuring GPIO for input for some reason disables rfkill */
/*ath5k_hw_set_gpio_input(sc->ah, sc->rf_kill.gpio);*/
return (ath5k_hw_get_gpio(sc->ah, sc->rf_kill.gpio) ==
sc->rf_kill.polarity);
}
void
ath5k_rfkill_hw_start(struct ath5k_hw *ah)
{
struct ath5k_softc *sc = ah->ah_sc;
/* read rfkill GPIO configuration from EEPROM header */
sc->rf_kill.gpio = ah->ah_capabilities.cap_eeprom.ee_rfkill_pin;
sc->rf_kill.polarity = ah->ah_capabilities.cap_eeprom.ee_rfkill_pol;
ath5k_rfkill_disable(sc);
/* enable interrupt for rfkill switch */
if (AR5K_EEPROM_HDR_RFKILL(ah->ah_capabilities.cap_eeprom.ee_header))
ath5k_rfkill_set_intr(sc, 1);
}
void
ath5k_rfkill_hw_stop(struct ath5k_hw *ah)
{
struct ath5k_softc *sc = ah->ah_sc;
/* disable interrupt for rfkill switch */
if (AR5K_EEPROM_HDR_RFKILL(ah->ah_capabilities.cap_eeprom.ee_header))
ath5k_rfkill_set_intr(sc, 0);
/* enable RFKILL when stopping HW so Wifi LED is turned off */
ath5k_rfkill_enable(sc);
}
|
145504.c | /****************************************************************************
* arch/arm/src/lpc17xx_40xx/lpc17_40_irq.c
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you 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.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <stdint.h>
#include <assert.h>
#include <debug.h>
#include <nuttx/irq.h>
#include <nuttx/arch.h>
#include <arch/irq.h>
#include <arch/armv7-m/nvicpri.h>
#include "nvic.h"
#include "ram_vectors.h"
#include "arm_internal.h"
#include "lpc17_40_gpio.h"
#include "lpc17_40_clrpend.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* Get a 32-bit version of the default priority */
#define DEFPRIORITY32 \
(NVIC_SYSH_PRIORITY_DEFAULT << 24 | \
NVIC_SYSH_PRIORITY_DEFAULT << 16 | \
NVIC_SYSH_PRIORITY_DEFAULT << 8 | \
NVIC_SYSH_PRIORITY_DEFAULT)
/* Given the address of a NVIC ENABLE register, this is the offset to
* the corresponding CLEAR ENABLE register.
*/
#define NVIC_ENA_OFFSET (0)
#define NVIC_CLRENA_OFFSET (NVIC_IRQ0_31_CLEAR - NVIC_IRQ0_31_ENABLE)
/****************************************************************************
* Public Data
****************************************************************************/
/* g_current_regs[] holds a references to the current interrupt level
* register storage structure. If is non-NULL only during interrupt
* processing. Access to g_current_regs[] must be through the macro
* CURRENT_REGS for portability.
*/
volatile uint32_t *g_current_regs[1];
/* This is the address of the exception vector table (determined by the
* linker script).
*/
extern uint32_t _vectors[];
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: lpc17_40_dumpnvic
*
* Description:
* Dump some interesting NVIC registers
*
****************************************************************************/
#if defined(CONFIG_DEBUG_IRQ_INFO)
static void lpc17_40_dumpnvic(const char *msg, int irq)
{
irqstate_t flags;
flags = enter_critical_section();
irqinfo("NVIC (%s, irq=%d):\n", msg, irq);
irqinfo(" INTCTRL: %08x VECTAB: %08x\n",
getreg32(NVIC_INTCTRL), getreg32(NVIC_VECTAB));
#if 0
irqinfo(" SYSH ENABLE MEMFAULT: %08x BUSFAULT: %08x USGFAULT: %08x "
"SYSTICK: %08x\n",
getreg32(NVIC_SYSHCON_MEMFAULTENA),
getreg32(NVIC_SYSHCON_BUSFAULTENA),
getreg32(NVIC_SYSHCON_USGFAULTENA),
getreg32(NVIC_SYSTICK_CTRL_ENABLE));
#endif
irqinfo(" IRQ ENABLE: %08x\n", getreg32(NVIC_IRQ0_31_ENABLE));
irqinfo(" SYSH_PRIO: %08x %08x %08x\n",
getreg32(NVIC_SYSH4_7_PRIORITY),
getreg32(NVIC_SYSH8_11_PRIORITY),
getreg32(NVIC_SYSH12_15_PRIORITY));
irqinfo(" IRQ PRIO: %08x %08x %08x %08x\n",
getreg32(NVIC_IRQ0_3_PRIORITY),
getreg32(NVIC_IRQ4_7_PRIORITY),
getreg32(NVIC_IRQ8_11_PRIORITY),
getreg32(NVIC_IRQ12_15_PRIORITY));
irqinfo(" %08x %08x %08x %08x\n",
getreg32(NVIC_IRQ16_19_PRIORITY),
getreg32(NVIC_IRQ20_23_PRIORITY),
getreg32(NVIC_IRQ24_27_PRIORITY),
getreg32(NVIC_IRQ28_31_PRIORITY));
irqinfo(" %08x %08x %08x %08x\n",
getreg32(NVIC_IRQ32_35_PRIORITY),
getreg32(NVIC_IRQ36_39_PRIORITY),
getreg32(NVIC_IRQ40_43_PRIORITY),
getreg32(NVIC_IRQ44_47_PRIORITY));
leave_critical_section(flags);
}
#else
# define lpc17_40_dumpnvic(msg, irq)
#endif
/****************************************************************************
* Name: lpc17_40_nmi, lpc17_40_busfault, lpc17_40_usagefault,
* lpc17_40_pendsv, lpc17_40_dbgmonitor, lpc17_40_pendsv,
* lpc17_40_reserved
*
* Description:
* Handlers for various exceptions. None are handled and all are fatal
* error conditions. The only advantage these provided over the default
* unexpected interrupt handler is that they provide a diagnostic output.
*
****************************************************************************/
#ifdef CONFIG_DEBUG_FEATURES
static int lpc17_40_nmi(int irq, void *context, void *arg)
{
up_irq_save();
_err("PANIC!!! NMI received\n");
PANIC();
return 0;
}
static int lpc17_40_busfault(int irq, void *context, void *arg)
{
up_irq_save();
_err("PANIC!!! Bus fault received\n");
PANIC();
return 0;
}
static int lpc17_40_usagefault(int irq, void *context, void *arg)
{
up_irq_save();
_err("PANIC!!! Usage fault received\n");
PANIC();
return 0;
}
static int lpc17_40_pendsv(int irq, void *context, void *arg)
{
up_irq_save();
_err("PANIC!!! PendSV received\n");
PANIC();
return 0;
}
static int lpc17_40_dbgmonitor(int irq, void *context, void *arg)
{
up_irq_save();
_err("PANIC!!! Debug Monitor received\n");
PANIC();
return 0;
}
static int lpc17_40_reserved(int irq, void *context, void *arg)
{
up_irq_save();
_err("PANIC!!! Reserved interrupt\n");
PANIC();
return 0;
}
#endif
/****************************************************************************
* Name: lpc17_40_prioritize_syscall
*
* Description:
* Set the priority of an exception. This function may be needed
* internally even if support for prioritized interrupts is not enabled.
*
****************************************************************************/
#ifdef CONFIG_ARMV7M_USEBASEPRI
static inline void lpc17_40_prioritize_syscall(int priority)
{
uint32_t regval;
/* SVCALL is system handler 11 */
regval = getreg32(NVIC_SYSH8_11_PRIORITY);
regval &= ~NVIC_SYSH_PRIORITY_PR11_MASK;
regval |= (priority << NVIC_SYSH_PRIORITY_PR11_SHIFT);
putreg32(regval, NVIC_SYSH8_11_PRIORITY);
}
#endif
/****************************************************************************
* Name: lpc17_40_irqinfo
*
* Description:
* Given an IRQ number, provide the register and bit setting to enable or
* disable the irq.
*
****************************************************************************/
static int lpc17_40_irqinfo(int irq, uintptr_t *regaddr, uint32_t *bit,
uintptr_t offset)
{
DEBUGASSERT(irq >= LPC17_40_IRQ_NMI && irq < NR_IRQS);
/* Check for external interrupt */
if (irq >= LPC17_40_IRQ_EXTINT)
{
if (irq < (LPC17_40_IRQ_EXTINT + 32))
{
*regaddr = (NVIC_IRQ0_31_ENABLE + offset);
*bit = 1 << (irq - LPC17_40_IRQ_EXTINT);
}
else if (irq < LPC17_40_IRQ_NIRQS)
{
*regaddr = (NVIC_IRQ32_63_ENABLE + offset);
*bit = 1 << (irq - LPC17_40_IRQ_EXTINT - 32);
}
else
{
return ERROR; /* Invalid irq */
}
}
/* Handle processor exceptions. Only a few can be disabled */
else
{
*regaddr = NVIC_SYSHCON;
if (irq == LPC17_40_IRQ_MEMFAULT)
{
*bit = NVIC_SYSHCON_MEMFAULTENA;
}
else if (irq == LPC17_40_IRQ_BUSFAULT)
{
*bit = NVIC_SYSHCON_BUSFAULTENA;
}
else if (irq == LPC17_40_IRQ_USAGEFAULT)
{
*bit = NVIC_SYSHCON_USGFAULTENA;
}
else if (irq == LPC17_40_IRQ_SYSTICK)
{
*regaddr = NVIC_SYSTICK_CTRL;
*bit = NVIC_SYSTICK_CTRL_ENABLE;
}
else
{
return ERROR; /* Invalid or unsupported exception */
}
}
return OK;
}
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: up_irqinitialize
****************************************************************************/
void up_irqinitialize(void)
{
uintptr_t regaddr;
int nintlines;
int i;
/* The NVIC ICTR register (bits 0-4) holds the number of interrupt
* lines that the NVIC supports, defined in groups of 32. That is,
* the total number of interrupt lines is up to (32*(INTLINESNUM+1)).
*
* 0 -> 32 interrupt lines, 1 enable register, 8 priority registers
* 1 -> 64 " " " ", 2 enable registers, 16 priority registers
* 2 -> 96 " " " ", 3 enable registers, 24 priority registers
* ...
*/
nintlines = (getreg32(NVIC_ICTR) & NVIC_ICTR_INTLINESNUM_MASK) + 1;
/* Disable all interrupts. There are nintlines interrupt enable
* registers.
*/
for (i = nintlines, regaddr = NVIC_IRQ0_31_CLEAR;
i > 0;
i--, regaddr += 4)
{
putreg32(0xffffffff, regaddr);
}
/* Make sure that we are using the correct vector table. The default
* vector address is 0x0000:0000 but if we are executing code that is
* positioned in SRAM or in external FLASH, then we may need to reset
* the interrupt vector so that it refers to the table in SRAM or in
* external FLASH.
*/
putreg32((uint32_t)_vectors, NVIC_VECTAB);
/* If CONFIG_ARCH_RAMVECTORS is defined, then we are using a RAM-based
* vector table that requires special initialization.
*
* But even in this case NVIC_VECTAB has to point to the initial table
* because arm_ramvec_initialize() initializes RAM table from table
* pointed by NVIC_VECTAB register.
*/
#ifdef CONFIG_ARCH_RAMVECTORS
arm_ramvec_initialize();
#endif
/* Set all interrupts (and exceptions) to the default priority */
putreg32(DEFPRIORITY32, NVIC_SYSH4_7_PRIORITY);
putreg32(DEFPRIORITY32, NVIC_SYSH8_11_PRIORITY);
putreg32(DEFPRIORITY32, NVIC_SYSH12_15_PRIORITY);
/* Now set all of the interrupt lines to the default priority. There are
* nintlines * 8 priority registers.
*/
for (i = (nintlines << 3), regaddr = NVIC_IRQ0_3_PRIORITY;
i > 0;
i--, regaddr += 4)
{
putreg32(DEFPRIORITY32, regaddr);
}
/* currents_regs is non-NULL only while processing an interrupt */
CURRENT_REGS = NULL;
/* Attach the SVCall and Hard Fault exception handlers. The SVCall
* exception is used for performing context switches; The Hard Fault
* must also be caught because a SVCall may show up as a Hard Fault
* under certain conditions.
*/
irq_attach(LPC17_40_IRQ_SVCALL, arm_svcall, NULL);
irq_attach(LPC17_40_IRQ_HARDFAULT, arm_hardfault, NULL);
/* Set the priority of the SVCall interrupt */
#ifdef CONFIG_ARCH_IRQPRIO
/* up_prioritize_irq(LPC17_40_IRQ_PENDSV, NVIC_SYSH_PRIORITY_MIN); */
#endif
#ifdef CONFIG_ARMV7M_USEBASEPRI
lpc17_40_prioritize_syscall(NVIC_SYSH_SVCALL_PRIORITY);
#endif
/* If the MPU is enabled, then attach and enable the Memory Management
* Fault handler.
*/
#ifdef CONFIG_ARM_MPU
irq_attach(LPC17_40_IRQ_MEMFAULT, arm_memfault, NULL);
up_enable_irq(LPC17_40_IRQ_MEMFAULT);
#endif
/* Attach all other processor exceptions (except reset and sys tick) */
#ifdef CONFIG_DEBUG_FEATURES
irq_attach(LPC17_40_IRQ_NMI, lpc17_40_nmi, NULL);
#ifndef CONFIG_ARM_MPU
irq_attach(LPC17_40_IRQ_MEMFAULT, arm_memfault, NULL);
#endif
irq_attach(LPC17_40_IRQ_BUSFAULT, lpc17_40_busfault, NULL);
irq_attach(LPC17_40_IRQ_USAGEFAULT, lpc17_40_usagefault, NULL);
irq_attach(LPC17_40_IRQ_PENDSV, lpc17_40_pendsv, NULL);
irq_attach(LPC17_40_IRQ_DBGMONITOR, lpc17_40_dbgmonitor, NULL);
irq_attach(LPC17_40_IRQ_RESERVED, lpc17_40_reserved, NULL);
#endif
lpc17_40_dumpnvic("initial", LPC17_40_IRQ_NIRQS);
/* Initialize logic to support a second level of interrupt decoding for
* GPIO pins.
*/
#ifdef CONFIG_LPC17_40_GPIOIRQ
lpc17_40_gpioirqinitialize();
#endif
/* And finally, enable interrupts */
#ifndef CONFIG_SUPPRESS_INTERRUPTS
up_irq_enable();
#endif
}
/****************************************************************************
* Name: up_disable_irq
*
* Description:
* Disable the IRQ specified by 'irq'
*
****************************************************************************/
void up_disable_irq(int irq)
{
uintptr_t regaddr;
uint32_t regval;
uint32_t bit;
if (lpc17_40_irqinfo(irq, ®addr, &bit, NVIC_CLRENA_OFFSET) == 0)
{
/* Modify the appropriate bit in the register to disable the interrupt.
* For normal interrupts, we need to set the bit in the associated
* Interrupt Clear Enable register. For other exceptions, we need to
* clear the bit in the System Handler Control and State Register.
*/
if (irq >= LPC17_40_IRQ_EXTINT)
{
putreg32(bit, regaddr);
}
else
{
regval = getreg32(regaddr);
regval &= ~bit;
putreg32(regval, regaddr);
}
}
#ifdef CONFIG_LPC17_40_GPIOIRQ
else if (irq >= LPC17_40_VALID_FIRST0L)
{
/* Maybe it is a (derived) GPIO IRQ */
lpc17_40_gpioirqdisable(irq);
}
#endif
lpc17_40_dumpnvic("disable", irq);
}
/****************************************************************************
* Name: up_enable_irq
*
* Description:
* Enable the IRQ specified by 'irq'
*
****************************************************************************/
void up_enable_irq(int irq)
{
uintptr_t regaddr;
uint32_t regval;
uint32_t bit;
if (lpc17_40_irqinfo(irq, ®addr, &bit, NVIC_ENA_OFFSET) == 0)
{
/* Modify the appropriate bit in the register to enable the interrupt.
* For normal interrupts, we need to set the bit in the associated
* Interrupt Set Enable register. For other exceptions, we need to
* set the bit in the System Handler Control and State Register.
*/
if (irq >= LPC17_40_IRQ_EXTINT)
{
putreg32(bit, regaddr);
}
else
{
regval = getreg32(regaddr);
regval |= bit;
putreg32(regval, regaddr);
}
}
#ifdef CONFIG_LPC17_40_GPIOIRQ
else if (irq >= LPC17_40_VALID_FIRST0L)
{
/* Maybe it is a (derived) GPIO IRQ */
lpc17_40_gpioirqenable(irq);
}
#endif
lpc17_40_dumpnvic("enable", irq);
}
/****************************************************************************
* Name: arm_ack_irq
*
* Description:
* Acknowledge the IRQ
*
****************************************************************************/
void arm_ack_irq(int irq)
{
#if 0 /* Does not appear to be necessary in most cases */
lpc17_40_clrpend(irq);
#endif
}
/****************************************************************************
* Name: up_prioritize_irq
*
* Description:
* Set the priority of an IRQ.
*
* Since this API is not supported on all architectures, it should be
* avoided in common implementations where possible.
*
****************************************************************************/
#ifdef CONFIG_ARCH_IRQPRIO
int up_prioritize_irq(int irq, int priority)
{
uint32_t regaddr;
uint32_t regval;
int shift;
DEBUGASSERT(irq >= LPC17_40_IRQ_MEMFAULT && irq < LPC17_40_IRQ_NIRQS &&
(unsigned)priority <= NVIC_SYSH_PRIORITY_MIN);
if (irq < LPC17_40_IRQ_EXTINT)
{
/* NVIC_SYSH_PRIORITY() maps {0..15} to one of three priority
* registers (0-3 are invalid)
*/
regaddr = NVIC_SYSH_PRIORITY(irq);
irq -= 4;
}
else
{
/* NVIC_IRQ_PRIORITY() maps {0..} to one of many priority registers */
irq -= LPC17_40_IRQ_EXTINT;
regaddr = NVIC_IRQ_PRIORITY(irq);
}
regval = getreg32(regaddr);
shift = ((irq & 3) << 3);
regval &= ~(0xff << shift);
regval |= (priority << shift);
putreg32(regval, regaddr);
lpc17_40_dumpnvic("prioritize", irq);
return OK;
}
#endif
|
162242.c | /*++
Copyright (c) Microsoft Corporation. All rights reserved.
You may only use this code if you agree to the terms of the Windows Research Kernel Source Code License agreement (see License.txt).
If you do not agree to the terms, do not use the code.
Module Name:
kiinit.c
Abstract:
This module implements architecture independent kernel initialization.
--*/
#include "ki.h"
//
// External data.
//
extern ALIGNED_SPINLOCK AfdWorkQueueSpinLock;
extern ALIGNED_SPINLOCK CcBcbSpinLock;
extern ALIGNED_SPINLOCK CcMasterSpinLock;
extern ALIGNED_SPINLOCK CcVacbSpinLock;
extern ALIGNED_SPINLOCK CcWorkQueueSpinLock;
extern ALIGNED_SPINLOCK IopCancelSpinLock;
extern ALIGNED_SPINLOCK IopCompletionLock;
extern ALIGNED_SPINLOCK IopDatabaseLock;
extern ALIGNED_SPINLOCK IopVpbSpinLock;
extern ALIGNED_SPINLOCK NtfsStructLock;
extern ALIGNED_SPINLOCK MmPfnLock;
extern ALIGNED_SPINLOCK NonPagedPoolLock;
extern ALIGNED_SPINLOCK MmNonPagedPoolLock;
extern ALIGNED_SPINLOCK MmSystemSpaceLock;
#if defined(KE_MULTINODE)
extern PHALNUMAQUERYPROCESSORNODE KiQueryProcessorNode;
extern PHALNUMAPAGETONODE MmPageToNode;
#endif
//
// Put all code for kernel initialization in the INIT section. It will be
// deallocated by memory management when phase 1 initialization is completed.
//
#pragma alloc_text(INIT, KeInitSystem)
#pragma alloc_text(INIT, KiInitSpinLocks)
#pragma alloc_text(INIT, KiInitSystem)
#pragma alloc_text(INIT, KeNumaInitialize)
BOOLEAN
KeInitSystem (
VOID
)
/*++
Routine Description:
This function initializes executive structures implemented by the
kernel.
N.B. This function is only called during phase 1 initialization.
Arguments:
None.
Return Value:
A value of TRUE is returned if initialization is successful. Otherwise,
a value of FALSE is returned.
--*/
{
HANDLE Handle;
ULONG Index;
ULONG Limit;
OBJECT_ATTRIBUTES ObjectAttributes;
PKPRCB Prcb;
NTSTATUS Status;
//
// If threaded DPCs are enabled for the host system, then create a DPC
// thread for each processor.
//
if (KeThreadDpcEnable != FALSE) {
Index = 0;
Limit = (ULONG)KeNumberProcessors;
InitializeObjectAttributes( &ObjectAttributes, NULL, 0, NULL, NULL);
do {
Prcb = KiProcessorBlock[Index];
KeInitializeEvent(&Prcb->DpcEvent, SynchronizationEvent, FALSE);
InitializeListHead(&Prcb->DpcData[DPC_THREADED].DpcListHead);
KeInitializeSpinLock(&Prcb->DpcData[DPC_THREADED].DpcLock);
Prcb->DpcData[DPC_THREADED].DpcQueueDepth = 0;
Status = PsCreateSystemThread(&Handle,
THREAD_ALL_ACCESS,
&ObjectAttributes,
NULL,
NULL,
KiExecuteDpc,
Prcb);
if (!NT_SUCCESS(Status)) {
return FALSE;
}
ZwClose(Handle);
Index += 1;
} while (Index < Limit);
}
//
// Perform platform dependent initialization.
//
return KiInitMachineDependent();
}
VOID
KiInitSpinLocks (
PKPRCB Prcb,
ULONG Number
)
/*++
Routine Description:
This function initializes the spinlock structures in the per processor
PRCB. This function is called once for each processor.
Arguments:
Prcb - Supplies a pointer to a PRCB.
Number - Supplies the number of respective processor.
Return Value:
None.
--*/
{
ULONG Index;
//
// Initialize dispatcher ready queue list heads, the ready summary, and
// the deferred ready list head.
//
Prcb->QueueIndex = 1;
Prcb->ReadySummary = 0;
Prcb->DeferredReadyListHead.Next = NULL;
for (Index = 0; Index < MAXIMUM_PRIORITY; Index += 1) {
InitializeListHead(&Prcb->DispatcherReadyListHead[Index]);
}
//
// Initialize the normal DPC data.
//
InitializeListHead(&Prcb->DpcData[DPC_NORMAL].DpcListHead);
KeInitializeSpinLock(&Prcb->DpcData[DPC_NORMAL].DpcLock);
Prcb->DpcData[DPC_NORMAL].DpcQueueDepth = 0;
Prcb->DpcData[DPC_NORMAL].DpcCount = 0;
Prcb->DpcRoutineActive = 0;
Prcb->MaximumDpcQueueDepth = KiMaximumDpcQueueDepth;
Prcb->MinimumDpcRate = KiMinimumDpcRate;
Prcb->AdjustDpcThreshold = KiAdjustDpcThreshold;
//
// Initialize the generic call DPC structure, set the target processor
// number, and set the DPC importance.
//
KeInitializeDpc(&Prcb->CallDpc, NULL, NULL);
KeSetTargetProcessorDpc(&Prcb->CallDpc, (CCHAR)Number);
KeSetImportanceDpc(&Prcb->CallDpc, HighImportance);
//
// Initialize wait list.
//
InitializeListHead(&Prcb->WaitListHead);
//
// Initialize general numbered queued spinlock structures.
//
#if defined(_AMD64_)
KeGetPcr()->LockArray = &Prcb->LockQueue[0];
#endif
Prcb->LockQueue[LockQueueDispatcherLock].Next = NULL;
Prcb->LockQueue[LockQueueDispatcherLock].Lock = &KiDispatcherLock;
Prcb->LockQueue[LockQueueUnusedSpare1].Next = NULL;
Prcb->LockQueue[LockQueueUnusedSpare1].Lock = NULL;
Prcb->LockQueue[LockQueuePfnLock].Next = NULL;
Prcb->LockQueue[LockQueuePfnLock].Lock = &MmPfnLock;
Prcb->LockQueue[LockQueueSystemSpaceLock].Next = NULL;
Prcb->LockQueue[LockQueueSystemSpaceLock].Lock = &MmSystemSpaceLock;
Prcb->LockQueue[LockQueueBcbLock].Next = NULL;
Prcb->LockQueue[LockQueueBcbLock].Lock = &CcBcbSpinLock;
Prcb->LockQueue[LockQueueMasterLock].Next = NULL;
Prcb->LockQueue[LockQueueMasterLock].Lock = &CcMasterSpinLock;
Prcb->LockQueue[LockQueueVacbLock].Next = NULL;
Prcb->LockQueue[LockQueueVacbLock].Lock = &CcVacbSpinLock;
Prcb->LockQueue[LockQueueWorkQueueLock].Next = NULL;
Prcb->LockQueue[LockQueueWorkQueueLock].Lock = &CcWorkQueueSpinLock;
Prcb->LockQueue[LockQueueNonPagedPoolLock].Next = NULL;
Prcb->LockQueue[LockQueueNonPagedPoolLock].Lock = &NonPagedPoolLock;
Prcb->LockQueue[LockQueueMmNonPagedPoolLock].Next = NULL;
Prcb->LockQueue[LockQueueMmNonPagedPoolLock].Lock = &MmNonPagedPoolLock;
Prcb->LockQueue[LockQueueIoCancelLock].Next = NULL;
Prcb->LockQueue[LockQueueIoCancelLock].Lock = &IopCancelSpinLock;
Prcb->LockQueue[LockQueueIoVpbLock].Next = NULL;
Prcb->LockQueue[LockQueueIoVpbLock].Lock = &IopVpbSpinLock;
Prcb->LockQueue[LockQueueIoDatabaseLock].Next = NULL;
Prcb->LockQueue[LockQueueIoDatabaseLock].Lock = &IopDatabaseLock;
Prcb->LockQueue[LockQueueIoCompletionLock].Next = NULL;
Prcb->LockQueue[LockQueueIoCompletionLock].Lock = &IopCompletionLock;
Prcb->LockQueue[LockQueueNtfsStructLock].Next = NULL;
Prcb->LockQueue[LockQueueNtfsStructLock].Lock = &NtfsStructLock;
Prcb->LockQueue[LockQueueAfdWorkQueueLock].Next = NULL;
Prcb->LockQueue[LockQueueAfdWorkQueueLock].Lock = &AfdWorkQueueSpinLock;
Prcb->LockQueue[LockQueueUnusedSpare16].Next = NULL;
Prcb->LockQueue[LockQueueUnusedSpare16].Lock = NULL;
//
// Initialize the timer table numbered queued spinlock structures.
//
for (Index = 0; Index < LOCK_QUEUE_TIMER_TABLE_LOCKS; Index += 1) {
KeInitializeSpinLock(&KiTimerTableLock[Index].Lock);
Prcb->LockQueue[LockQueueTimerTableLock + Index].Next = NULL;
Prcb->LockQueue[LockQueueTimerTableLock + Index].Lock = &KiTimerTableLock[Index].Lock;
}
//
// Initialize processor control block lock.
//
KeInitializeSpinLock(&Prcb->PrcbLock);
//
// If this is processor zero, then also initialize the queued spin lock
// home address.
//
if (Number == 0) {
KeInitializeSpinLock(&KiDispatcherLock);
KeInitializeSpinLock(&KiReverseStallIpiLock);
KeInitializeSpinLock(&MmPfnLock);
KeInitializeSpinLock(&MmSystemSpaceLock);
KeInitializeSpinLock(&CcBcbSpinLock);
KeInitializeSpinLock(&CcMasterSpinLock);
KeInitializeSpinLock(&CcVacbSpinLock);
KeInitializeSpinLock(&CcWorkQueueSpinLock);
KeInitializeSpinLock(&IopCancelSpinLock);
KeInitializeSpinLock(&IopCompletionLock);
KeInitializeSpinLock(&IopDatabaseLock);
KeInitializeSpinLock(&IopVpbSpinLock);
KeInitializeSpinLock(&NonPagedPoolLock);
KeInitializeSpinLock(&MmNonPagedPoolLock);
KeInitializeSpinLock(&NtfsStructLock);
KeInitializeSpinLock(&AfdWorkQueueSpinLock);
}
return;
}
VOID
KiInitSystem (
VOID
)
/*++
Routine Description:
This function initializes architecture independent kernel structures.
N.B. This function is only called on processor 0.
Arguments:
None.
Return Value:
None.
--*/
{
ULONG Index;
//
// Initialize bugcheck callback listhead and spinlock.
//
InitializeListHead(&KeBugCheckCallbackListHead);
InitializeListHead(&KeBugCheckReasonCallbackListHead);
KeInitializeSpinLock(&KeBugCheckCallbackLock);
//
// Initialize the timer expiration DPC object and set the destination
// processor to processor zero.
//
KeInitializeDpc(&KiTimerExpireDpc, KiTimerExpiration, NULL);
KeSetTargetProcessorDpc(&KiTimerExpireDpc, 0);
//
// Initialize the profile listhead and profile locks
//
KeInitializeSpinLock(&KiProfileLock);
InitializeListHead(&KiProfileListHead);
//
// Initialize the active profile source listhead.
//
InitializeListHead(&KiProfileSourceListHead);
//
// Initialize the timer table and the timer table due time table.
//
// N.B. Each entry in the timer table due time table is set to an infinite
// absolute due time.
//
for (Index = 0; Index < TIMER_TABLE_SIZE; Index += 1) {
InitializeListHead(&KiTimerTableListHead[Index].Entry);
KiTimerTableListHead[Index].Time.HighPart = 0xffffffff;
KiTimerTableListHead[Index].Time.LowPart = 0;
}
//
// Initialize the swap event, the process inswap listhead, the
// process outswap listhead, and the kernel stack inswap listhead.
//
KeInitializeEvent(&KiSwapEvent,
SynchronizationEvent,
FALSE);
KiProcessInSwapListHead.Next = NULL;
KiProcessOutSwapListHead.Next = NULL;
KiStackInSwapListHead.Next = NULL;
//
// Initialize the generic DPC call fast mutex.
//
ExInitializeFastMutex(&KiGenericCallDpcMutex);
//
// Initialize the system service descriptor table.
//
KeServiceDescriptorTable[0].Base = &KiServiceTable[0];
KeServiceDescriptorTable[0].Count = NULL;
KeServiceDescriptorTable[0].Limit = KiServiceLimit;
KeServiceDescriptorTable[0].Number = KiArgumentTable;
for (Index = 1; Index < NUMBER_SERVICE_TABLES; Index += 1) {
KeServiceDescriptorTable[Index].Limit = 0;
}
//
// Copy the system service descriptor table to the shadow table
// which is used to record the Win32 system services.
//
RtlCopyMemory(KeServiceDescriptorTableShadow,
KeServiceDescriptorTable,
sizeof(KeServiceDescriptorTable));
return;
}
ULARGE_INTEGER
KeComputeReciprocal (
IN LONG Divisor,
OUT PCCHAR Shift
)
/*++
Routine Description:
This function computes the 64-bit reciprocal of the specified value.
Arguments:
Divisor - Supplies the value for which the large integer reciprocal is
computed.
Shift - Supplies a pointer to a variable that receives the computed
shift count.
Return Value:
The 64-bit reciprocal is returned as the function value.
--*/
{
LARGE_INTEGER Fraction;
LONG NumberBits;
LONG Remainder;
//
// Compute the large integer reciprocal of the specified value.
//
NumberBits = 0;
Remainder = 1;
Fraction.LowPart = 0;
Fraction.HighPart = 0;
while (Fraction.HighPart >= 0) {
NumberBits += 1;
Fraction.HighPart = (Fraction.HighPart << 1) | (Fraction.LowPart >> 31);
Fraction.LowPart <<= 1;
Remainder <<= 1;
if (Remainder >= Divisor) {
Remainder -= Divisor;
Fraction.LowPart |= 1;
}
}
if (Remainder != 0) {
if ((Fraction.LowPart == 0xffffffff) && (Fraction.HighPart == 0xffffffff)) {
Fraction.LowPart = 0;
Fraction.HighPart = 0x80000000;
NumberBits -= 1;
} else {
if (Fraction.LowPart == 0xffffffff) {
Fraction.LowPart = 0;
Fraction.HighPart += 1;
} else {
Fraction.LowPart += 1;
}
}
}
//
// Compute the shift count value and return the reciprocal fraction.
//
*Shift = (CCHAR)(NumberBits - 64);
return *((PULARGE_INTEGER)&Fraction);
}
ULONG
KeComputeReciprocal32 (
IN LONG Divisor,
OUT PCCHAR Shift
)
/*++
Routine Description:
This function computes the 32-bit reciprocal of the specified value.
Arguments:
Divisor - Supplies the value for which the large integer reciprocal is
computed.
Shift - Supplies a pointer to a variable that receives the computed
shift count.
Return Value:
The 32-bit reciprocal is returned as the function value.
--*/
{
LONG Fraction;
LONG NumberBits;
LONG Remainder;
//
// Compute the 32-bit reciprocal of the specified value.
//
NumberBits = 0;
Remainder = 1;
Fraction = 0;
while (Fraction >= 0) {
NumberBits += 1;
Fraction <<= 1;
Remainder <<= 1;
if (Remainder >= Divisor) {
Remainder -= Divisor;
Fraction |= 1;
}
}
if (Remainder != 0) {
if (Fraction == 0xffffffff) {
Fraction = 0x80000000;
NumberBits -= 1;
} else {
Fraction += 1;
}
}
//
// Compute the shift count value and return the reciprocal fraction.
//
*Shift = (CCHAR)(NumberBits - 32);
return Fraction;
}
VOID
KeNumaInitialize (
VOID
)
/*++
Routine Description:
Initialize the kernel structures needed to support NUMA systems.
Arguments:
None.
Return Value:
None.
--*/
{
#if defined(KE_MULTINODE)
ULONG Length;
HAL_NUMA_TOPOLOGY_INTERFACE NumaInformation;
NTSTATUS Status;
//
// Query the NUMA topology of the system.
//
Status = HalQuerySystemInformation(HalNumaTopologyInterface,
sizeof(HAL_NUMA_TOPOLOGY_INTERFACE),
&NumaInformation,
&Length);
//
// If the query was successful and the number of nodes in the host
// system is greater than one, then set the number of nodes and the
// address of the page to node and query processor functions.
//
if (NT_SUCCESS(Status)) {
ASSERT(Length == sizeof(HAL_NUMA_TOPOLOGY_INTERFACE));
ASSERT(NumaInformation.NumberOfNodes <= MAXIMUM_CCNUMA_NODES);
ASSERT(NumaInformation.QueryProcessorNode != NULL);
ASSERT(NumaInformation.PageToNode != NULL);
if (NumaInformation.NumberOfNodes > 1) {
KeNumberNodes = (UCHAR)NumaInformation.NumberOfNodes;
MmPageToNode = NumaInformation.PageToNode;
KiQueryProcessorNode = NumaInformation.QueryProcessorNode;
}
}
#endif
return;
}
|
463997.c | /****************************************************************************
* @file main.c
* @version V1.00
* @brief Demonstrate the RTC function and displays current time to the
* UART console
*
* SPDX-License-Identifier: Apache-2.0
* @copyright (C) 2020 Nuvoton Technology Corp. All rights reserved.
******************************************************************************/
#include <stdio.h>
#include "NuMicro.h"
/*---------------------------------------------------------------------------------------------------------*/
/* Global variables */
/*---------------------------------------------------------------------------------------------------------*/
volatile uint32_t g_u32TICK = 0;
/*---------------------------------------------------------------------------------------------------------*/
/* Define functions prototype */
/*---------------------------------------------------------------------------------------------------------*/
void RTC_TickHandle(void);
void RTC_IRQHandler(void);
void LXT_Enable(void);
void SYS_Init(void);
int32_t main(void);
#if defined (__GNUC__) && !defined(__ARMCC_VERSION) && defined(OS_USE_SEMIHOSTING)
extern void initialise_monitor_handles(void);
#endif
/*---------------------------------------------------------------------------------------------------------*/
/* RTC Tick Handle */
/*---------------------------------------------------------------------------------------------------------*/
void RTC_TickHandle(void)
{
S_RTC_TIME_DATA_T sCurTime;
/* Get the current time */
RTC_GetDateAndTime(&sCurTime);
printf(" Current Time:%u/%02u/%02u %02u:%02u:%02u\n", sCurTime.u32Year, sCurTime.u32Month, sCurTime.u32Day, sCurTime.u32Hour, sCurTime.u32Minute, sCurTime.u32Second);
g_u32TICK++;
}
/**
* @brief RTC ISR to handle interrupt event
* @param None
* @retval None
*/
void RTC_IRQHandler(void)
{
/* tick interrupt occurred */
if ((RTC->INTEN & RTC_INTEN_TICKIEN_Msk) && (RTC->INTSTS & RTC_INTSTS_TICKIF_Msk))
{
RTC->INTSTS = 0x2;
RTC_TickHandle();
}
}
/*---------------------------------------------------------------------------------------------------------*/
/* Enable the external 32768Hz XTAL Clock */
/*---------------------------------------------------------------------------------------------------------*/
void LXT_Enable(void)
{
/* Set X32_OUT(PF.4) and X32_IN(PF.5) to input mode */
PF->MODE &= ~(GPIO_MODE_MODE4_Msk | GPIO_MODE_MODE5_Msk);
/* Enable external 32768Hz XTAL */
CLK_EnableXtalRC(CLK_PWRCTL_LXTEN_Msk);
/* Waiting for clock ready */
CLK_WaitClockReady(CLK_STATUS_LXTSTB_Msk);
/* Disable digital input path of analog pin X32_OUT to prevent leakage */
GPIO_DISABLE_DIGITAL_PATH(PF, (1ul << 4));
/* Disable digital input path of analog pin XT32_IN to prevent leakage */
GPIO_DISABLE_DIGITAL_PATH(PF, (1ul << 5));
}
/*---------------------------------------------------------------------------------------------------------*/
/* Init System Clock */
/*---------------------------------------------------------------------------------------------------------*/
void SYS_Init(void)
{
/* Unlock protected registers */
SYS_UnlockReg();
/* Enable HIRC clock (Internal RC 48MHz) */
CLK_EnableXtalRC(CLK_PWRCTL_HIRCEN_Msk);
/* Wait for HIRC clock ready */
CLK_WaitClockReady(CLK_STATUS_HIRCSTB_Msk);
/* Select HCLK clock source as HIRC and and HCLK source divider as 1 */
CLK_SetHCLK(CLK_CLKSEL0_HCLKSEL_HIRC, CLK_CLKDIV0_HCLK(1));
/* Set both PCLK0 and PCLK1 as HCLK/2 */
CLK->PCLKDIV = CLK_PCLKDIV_APB0DIV_DIV2 | CLK_PCLKDIV_APB1DIV_DIV2;
/* Enable external 32768Hz XTAL */
LXT_Enable();
/* Debug UART clock setting */
UartDebugCLK();
/* Enable RTC peripheral clock */
CLK_EnableModuleClock(RTC_MODULE);
/* Update System Core Clock */
/* User can use SystemCoreClockUpdate() to calculate SystemCoreClock and CycylesPerUs automatically. */
SystemCoreClockUpdate();
/*---------------------------------------------------------------------------------------------------------*/
/* Init I/O Multi-function */
/*---------------------------------------------------------------------------------------------------------*/
UartDebugMFP();
/* Lock protected registers */
SYS_LockReg();
}
/*---------------------------------------------------------------------------------------------------------*/
/* MAIN function */
/*---------------------------------------------------------------------------------------------------------*/
int32_t main(void)
{
S_RTC_TIME_DATA_T sInitTime;
SYS_Init();
#if defined (__GNUC__) && !defined(__ARMCC_VERSION) && defined(OS_USE_SEMIHOSTING)
initialise_monitor_handles();
#endif
/* Init Debug UART */
UartDebugInit();
printf("\n\nCPU @ %u Hz\n", SystemCoreClock);
/* Time Setting */
sInitTime.u32Year = 2018;
sInitTime.u32Month = 12;
sInitTime.u32Day = 11;
sInitTime.u32Hour = 13;
sInitTime.u32Minute = 30;
sInitTime.u32Second = 0;
sInitTime.u32DayOfWeek = RTC_TUESDAY;
sInitTime.u32TimeScale = RTC_CLOCK_24;
RTC_Open(&sInitTime);
printf("\n RTC Time Display Test (Exit after 10 seconds)\n\n");
/* Set Tick Period */
RTC_SetTickPeriod(RTC_TICK_1_SEC);
/* Enable RTC Tick Interrupt */
RTC_EnableInt(RTC_INTEN_TICKIEN_Msk);
NVIC_EnableIRQ(RTC_IRQn);
g_u32TICK = 0;
while (g_u32TICK < 10);
printf("\n RTC Time Display Test End !!\n");
/* Disable RTC Tick Interrupt */
RTC_DisableInt(RTC_INTEN_TICKIEN_Msk);
NVIC_DisableIRQ(RTC_IRQn);
while (1);
}
|
322010.c | /* Copyright (C) 2007-2020 Free Software Foundation, Inc.
This file is part of GCC.
GCC 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, or (at your option) any later
version.
GCC 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.
Under Section 7 of GPL version 3, you are granted additional
permissions described in the GCC Runtime Library Exception, version
3.1, as published by the Free Software Foundation.
You should have received a copy of the GNU General Public License and
a copy of the GCC Runtime Library Exception along with this program;
see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
<http://www.gnu.org/licenses/>. */
#include "bid_conf.h"
#include "bid_functions.h"
#include "bid_gcc_intrinsics.h"
#if LIBGCC2_HAS_TF_MODE || BID_HAS_TF_MODE
_Decimal32
__bid_trunctfsd (TFtype x) {
union decimal32 res;
union float128 ux;
ux.f = x;
res.i = __binary128_to_bid32 (ux.i);
return (res.d);
}
#endif
|
305756.c | #include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <assert.h>
#include "common.h"
int
main(int argc, char *argv[])
{
if (argc != 2) {
fprintf(stderr, "usage: cpu <string>\n");
exit(1);
}
char *str = argv[1];
while (1) {
Spin(1);
printf("%s\n", str);
}
return 0;
}
|
284827.c | //*******************************************************************
//Author: Gyouho Kim
//Description: AM stack with MRRv6 and SNSv10, ADXL362
// Modified from 'ARstack_ondemand_v1.7.c'
// v1.7: CL unlimited during tx, shortening CLEN, pulse width
// v1.8: Incorporate HRV light detection & clean up
// v1.9: PMU setting adjustment based on temp
// v1.10: Use case update; send radio only when activity detected, check in every n wakeups
// Header increased to 96b
// Different thresholding for low light conditions
// v1.11: Adding hard reset trigger; adding option to set decap in parallel
// v1.12: Fixing high current issue when disabling ADXL after false trigger
// Making freq hopping configurable, only need the min cap setting now
// v1.13: Fixing flag initialization in 0x32 trig, battery field in 0x3D packet
// Changing some default values
// v1.13 used for MOD demo & delivery May 2018
//*******************************************************************
#include "PREv17.h"
#include "PREv17_RF.h"
#include "mbus.h"
#include "PMUv7_RF.h"
// uncomment this for debug mbus message
//#define DEBUG_MBUS_MSG
// AM stack
#define PMU_ADDR 0x6
#define WAKEUP_PERIOD_PARKING 60000 // About 2 hours (PRCv17)
// System parameters
#define MBUS_DELAY 100 // Amount of delay between successive messages; 100: 6-7ms
#define WAKEUP_PERIOD_LDO 5 // About 1 sec (PRCv17)
#define DATA_STORAGE_SIZE 10 // Need to leave about 500 Bytes for stack --> around 60 words
#define TEMP_NUM_MEAS 1
#define TIMERWD_VAL 0xFFFFF // 0xFFFFF about 13 sec with Y5 run default clock (PRCv17)
#define TIMER32_VAL 0x50000 // 0x20000 about 1 sec with Y5 run default clock (PRCv17)
#define GPIO_SDA 5
#define GPIO_SCL 6
//********************************************************************
// Global Variables
//********************************************************************
// "static" limits the variables to this file, giving compiler more freedom
// "volatile" should only be used for MMIO --> ensures memory storage
volatile uint32_t irq_history;
volatile uint32_t enumerated;
volatile uint32_t wakeup_data;
volatile uint32_t stack_state;
volatile uint32_t wfi_timeout_flag;
volatile uint32_t exec_count;
volatile uint32_t meas_count;
volatile uint32_t exec_count_irq;
volatile uint32_t PMU_ADC_3P0_VAL;
volatile uint32_t pmu_parkinglot_mode;
volatile uint32_t pmu_sar_conv_ratio_val;
volatile uint32_t read_data_batadc;
volatile uint32_t sleep_time_prev;
volatile uint32_t sleep_time_threshold_factor;
volatile uint32_t wakeup_period_calc_factor;
volatile uint32_t WAKEUP_PERIOD_CONT_USER;
volatile uint32_t WAKEUP_PERIOD_CONT;
volatile uint32_t WAKEUP_PERIOD_CONT_INIT;
volatile uint32_t pmu_setting_temp_vals[3] = {0};
volatile uint32_t data_storage_count;
volatile uint32_t sns_running;
volatile uint32_t set_sns_exec_count;
volatile prev17_r0B_t prev17_r0B = PREv17_R0B_DEFAULT;
volatile prev17_r0D_t prev17_r0D = PREv17_R0D_DEFAULT;
//***************************************************
// SHT35 Functions
//***************************************************
static void operation_i2c_start(void);
static void operation_i2c_stop(void);
static void operation_i2c_addr(uint8_t addr, uint8_t RWn);
static void operation_i2c_cmd(uint8_t cmd);
static void operation_i2c_rd(uint8_t ACK);
static void operation_gpio_stop(void);
//***************************************************
// Sleep Functions
//***************************************************
static void operation_sleep(void);
static void operation_sleep_noirqreset(void);
//*******************************************************************
// INTERRUPT HANDLERS (Updated for PRCv17)
//*******************************************************************
void handler_ext_int_wakeup (void) __attribute__ ((interrupt ("IRQ")));
void handler_ext_int_gocep (void) __attribute__ ((interrupt ("IRQ")));
void handler_ext_int_timer32 (void) __attribute__ ((interrupt ("IRQ")));
void handler_ext_int_reg0 (void) __attribute__ ((interrupt ("IRQ")));
void handler_ext_int_reg1 (void) __attribute__ ((interrupt ("IRQ")));
void handler_ext_int_reg2 (void) __attribute__ ((interrupt ("IRQ")));
void handler_ext_int_reg3 (void) __attribute__ ((interrupt ("IRQ")));
void handler_ext_int_timer32(void) { // TIMER32
*NVIC_ICPR = (0x1 << IRQ_TIMER32);
*REG1 = *TIMER32_CNT;
*REG2 = *TIMER32_STAT;
*TIMER32_STAT = 0x0;
wfi_timeout_flag = 1;
}
void handler_ext_int_reg0(void) { // REG0
*NVIC_ICPR = (0x1 << IRQ_REG0);
}
void handler_ext_int_reg1(void) { // REG1
*NVIC_ICPR = (0x1 << IRQ_REG1);
}
void handler_ext_int_reg2(void) { // REG2
*NVIC_ICPR = (0x1 << IRQ_REG2);
}
void handler_ext_int_reg3(void) { // REG3
*NVIC_ICPR = (0x1 << IRQ_REG3);
}
void handler_ext_int_gocep(void) { // GOCEP
*NVIC_ICPR = (0x1 << IRQ_GOCEP);
}
void handler_ext_int_wakeup(void) { // WAKE-UP
//[ 0] = GOC/EP
//[ 1] = Wakeuptimer
//[ 2] = XO timer
//[ 3] = gpio_pad
//[ 4] = mbus message
//[ 8] = gpio[0]
//[ 9] = gpio[1]
//[10] = gpio[2]
//[11] = gpio[3]
*NVIC_ICPR = (0x1 << IRQ_WAKEUP);
}
//***************************************************
// ADXL362 Functions
//***************************************************
static void operation_i2c_start(){
// Enable GPIO OUTPUT
unfreeze_gpio_out();
gpio_write_data((1<<GPIO_SDA) | (1<<GPIO_SCL));
set_gpio_pad((1<<GPIO_SDA) | (1<<GPIO_SCL));
gpio_set_dir((1<<GPIO_SDA) | (1<<GPIO_SCL));
//Start
gpio_write_data((0<<GPIO_SDA) | (1<<GPIO_SCL));
gpio_write_data((0<<GPIO_SDA) | (0<<GPIO_SCL));
}
static void operation_i2c_stop(){
// Stop
gpio_write_data((0<<GPIO_SDA) | (1<<GPIO_SCL));
gpio_write_data((1<<GPIO_SDA) | (1<<GPIO_SCL));
}
static void operation_i2c_addr(uint8_t addr, uint8_t RWn){
//Assume started
//[6]
gpio_set_dir((1<<GPIO_SDA) | (1<<GPIO_SCL));
gpio_write_data((((addr>>6)&0x1)<<GPIO_SDA) | (0<<GPIO_SCL));
gpio_write_data((((addr>>6)&0x1)<<GPIO_SDA) | (1<<GPIO_SCL));
gpio_write_data((((addr>>6)&0x1)<<GPIO_SDA) | (0<<GPIO_SCL));
//[5]
gpio_write_data((((addr>>5)&0x1)<<GPIO_SDA) | (0<<GPIO_SCL));
gpio_write_data((((addr>>5)&0x1)<<GPIO_SDA) | (1<<GPIO_SCL));
gpio_write_data((((addr>>5)&0x1)<<GPIO_SDA) | (0<<GPIO_SCL));
//[4]
gpio_write_data((((addr>>4)&0x1)<<GPIO_SDA) | (0<<GPIO_SCL));
gpio_write_data((((addr>>4)&0x1)<<GPIO_SDA) | (1<<GPIO_SCL));
gpio_write_data((((addr>>4)&0x1)<<GPIO_SDA) | (0<<GPIO_SCL));
//[3]
gpio_write_data((((addr>>3)&0x1)<<GPIO_SDA) | (0<<GPIO_SCL));
gpio_write_data((((addr>>3)&0x1)<<GPIO_SDA) | (1<<GPIO_SCL));
gpio_write_data((((addr>>3)&0x1)<<GPIO_SDA) | (0<<GPIO_SCL));
//[2]
gpio_write_data((((addr>>2)&0x1)<<GPIO_SDA) | (0<<GPIO_SCL));
gpio_write_data((((addr>>2)&0x1)<<GPIO_SDA) | (1<<GPIO_SCL));
gpio_write_data((((addr>>2)&0x1)<<GPIO_SDA) | (0<<GPIO_SCL));
//[1]
gpio_write_data((((addr>>1)&0x1)<<GPIO_SDA) | (0<<GPIO_SCL));
gpio_write_data((((addr>>1)&0x1)<<GPIO_SDA) | (1<<GPIO_SCL));
gpio_write_data((((addr>>1)&0x1)<<GPIO_SDA) | (0<<GPIO_SCL));
//[0]
gpio_write_data((((addr>>0)&0x1)<<GPIO_SDA) | (0<<GPIO_SCL));
gpio_write_data((((addr>>0)&0x1)<<GPIO_SDA) | (1<<GPIO_SCL));
gpio_write_data((((addr>>0)&0x1)<<GPIO_SDA) | (0<<GPIO_SCL));
//WRITEn/READ
//Need Hack
if((RWn&0x1) == 1){ //Need hack
gpio_set_dir((0<<GPIO_SDA) | (1<<GPIO_SCL));
gpio_write_data(0<<GPIO_SCL);
gpio_write_data(1<<GPIO_SCL);
gpio_write_data(0<<GPIO_SCL);
}
else{
gpio_write_data((0<<GPIO_SDA) | (0<<GPIO_SCL));
gpio_write_data((0<<GPIO_SDA) | (1<<GPIO_SCL));
gpio_write_data((0<<GPIO_SDA) | (0<<GPIO_SCL));
}
//Wait for ACK
gpio_set_dir((0<<GPIO_SDA) | (1<<GPIO_SCL));
while((*GPIO_DATA>>GPIO_SDA)&0x1){
//mbus_write_message32(0xCE, *GPIO_DATA);
}
gpio_write_data(0<<GPIO_SCL);
gpio_write_data(1<<GPIO_SCL);
gpio_write_data(0<<GPIO_SCL);
}
static void operation_i2c_cmd(uint8_t cmd){
gpio_set_dir((1<<GPIO_SDA) | (1<<GPIO_SCL));
//[7]
gpio_write_data((((cmd>>7)&0x1)<<GPIO_SDA) | (0<<GPIO_SCL));
gpio_write_data((((cmd>>7)&0x1)<<GPIO_SDA) | (1<<GPIO_SCL));
gpio_write_data((((cmd>>7)&0x1)<<GPIO_SDA) | (0<<GPIO_SCL));
//[6]
gpio_write_data((((cmd>>6)&0x1)<<GPIO_SDA) | (0<<GPIO_SCL));
gpio_write_data((((cmd>>6)&0x1)<<GPIO_SDA) | (1<<GPIO_SCL));
gpio_write_data((((cmd>>6)&0x1)<<GPIO_SDA) | (0<<GPIO_SCL));
//[5]
gpio_write_data((((cmd>>5)&0x1)<<GPIO_SDA) | (0<<GPIO_SCL));
gpio_write_data((((cmd>>5)&0x1)<<GPIO_SDA) | (1<<GPIO_SCL));
gpio_write_data((((cmd>>5)&0x1)<<GPIO_SDA) | (0<<GPIO_SCL));
//[4]
gpio_write_data((((cmd>>4)&0x1)<<GPIO_SDA) | (0<<GPIO_SCL));
gpio_write_data((((cmd>>4)&0x1)<<GPIO_SDA) | (1<<GPIO_SCL));
gpio_write_data((((cmd>>4)&0x1)<<GPIO_SDA) | (0<<GPIO_SCL));
//[3]
gpio_write_data((((cmd>>3)&0x1)<<GPIO_SDA) | (0<<GPIO_SCL));
gpio_write_data((((cmd>>3)&0x1)<<GPIO_SDA) | (1<<GPIO_SCL));
gpio_write_data((((cmd>>3)&0x1)<<GPIO_SDA) | (0<<GPIO_SCL));
//[2]
gpio_write_data((((cmd>>2)&0x1)<<GPIO_SDA) | (0<<GPIO_SCL));
gpio_write_data((((cmd>>2)&0x1)<<GPIO_SDA) | (1<<GPIO_SCL));
gpio_write_data((((cmd>>2)&0x1)<<GPIO_SDA) | (0<<GPIO_SCL));
//[1]
gpio_write_data((((cmd>>1)&0x1)<<GPIO_SDA) | (0<<GPIO_SCL));
gpio_write_data((((cmd>>1)&0x1)<<GPIO_SDA) | (1<<GPIO_SCL));
gpio_write_data((((cmd>>1)&0x1)<<GPIO_SDA) | (0<<GPIO_SCL));
//[0]
if((cmd&0x1) == 1){ //Need hack
gpio_set_dir((0<<GPIO_SDA) | (1<<GPIO_SCL));
gpio_write_data(0<<GPIO_SCL);
gpio_write_data(1<<GPIO_SCL);
gpio_write_data(0<<GPIO_SCL);
}
else{
gpio_write_data((0<<GPIO_SDA) | (0<<GPIO_SCL));
gpio_write_data((0<<GPIO_SDA) | (1<<GPIO_SCL));
gpio_write_data((0<<GPIO_SDA) | (0<<GPIO_SCL));
}
//Wait for ACK
gpio_set_dir((0<<GPIO_SDA) | (1<<GPIO_SCL));
while((*GPIO_DATA>>GPIO_SDA)&0x1){
//mbus_write_message32(0xCF, *GPIO_DATA);
}
gpio_write_data(0<<GPIO_SCL);
gpio_write_data(1<<GPIO_SCL);
gpio_write_data(0<<GPIO_SCL);
}
static void operation_i2c_rd(uint8_t ACK){
uint8_t data;
data = 0;
gpio_set_dir((0<<GPIO_SDA) | (1<<GPIO_SCL));
//[7]
gpio_write_data(0<<GPIO_SCL);
gpio_write_data(1<<GPIO_SCL);
data = data | ((*GPIO_DATA>>GPIO_SDA&0x1)<<7);
//[6]
gpio_write_data(0<<GPIO_SCL);
gpio_write_data(1<<GPIO_SCL);
data = data | ((*GPIO_DATA>>GPIO_SDA&0x1)<<6);
//[5]
gpio_write_data(0<<GPIO_SCL);
gpio_write_data(1<<GPIO_SCL);
data = data | ((*GPIO_DATA>>GPIO_SDA&0x1)<<5);
//[4]
gpio_write_data(0<<GPIO_SCL);
gpio_write_data(1<<GPIO_SCL);
data = data | ((*GPIO_DATA>>GPIO_SDA&0x1)<<4);
//[3]
gpio_write_data(0<<GPIO_SCL);
gpio_write_data(1<<GPIO_SCL);
data = data | ((*GPIO_DATA>>GPIO_SDA&0x1)<<3);
//[2]
gpio_write_data(0<<GPIO_SCL);
gpio_write_data(1<<GPIO_SCL);
data = data | ((*GPIO_DATA>>GPIO_SDA&0x1)<<2);
//[1]
gpio_write_data(0<<GPIO_SCL);
gpio_write_data(1<<GPIO_SCL);
data = data | ((*GPIO_DATA>>GPIO_SDA&0x1)<<1);
//[0]
gpio_write_data(0<<GPIO_SCL);
gpio_write_data(1<<GPIO_SCL);
data = data | ((*GPIO_DATA>>GPIO_SDA&0x1)<<0);
gpio_write_data(0<<GPIO_SCL);
if (ACK&0x1){
gpio_write_data((0<<GPIO_SDA) | (0<<GPIO_SCL));
gpio_set_dir((1<<GPIO_SDA) | (1<<GPIO_SCL));
gpio_write_data((0<<GPIO_SDA) | (1<<GPIO_SCL));
gpio_write_data((0<<GPIO_SDA) | (0<<GPIO_SCL));
}
else{
gpio_write_data(1<<GPIO_SCL);
gpio_write_data(0<<GPIO_SCL);
}
mbus_write_message32(0xCF, data);
}
static void operation_gpio_stop(){
freeze_gpio_out();
}
//************************************
// PMU Related Functions
//************************************
static void pmu_set_sar_override(uint32_t val){
// SAR_RATIO_OVERRIDE
mbus_remote_register_write(PMU_ADDR,0x05, //default 12'h000
( (0 << 13) // Enables override setting [12] (1'b1)
| (0 << 12) // Let VDD_CLK always connected to vbat
| (1 << 11) // Enable override setting [10] (1'h0)
| (0 << 10) // Have the converter have the periodic reset (1'h0)
| (1 << 9) // Enable override setting [8] (1'h0)
| (0 << 8) // Switch input / output power rails for upconversion (1'h0)
| (1 << 7) // Enable override setting [6:0] (1'h0)
| (val) // Binary converter's conversion ratio (7'h00)
));
delay(MBUS_DELAY*2);
mbus_remote_register_write(PMU_ADDR,0x05, //default 12'h000
( (1 << 13) // Enables override setting [12] (1'b1)
| (0 << 12) // Let VDD_CLK always connected to vbat
| (1 << 11) // Enable override setting [10] (1'h0)
| (0 << 10) // Have the converter have the periodic reset (1'h0)
| (1 << 9) // Enable override setting [8] (1'h0)
| (0 << 8) // Switch input / output power rails for upconversion (1'h0)
| (1 << 7) // Enable override setting [6:0] (1'h0)
| (val) // Binary converter's conversion ratio (7'h00)
));
delay(MBUS_DELAY*2);
}
inline static void pmu_set_adc_period(uint32_t val){
// PMU_CONTROLLER_DESIRED_STATE Active
mbus_remote_register_write(PMU_ADDR,0x3C,
(( 1 << 0) //state_sar_scn_on
| (0 << 1) //state_wait_for_clock_cycles
| (1 << 2) //state_wait_for_time
| (1 << 3) //state_sar_scn_reset
| (1 << 4) //state_sar_scn_stabilized
| (1 << 5) //state_sar_scn_ratio_roughly_adjusted
| (1 << 6) //state_clock_supply_switched
| (1 << 7) //state_control_supply_switched
| (1 << 8) //state_upconverter_on
| (1 << 9) //state_upconverter_stabilized
| (1 << 10) //state_refgen_on
| (0 << 11) //state_adc_output_ready
| (0 << 12) //state_adc_adjusted
| (0 << 13) //state_sar_scn_ratio_adjusted
| (1 << 14) //state_downconverter_on
| (1 << 15) //state_downconverter_stabilized
| (1 << 16) //state_vdd_3p6_turned_on
| (1 << 17) //state_vdd_1p2_turned_on
| (1 << 18) //state_vdd_0P6_turned_on
| (1 << 19) //state_state_horizon
));
delay(MBUS_DELAY*10);
// Register 0x36: TICK_REPEAT_VBAT_ADJUST
mbus_remote_register_write(PMU_ADDR,0x36,val);
delay(MBUS_DELAY*10);
// Register 0x33: TICK_ADC_RESET
mbus_remote_register_write(PMU_ADDR,0x33,2);
delay(MBUS_DELAY);
// Register 0x34: TICK_ADC_CLK
mbus_remote_register_write(PMU_ADDR,0x34,2);
delay(MBUS_DELAY);
// PMU_CONTROLLER_DESIRED_STATE Active
mbus_remote_register_write(PMU_ADDR,0x3C,
(( 1 << 0) //state_sar_scn_on
| (1 << 1) //state_wait_for_clock_cycles
| (1 << 2) //state_wait_for_time
| (1 << 3) //state_sar_scn_reset
| (1 << 4) //state_sar_scn_stabilized
| (1 << 5) //state_sar_scn_ratio_roughly_adjusted
| (1 << 6) //state_clock_supply_switched
| (1 << 7) //state_control_supply_switched
| (1 << 8) //state_upconverter_on
| (1 << 9) //state_upconverter_stabilized
| (1 << 10) //state_refgen_on
| (0 << 11) //state_adc_output_ready
| (0 << 12) //state_adc_adjusted
| (0 << 13) //state_sar_scn_ratio_adjusted
| (1 << 14) //state_downconverter_on
| (1 << 15) //state_downconverter_stabilized
| (1 << 16) //state_vdd_3p6_turned_on
| (1 << 17) //state_vdd_1p2_turned_on
| (1 << 18) //state_vdd_0P6_turned_on
| (1 << 19) //state_state_horizon
));
delay(MBUS_DELAY);
}
inline static void pmu_set_active_clk(uint8_t r, uint8_t l, uint8_t base, uint8_t l_1p2){
// The first register write to PMU needs to be repeated
// Register 0x16: V1P2 Active
mbus_remote_register_write(PMU_ADDR,0x16,
( (0 << 19) // Enable PFM even during periodic reset
| (0 << 18) // Enable PFM even when Vref is not used as ref
| (0 << 17) // Enable PFM
| (3 << 14) // Comparator clock division ratio
| (0 << 13) // Enable main feedback loop
| (r << 9) // Frequency multiplier R
| (l_1p2 << 5) // Frequency multiplier L (actually L+1)
| (base) // Floor frequency base (0-63)
));
delay(MBUS_DELAY);
mbus_remote_register_write(PMU_ADDR,0x16,
( (0 << 19) // Enable PFM even during periodic reset
| (0 << 18) // Enable PFM even when Vref is not used as ref
| (0 << 17) // Enable PFM
| (3 << 14) // Comparator clock division ratio
| (0 << 13) // Enable main feedback loop
| (r << 9) // Frequency multiplier R
| (l_1p2 << 5) // Frequency multiplier L (actually L+1)
| (base) // Floor frequency base (0-63)
));
delay(MBUS_DELAY);
// Register 0x18: V3P6 Active
mbus_remote_register_write(PMU_ADDR,0x18,
( (3 << 14) // Desired Vout/Vin ratio; defualt: 0
| (0 << 13) // Enable main feedback loop
| (r << 9) // Frequency multiplier R
| (l << 5) // Frequency multiplier L (actually L+1)
| (base) // Floor frequency base (0-63)
));
delay(MBUS_DELAY);
// Register 0x1A: V0P6 Active
mbus_remote_register_write(PMU_ADDR,0x1A,
( (0 << 13) // Enable main feedback loop
| (r << 9) // Frequency multiplier R
| (l << 5) // Frequency multiplier L (actually L+1)
| (base) // Floor frequency base (0-63)
));
delay(MBUS_DELAY);
}
inline static void pmu_set_sleep_clk(uint8_t r, uint8_t l, uint8_t base, uint8_t l_1p2){
// Register 0x17: V3P6 Sleep
mbus_remote_register_write(PMU_ADDR,0x17,
( (3 << 14) // Desired Vout/Vin ratio; defualt: 0
| (0 << 13) // Enable main feedback loop
| (r << 9) // Frequency multiplier R
| (l << 5) // Frequency multiplier L (actually L+1)
| (base) // Floor frequency base (0-63)
));
delay(MBUS_DELAY);
// Register 0x15: V1P2 Sleep
mbus_remote_register_write(PMU_ADDR,0x15,
( (0 << 19) // Enable PFM even during periodic reset
| (0 << 18) // Enable PFM even when Vref is not used as ref
| (0 << 17) // Enable PFM
| (3 << 14) // Comparator clock division ratio
| (0 << 13) // Enable main feedback loop
| (r << 9) // Frequency multiplier R
| (l_1p2 << 5) // Frequency multiplier L (actually L+1)
| (base) // Floor frequency base (0-63)
));
delay(MBUS_DELAY);
// Register 0x19: V0P6 Sleep
mbus_remote_register_write(PMU_ADDR,0x19,
( (0 << 13) // Enable main feedback loop
| (r << 9) // Frequency multiplier R
| (l << 5) // Frequency multiplier L (actually L+1)
| (base) // Floor frequency base (0-63)
));
delay(MBUS_DELAY);
}
inline static void pmu_set_clk_init(){
pmu_set_active_clk(0xA,0x1,0x10,0x2);
pmu_set_sleep_clk(0xF,0x0,0x1,0x1);
// SAR_RATIO_OVERRIDE
// Use the new reset scheme in PMUv3
mbus_remote_register_write(PMU_ADDR,0x05, //default 12'h000
( (0 << 13) // Enables override setting [12] (1'b1)
| (0 << 12) // Let VDD_CLK always connected to vbat
| (1 << 11) // Enable override setting [10] (1'h0)
| (0 << 10) // Have the converter have the periodic reset (1'h0)
| (0 << 9) // Enable override setting [8] (1'h0)
| (0 << 8) // Switch input / output power rails for upconversion (1'h0)
| (0 << 7) // Enable override setting [6:0] (1'h0)
| (0x45) // Binary converter's conversion ratio (7'h00)
));
delay(MBUS_DELAY);
pmu_set_sar_override(0x4D);
pmu_set_adc_period(1); // 0x100 about 1 min for 1/2/1 1P2 setting
}
inline static void pmu_adc_reset_setting(){
// PMU ADC will be automatically reset when system wakes up
// PMU_CONTROLLER_DESIRED_STATE Active
mbus_remote_register_write(PMU_ADDR,0x3C,
(( 1 << 0) //state_sar_scn_on
| (1 << 1) //state_wait_for_clock_cycles
| (1 << 2) //state_wait_for_time
| (1 << 3) //state_sar_scn_reset
| (1 << 4) //state_sar_scn_stabilized
| (1 << 5) //state_sar_scn_ratio_roughly_adjusted
| (1 << 6) //state_clock_supply_switched
| (1 << 7) //state_control_supply_switched
| (1 << 8) //state_upconverter_on
| (1 << 9) //state_upconverter_stabilized
| (1 << 10) //state_refgen_on
| (0 << 11) //state_adc_output_ready
| (0 << 12) //state_adc_adjusted
| (0 << 13) //state_sar_scn_ratio_adjusted
| (1 << 14) //state_downconverter_on
| (1 << 15) //state_downconverter_stabilized
| (1 << 16) //state_vdd_3p6_turned_on
| (1 << 17) //state_vdd_1p2_turned_on
| (1 << 18) //state_vdd_0P6_turned_on
| (1 << 19) //state_state_horizon
));
delay(MBUS_DELAY);
}
inline static void pmu_adc_disable(){
// PMU ADC will be automatically reset when system wakes up
// PMU_CONTROLLER_DESIRED_STATE Sleep
mbus_remote_register_write(PMU_ADDR,0x3B,
(( 1 << 0) //state_sar_scn_on
| (1 << 1) //state_wait_for_clock_cycles
| (1 << 2) //state_wait_for_time
| (1 << 3) //state_sar_scn_reset
| (1 << 4) //state_sar_scn_stabilized
| (1 << 5) //state_sar_scn_ratio_roughly_adjusted
| (1 << 6) //state_clock_supply_switched
| (1 << 7) //state_control_supply_switched
| (1 << 8) //state_upconverter_on
| (1 << 9) //state_upconverter_stabilized
| (1 << 10) //state_refgen_on
| (0 << 11) //state_adc_output_ready
| (0 << 12) //state_adc_adjusted
| (0 << 13) //state_sar_scn_ratio_adjusted
| (1 << 14) //state_downconverter_on
| (1 << 15) //state_downconverter_stabilized
| (1 << 16) //state_vdd_3p6_turned_on
| (1 << 17) //state_vdd_1p2_turned_on
| (1 << 18) //state_vdd_0P6_turned_on
| (1 << 19) //state_state_horizon
));
delay(MBUS_DELAY);
}
inline static void pmu_adc_enable(){
// PMU ADC will be automatically reset when system wakes up
// PMU_CONTROLLER_DESIRED_STATE Sleep
mbus_remote_register_write(PMU_ADDR,0x3B,
(( 1 << 0) //state_sar_scn_on
| (1 << 1) //state_wait_for_clock_cycles
| (1 << 2) //state_wait_for_time
| (1 << 3) //state_sar_scn_reset
| (1 << 4) //state_sar_scn_stabilized
| (1 << 5) //state_sar_scn_ratio_roughly_adjusted
| (1 << 6) //state_clock_supply_switched
| (1 << 7) //state_control_supply_switched
| (1 << 8) //state_upconverter_on
| (1 << 9) //state_upconverter_stabilized
| (1 << 10) //state_refgen_on
| (1 << 11) //state_adc_output_ready
| (0 << 12) //state_adc_adjusted // Turning off offset cancellation
| (1 << 13) //state_sar_scn_ratio_adjusted
| (1 << 14) //state_downconverter_on
| (1 << 15) //state_downconverter_stabilized
| (1 << 16) //state_vdd_3p6_turned_on
| (1 << 17) //state_vdd_1p2_turned_on
| (1 << 18) //state_vdd_0P6_turned_on
| (1 << 19) //state_state_horizon
));
delay(MBUS_DELAY);
}
inline static void pmu_adc_read_latest(){
// Grab latest PMU ADC readings
// PMU register read is handled differently
mbus_remote_register_write(PMU_ADDR,0x00,0x03);
delay(MBUS_DELAY);
read_data_batadc = *((volatile uint32_t *) REG0) & 0xFF;
}
inline static void pmu_parkinglot_decision_3v_battery(){
// Battery > 3.0V
if (read_data_batadc < (PMU_ADC_3P0_VAL)){
pmu_set_sar_override(0x3C);
// Battery 2.9V - 3.0V
}else if (read_data_batadc < PMU_ADC_3P0_VAL + 4){
pmu_set_sar_override(0x3F);
// Battery 2.8V - 2.9V
}else if (read_data_batadc < PMU_ADC_3P0_VAL + 8){
pmu_set_sar_override(0x41);
// Battery 2.7V - 2.8V
}else if (read_data_batadc < PMU_ADC_3P0_VAL + 12){
pmu_set_sar_override(0x43);
// Battery 2.6V - 2.7V
}else if (read_data_batadc < PMU_ADC_3P0_VAL + 17){
pmu_set_sar_override(0x45);
// Battery 2.5V - 2.6V
}else if (read_data_batadc < PMU_ADC_3P0_VAL + 21){
pmu_set_sar_override(0x48);
// Battery 2.4V - 2.5V
}else if (read_data_batadc < PMU_ADC_3P0_VAL + 27){
pmu_set_sar_override(0x4B);
// Battery 2.3V - 2.4V
}else if (read_data_batadc < PMU_ADC_3P0_VAL + 32){
pmu_set_sar_override(0x4E);
// Battery 2.2V - 2.3V
}else if (read_data_batadc < PMU_ADC_3P0_VAL + 39){
pmu_set_sar_override(0x51);
// Battery 2.1V - 2.2V
}else if (read_data_batadc < PMU_ADC_3P0_VAL + 46){
pmu_set_sar_override(0x56);
// Battery 2.0V - 2.1V
}else if (read_data_batadc < PMU_ADC_3P0_VAL + 53){
pmu_set_sar_override(0x5A);
// Battery <= 2.0V
}else if (read_data_batadc < PMU_ADC_3P0_VAL + 53){
pmu_set_sar_override(0x5F);
}else{
// Brown out
pmu_set_sar_override(0x65);
// Go to sleep without timer
operation_sleep();
}
}
inline static void pmu_reset_solar_short(){
mbus_remote_register_write(PMU_ADDR,0x0E,
( (1 << 10) // When to turn on harvester-inhibiting switch (0: PoR, 1: VBAT high)
| (1 << 9) // Enables override setting [8]
| (0 << 8) // Turn on the harvester-inhibiting switch
| (1 << 4) // clamp_tune_bottom (increases clamp thresh)
| (0) // clamp_tune_top (decreases clamp thresh)
));
delay(MBUS_DELAY);
mbus_remote_register_write(PMU_ADDR,0x0E,
( (1 << 10) // When to turn on harvester-inhibiting switch (0: PoR, 1: VBAT high)
| (0 << 9) // Enables override setting [8]
| (0 << 8) // Turn on the harvester-inhibiting switch
| (1 << 4) // clamp_tune_bottom (increases clamp thresh)
| (0) // clamp_tune_top (decreases clamp thresh)
));
delay(MBUS_DELAY);
}
//***************************************************
// End of Program Sleep Operation
//***************************************************
static void operation_sleep(void){
// Reset GOC_DATA_IRQ
*GOC_DATA_IRQ = 0;
// Go to Sleep
mbus_sleep_all();
while(1);
}
static void operation_sleep_noirqreset(void){
// Go to Sleep
mbus_sleep_all();
while(1);
}
static void operation_init(void){
// Set CPU & Mbus Clock Speeds
prev17_r0B.CLK_GEN_RING = 0x1; // Default 0x1
prev17_r0B.CLK_GEN_DIV_MBC = 0x1; // Default 0x1
prev17_r0B.CLK_GEN_DIV_CORE = 0x3; // Default 0x3
prev17_r0B.GOC_CLK_GEN_SEL_DIV = 0x0; // Default 0x0
prev17_r0B.GOC_CLK_GEN_SEL_FREQ = 0x6; // Default 0x6
*REG_CLKGEN_TUNE = prev17_r0B.as_int;
prev17_r0D.SRAM_TUNE_ASO_DLY = 31; // Default 0x0, 5 bits
prev17_r0D.SRAM_TUNE_DECODER_DLY = 15; // Default 0x2, 4 bits
prev17_r0D.SRAM_USE_INVERTER_SA= 1;
*REG_SRAM_TUNE = prev17_r0D.as_int;
//Enumerate & Initialize Registers
enumerated = 0xDEADBE13;
exec_count = 0;
exec_count_irq = 0;
PMU_ADC_3P0_VAL = 0x62;
pmu_parkinglot_mode = 3;
// Set CPU Halt Option as RX --> Use for register read e.g.
// set_halt_until_mbus_rx();
//Enumeration
mbus_enumerate(PMU_ADDR);
delay(MBUS_DELAY);
// Set CPU Halt Option as TX --> Use for register write e.g.
// set_halt_until_mbus_tx();
// PMU Settings ----------------------------------------------
pmu_set_clk_init();
pmu_reset_solar_short();
// Disable PMU ADC measurement in active mode
// PMU_CONTROLLER_STALL_ACTIVE
mbus_remote_register_write(PMU_ADDR,0x3A,
( (1 << 19) // ignore state_horizon; default 1
| (1 << 13) // ignore adc_output_ready; default 0
| (1 << 12) // ignore adc_output_ready; default 0
| (1 << 11) // ignore adc_output_ready; default 0
));
delay(MBUS_DELAY);
pmu_adc_reset_setting();
delay(MBUS_DELAY);
pmu_adc_enable();
delay(MBUS_DELAY);
// Initialize other global variables
WAKEUP_PERIOD_CONT = 33750; // 1: 2-4 sec with PRCv9
WAKEUP_PERIOD_CONT_INIT = 3; // 0x1E (30): ~1 min with PRCv9
data_storage_count = 0;
wakeup_data = 0;
// Go to sleep without timer
//operation_sleep();
}
//********************************************************************
// MAIN function starts here
//********************************************************************
int main(){
// Only enable relevant interrupts (PRCv17)
//enable_reg_irq();
//enable_all_irq();
*NVIC_ISER = (1 << IRQ_WAKEUP) | (1 << IRQ_GOCEP) | (1 << IRQ_TIMER32) | (1 << IRQ_REG0)| (1 << IRQ_REG1)| (1 << IRQ_REG2)| (1 << IRQ_REG3);
// Config watchdog timer to about 10 sec; default: 0x02FFFFFF
config_timerwd(TIMERWD_VAL);
// Initialization sequence
if (enumerated != 0xDEADBE13){
operation_init();
}
*REG_CPS = 1;
delay(1000);
operation_i2c_start();
operation_i2c_addr(0x44,0);
operation_i2c_cmd(0x24);
operation_i2c_cmd(0x0B);
operation_i2c_stop();
delay(1000);
operation_i2c_start();
operation_i2c_addr(0x44,0x1);
operation_i2c_rd(0x1);
operation_i2c_rd(0x1);
operation_i2c_rd(0x1);
operation_i2c_rd(0x1);
operation_i2c_rd(0x1);
operation_i2c_rd(0x0);
operation_i2c_stop();
*REG_CPS = 0;
delay(5000);
*REG_CPS = 1;
delay(1000);
operation_i2c_start();
operation_i2c_addr(0x44,0);
operation_i2c_cmd(0x24);
operation_i2c_cmd(0x0B);
operation_i2c_stop();
delay(1000);
operation_i2c_start();
operation_i2c_addr(0x44,0x1);
operation_i2c_rd(0x1);
operation_i2c_rd(0x1);
operation_i2c_rd(0x1);
operation_i2c_rd(0x1);
operation_i2c_rd(0x1);
operation_i2c_rd(0x0);
operation_i2c_stop();
*REG_CPS = 0;
//operation_i2c_start();
//operation_i2c_addr(0x44,0x0);
//operation_i2c_cmd(0x30);
//operation_i2c_cmd(0xA2);
//operation_i2c_stop();
//operation_i2c_addr(0x44,0x1);
//operation_i2c_rd();
//operation_i2c_stop();
while(1);
}
|
503028.c | /****************************************************************************
*
* Copyright 2016 Samsung Electronics All Rights Reserved.
*
* 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.
*
****************************************************************************/
/************************************************************************
* mm/kmm_heap/kmm_initialize.c
*
* Copyright (C) 2013-2014 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name NuttX 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.
*
************************************************************************/
/************************************************************************
* Included Files
************************************************************************/
#include <tinyara/config.h>
#include <tinyara/mm/mm.h>
#ifdef CONFIG_MM_KERNEL_HEAP
/************************************************************************
* Pre-processor definition
************************************************************************/
/************************************************************************
* Private Types
************************************************************************/
/************************************************************************
* Public Data
************************************************************************/
/************************************************************************
* Private Functions
************************************************************************/
/************************************************************************
* Public Functions
************************************************************************/
/************************************************************************
* Name: kmm_initialize
*
* Description:
* Initialize the kernel heap data structures, providing the initial
* heap region.
*
* Parameters:
* heap_start - Address of the beginning of the (initial) memory region
* heap_size - The size (in bytes) if the (initial) memory region.
*
* Return Value:
* OK on success, negative errno on failure.
*
************************************************************************/
int kmm_initialize(FAR void *heap_start, size_t heap_size)
{
return mm_initialize(kmm_get_baseheap(), heap_start, heap_size);
}
#endif /* CONFIG_MM_KERNEL_HEAP */
|
74058.c | /* $Id$ */
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "test.h"
#define THIS_FILE "test.c"
#define DO_TEST(test) do { \
PJ_LOG(3, (THIS_FILE, "Running %s...", #test)); \
rc = test; \
PJ_LOG(3, (THIS_FILE, \
"%s(%d)", \
(rc ? "..ERROR" : "..success"), rc)); \
if (rc!=0) goto on_return; \
} while (0)
pj_pool_factory *mem;
void app_perror(pj_status_t status, const char *msg)
{
char errbuf[PJ_ERR_MSG_SIZE];
pjmedia_strerror(status, errbuf, sizeof(errbuf));
PJ_LOG(3,(THIS_FILE, "%s: %s", msg, errbuf));
}
/* Force linking PLC stuff if G.711 is disabled. See:
* https://trac.pjsip.org/repos/ticket/1337
*/
#if PJMEDIA_HAS_G711_CODEC==0
void *dummy()
{
// Dummy
return &pjmedia_plc_save;
}
#endif
int test_main(void)
{
int rc = 0;
pj_caching_pool caching_pool;
pj_pool_t *pool;
pj_init();
pj_caching_pool_init(&caching_pool, &pj_pool_factory_default_policy, 0);
pool = pj_pool_create(&caching_pool.factory, "test", 1000, 512, NULL);
pj_log_set_decor(PJ_LOG_HAS_NEWLINE);
pj_log_set_level(3);
mem = &caching_pool.factory;
pjmedia_event_mgr_create(pool, 0, NULL);
#if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0)
pjmedia_video_format_mgr_create(pool, 64, 0, NULL);
pjmedia_converter_mgr_create(pool, NULL);
pjmedia_vid_codec_mgr_create(pool, NULL);
#endif
#if HAS_VID_PORT_TEST
DO_TEST(vid_port_test());
#endif
#if HAS_VID_DEV_TEST
DO_TEST(vid_dev_test());
#endif
#if HAS_VID_CODEC_TEST
DO_TEST(vid_codec_test());
#endif
#if HAS_SDP_NEG_TEST
DO_TEST(sdp_neg_test());
#endif
//DO_TEST(sdp_test (&caching_pool.factory));
//DO_TEST(rtp_test(&caching_pool.factory));
//DO_TEST(session_test (&caching_pool.factory));
#if HAS_JBUF_TEST
DO_TEST(jbuf_main());
#endif
#if HAS_MIPS_TEST
DO_TEST(mips_test());
#endif
#if HAS_CODEC_VECTOR_TEST
DO_TEST(codec_test_vectors());
#endif
PJ_LOG(3,(THIS_FILE," "));
on_return:
if (rc != 0) {
PJ_LOG(3,(THIS_FILE,"Test completed with error(s)!"));
} else {
PJ_LOG(3,(THIS_FILE,"Looks like everything is okay!"));
}
#if defined(PJMEDIA_HAS_VIDEO) && (PJMEDIA_HAS_VIDEO != 0)
pjmedia_video_format_mgr_destroy(pjmedia_video_format_mgr_instance());
pjmedia_converter_mgr_destroy(pjmedia_converter_mgr_instance());
pjmedia_vid_codec_mgr_destroy(pjmedia_vid_codec_mgr_instance());
#endif
pjmedia_event_mgr_destroy(pjmedia_event_mgr_instance());
pj_pool_release(pool);
pj_caching_pool_destroy(&caching_pool);
return rc;
}
|
896450.c | /* File: cache.h */
/*
This file is a part of the Corrfunc package
Copyright (C) 2015-- Manodeep Sinha ([email protected])
License: MIT LICENSE. See LICENSE file under the top-level
directory at https://github.com/manodeep/Corrfunc/
*/
/*Taken from http://stackoverflow.com/questions/794632/programmatically-get-the-cache-line-size*/
// Author: Nick Strupat
// Date: October 29, 2010
// Returns the cache line size (in bytes) of the processor, or 0 on failure
/* BUG NOTE: Might be worthwhile to take the minimum cache linesize across all cpus
just in case the cpus have different caches. This has already happened on ARM
https://github.com/mono/mono/pull/3549
http://lists.infradead.org/pipermail/linux-arm-kernel/2016-September/453859.html
*/
#if defined(__APPLE__)
#include <sys/sysctl.h>
size_t cache_line_size(void)
{
size_t line_size = 0;
size_t sizeof_line_size = sizeof(line_size);
sysctlbyname("hw.cachelinesize", &line_size, &sizeof_line_size, 0, 0);
return line_size;
}
#elif defined(__linux__)
#include <stdio.h>
size_t cache_line_size(void)
{
FILE *fp = 0;
fp = fopen("/sys/devices/system/cpu/cpu0/cache/index0/coherency_line_size", "r");
size_t lineSize = 0;
if (fp) {
int nitems = fscanf(fp, "%zu", &lineSize);
if(nitems !=1) {
linesize=0;
}
fclose(fp);
}
return lineSize;
}
#else
#error Unrecognized platform
#endif
|
95696.c | #define a (2)
void main() {
int i, j=10, n=rand(), sn=0;
assume(n >= 0);
for(i=1; i<=n; i++) {
if (i<j)
sn = sn + a;
j--;
}
assert(sn==n*a || sn == 0);
}
|
569739.c | /*
* Copyright (c) 1984-2008, 2011-2015 Wind River Systems, Inc.
* SPDX-License-Identifier: Apache-2.0
*/
/*
* driver for x86 CPU local APIC (as an interrupt controller)
*/
#include <kernel.h>
#include <kernel_structs.h>
#include <arch/cpu.h>
#include <zephyr/types.h>
#include <string.h>
#include <misc/__assert.h>
#include <arch/x86/msr.h>
#include <toolchain.h>
#include <linker/sections.h>
#include <drivers/interrupt_controller/loapic.h> /* public API declarations */
#include <init.h>
#include <drivers/interrupt_controller/sysapic.h>
/* Local APIC Version Register Bits */
#define LOAPIC_VERSION_MASK 0x000000ff /* LO APIC Version mask */
#define LOAPIC_MAXLVT_MASK 0x00ff0000 /* LO APIC Max LVT mask */
#define LOAPIC_PENTIUM4 0x00000014 /* LO APIC in Pentium4 */
#define LOAPIC_LVT_PENTIUM4 5 /* LO APIC LVT - Pentium4 */
#define LOAPIC_LVT_P6 4 /* LO APIC LVT - P6 */
#define LOAPIC_LVT_P5 3 /* LO APIC LVT - P5 */
/* Local APIC Vector Table Bits */
#define LOAPIC_VECTOR 0x000000ff /* vectorNo */
#define LOAPIC_MODE 0x00000700 /* delivery mode */
#define LOAPIC_FIXED 0x00000000 /* delivery mode: FIXED */
#define LOAPIC_SMI 0x00000200 /* delivery mode: SMI */
#define LOAPIC_NMI 0x00000400 /* delivery mode: NMI */
#define LOAPIC_EXT 0x00000700 /* delivery mode: ExtINT */
#define LOAPIC_IDLE 0x00000000 /* delivery status: Idle */
#define LOAPIC_PEND 0x00001000 /* delivery status: Pend */
#define LOAPIC_HIGH 0x00000000 /* polarity: High */
#define LOAPIC_LOW 0x00002000 /* polarity: Low */
#define LOAPIC_REMOTE 0x00004000 /* remote IRR */
#define LOAPIC_EDGE 0x00000000 /* trigger mode: Edge */
#define LOAPIC_LEVEL 0x00008000 /* trigger mode: Level */
/* Local APIC Spurious-Interrupt Register Bits */
#define LOAPIC_ENABLE 0x100 /* APIC Enabled */
#define LOAPIC_FOCUS_DISABLE 0x200 /* Focus Processor Checking */
#if CONFIG_LOAPIC_SPURIOUS_VECTOR_ID == -1
#define LOAPIC_SPURIOUS_VECTOR_ID (CONFIG_IDT_NUM_VECTORS - 1)
#else
#define LOAPIC_SPURIOUS_VECTOR_ID CONFIG_LOAPIC_SPURIOUS_VECTOR_ID
#endif
#define LOPIC_SSPND_BITS_PER_IRQ 1 /* Just the one for enable disable*/
#define LOPIC_SUSPEND_BITS_REQD (ROUND_UP((LOAPIC_IRQ_COUNT * LOPIC_SSPND_BITS_PER_IRQ), 32))
#ifdef CONFIG_DEVICE_POWER_MANAGEMENT
#include <power.h>
u32_t loapic_suspend_buf[LOPIC_SUSPEND_BITS_REQD / 32] = {0};
static u32_t loapic_device_power_state = DEVICE_PM_ACTIVE_STATE;
#endif
/*
* this should not be a function at all, really, it should be
* hand-coded in include/drivers/sysapic.h. but for now it remains
* a function, just moved here from drivers/timer/loapic_timer.c
* where it REALLY didn't belong.
*/
#ifdef CONFIG_X2APIC
void z_x2apic_eoi(void)
{
x86_write_x2apic(LOAPIC_EOI, 0);
}
#endif
/**
*
* @brief Initialize the Local APIC or xAPIC
*
* This routine initializes Local APIC or xAPIC.
*
* @return N/A
*
*/
static int loapic_init(struct device *unused)
{
ARG_UNUSED(unused);
s32_t loApicMaxLvt; /* local APIC Max LVT */
/*
* enable the local APIC. note that we use xAPIC mode here, since
* x2APIC access is not enabled until the next step (if at all).
*/
x86_write_xapic(LOAPIC_SVR,
x86_read_xapic(LOAPIC_SVR) | LOAPIC_ENABLE);
#ifdef CONFIG_X2APIC
/*
* turn on x2APIC mode. we trust the config option, so
* we don't check CPUID to see if x2APIC is supported.
*/
u64_t msr = z_x86_msr_read(X86_APIC_BASE_MSR);
msr |= X86_APIC_BASE_MSR_X2APIC;
z_x86_msr_write(X86_APIC_BASE_MSR, msr);
#endif
loApicMaxLvt = (x86_read_loapic(LOAPIC_VER) & LOAPIC_MAXLVT_MASK) >> 16;
/* reset the DFR, TPR, TIMER_CONFIG, and TIMER_ICR */
#ifndef CONFIG_X2APIC
x86_write_loapic(LOAPIC_DFR, 0xffffffff); /* no DFR in x2APIC mode */
#endif
x86_write_loapic(LOAPIC_TPR, 0x0);
x86_write_loapic(LOAPIC_TIMER_CONFIG, 0x0);
x86_write_loapic(LOAPIC_TIMER_ICR, 0x0);
/* program Local Vector Table for the Virtual Wire Mode */
/* skip LINT0/LINT1 for Jailhouse guest case, because we won't
* ever be waiting for interrupts on those
*/
/* set LINT0: extInt, high-polarity, edge-trigger, not-masked */
x86_write_loapic(LOAPIC_LINT0, (x86_read_loapic(LOAPIC_LINT0) &
~(LOAPIC_MODE | LOAPIC_LOW |
LOAPIC_LEVEL | LOAPIC_LVT_MASKED)) |
(LOAPIC_EXT | LOAPIC_HIGH | LOAPIC_EDGE));
/* set LINT1: NMI, high-polarity, edge-trigger, not-masked */
x86_write_loapic(LOAPIC_LINT1, (x86_read_loapic(LOAPIC_LINT1) &
~(LOAPIC_MODE | LOAPIC_LOW |
LOAPIC_LEVEL | LOAPIC_LVT_MASKED)) |
(LOAPIC_NMI | LOAPIC_HIGH | LOAPIC_EDGE));
/* lock the Local APIC interrupts */
x86_write_loapic(LOAPIC_TIMER, LOAPIC_LVT_MASKED);
x86_write_loapic(LOAPIC_ERROR, LOAPIC_LVT_MASKED);
if (loApicMaxLvt >= LOAPIC_LVT_P6) {
x86_write_loapic(LOAPIC_PMC, LOAPIC_LVT_MASKED);
}
if (loApicMaxLvt >= LOAPIC_LVT_PENTIUM4) {
x86_write_loapic(LOAPIC_THERMAL, LOAPIC_LVT_MASKED);
}
#if CONFIG_LOAPIC_SPURIOUS_VECTOR
x86_write_loapic(LOAPIC_SVR, (x86_read_loapic(LOAPIC_SVR) & 0xFFFFFF00) |
(LOAPIC_SPURIOUS_VECTOR_ID & 0xFF));
#endif
/* discard a pending interrupt if any */
#if CONFIG_EOI_FORWARDING_BUG
z_lakemont_eoi();
#else
x86_write_loapic(LOAPIC_EOI, 0);
#endif
return 0;
}
/**
*
* @brief Set the vector field in the specified RTE
*
* This associates an IRQ with the desired vector in the IDT.
*
* @return N/A
*/
void z_loapic_int_vec_set(unsigned int irq, /* IRQ number of the interrupt */
unsigned int vector /* vector to copy into the LVT */
)
{
unsigned int oldLevel; /* previous interrupt lock level */
/*
* The following mappings are used:
*
* IRQ0 -> LOAPIC_TIMER
* IRQ1 -> LOAPIC_THERMAL
* IRQ2 -> LOAPIC_PMC
* IRQ3 -> LOAPIC_LINT0
* IRQ4 -> LOAPIC_LINT1
* IRQ5 -> LOAPIC_ERROR
*
* It's assumed that LVTs are spaced by 0x10 bytes
*/
/* update the 'vector' bits in the LVT */
oldLevel = irq_lock();
x86_write_loapic(LOAPIC_TIMER + (irq * 0x10),
(x86_read_loapic(LOAPIC_TIMER + (irq * 0x10)) &
~LOAPIC_VECTOR) | vector);
irq_unlock(oldLevel);
}
/**
*
* @brief Enable an individual LOAPIC interrupt (IRQ)
*
* @param irq the IRQ number of the interrupt
*
* This routine clears the interrupt mask bit in the LVT for the specified IRQ
*
* @return N/A
*/
void z_loapic_irq_enable(unsigned int irq)
{
unsigned int oldLevel; /* previous interrupt lock level */
/*
* See the comments in _LoApicLvtVecSet() regarding IRQ to LVT mappings
* and ths assumption concerning LVT spacing.
*/
/* clear the mask bit in the LVT */
oldLevel = irq_lock();
x86_write_loapic(LOAPIC_TIMER + (irq * 0x10),
x86_read_loapic(LOAPIC_TIMER + (irq * 0x10)) &
~LOAPIC_LVT_MASKED);
irq_unlock(oldLevel);
}
/**
*
* @brief Disable an individual LOAPIC interrupt (IRQ)
*
* @param irq the IRQ number of the interrupt
*
* This routine clears the interrupt mask bit in the LVT for the specified IRQ
*
* @return N/A
*/
void z_loapic_irq_disable(unsigned int irq)
{
unsigned int oldLevel; /* previous interrupt lock level */
/*
* See the comments in _LoApicLvtVecSet() regarding IRQ to LVT mappings
* and ths assumption concerning LVT spacing.
*/
/* set the mask bit in the LVT */
oldLevel = irq_lock();
x86_write_loapic(LOAPIC_TIMER + (irq * 0x10),
x86_read_loapic(LOAPIC_TIMER + (irq * 0x10)) |
LOAPIC_LVT_MASKED);
irq_unlock(oldLevel);
}
/**
* @brief Find the currently executing interrupt vector, if any
*
* This routine finds the vector of the interrupt that is being processed.
* The ISR (In-Service Register) register contain the vectors of the interrupts
* in service. And the higher vector is the identification of the interrupt
* being currently processed.
*
* This function must be called with interrupts locked in interrupt context.
*
* ISR registers' offsets:
* --------------------
* | Offset | bits |
* --------------------
* | 0100H | 0:31 |
* | 0110H | 32:63 |
* | 0120H | 64:95 |
* | 0130H | 96:127 |
* | 0140H | 128:159 |
* | 0150H | 160:191 |
* | 0160H | 192:223 |
* | 0170H | 224:255 |
* --------------------
*
* @return The vector of the interrupt that is currently being processed, or -1
* if no IRQ is being serviced.
*/
int __irq_controller_isr_vector_get(void)
{
int pReg, block;
/* Block 0 bits never lit up as these are all exception or reserved
* vectors
*/
for (block = 7; likely(block > 0); block--) {
pReg = x86_read_loapic(LOAPIC_ISR + (block * 0x10));
if (pReg) {
return (block * 32) + (find_msb_set(pReg) - 1);
}
}
return -1;
}
#ifdef CONFIG_DEVICE_POWER_MANAGEMENT
static int loapic_suspend(struct device *port)
{
volatile u32_t lvt; /* local vector table entry value */
int loapic_irq;
ARG_UNUSED(port);
(void)memset(loapic_suspend_buf, 0, (LOPIC_SUSPEND_BITS_REQD >> 3));
for (loapic_irq = 0; loapic_irq < LOAPIC_IRQ_COUNT; loapic_irq++) {
if (_irq_to_interrupt_vector[LOAPIC_IRQ_BASE + loapic_irq]) {
/* Since vector numbers are already present in RAM/ROM,
* We save only the mask bits here.
*/
lvt = x86_read_loapic(LOAPIC_TIMER + (loapic_irq * 0x10));
if ((lvt & LOAPIC_LVT_MASKED) == 0U) {
sys_bitfield_set_bit((mem_addr_t)loapic_suspend_buf,
loapic_irq);
}
}
}
loapic_device_power_state = DEVICE_PM_SUSPEND_STATE;
return 0;
}
int loapic_resume(struct device *port)
{
int loapic_irq;
ARG_UNUSED(port);
/* Assuming all loapic device registers lose their state, the call to
* z_loapic_init(), should bring all the registers to a sane state.
*/
loapic_init(NULL);
for (loapic_irq = 0; loapic_irq < LOAPIC_IRQ_COUNT; loapic_irq++) {
if (_irq_to_interrupt_vector[LOAPIC_IRQ_BASE + loapic_irq]) {
/* Configure vector and enable the required ones*/
z_loapic_int_vec_set(loapic_irq,
_irq_to_interrupt_vector[LOAPIC_IRQ_BASE + loapic_irq]);
if (sys_bitfield_test_bit((mem_addr_t) loapic_suspend_buf,
loapic_irq)) {
z_loapic_irq_enable(loapic_irq);
}
}
}
loapic_device_power_state = DEVICE_PM_ACTIVE_STATE;
return 0;
}
/*
* Implements the driver control management functionality
* the *context may include IN data or/and OUT data
*/
static int loapic_device_ctrl(struct device *port, u32_t ctrl_command,
void *context, device_pm_cb cb, void *arg)
{
int ret = 0;
if (ctrl_command == DEVICE_PM_SET_POWER_STATE) {
if (*((u32_t *)context) == DEVICE_PM_SUSPEND_STATE) {
ret = loapic_suspend(port);
} else if (*((u32_t *)context) == DEVICE_PM_ACTIVE_STATE) {
ret = loapic_resume(port);
}
} else if (ctrl_command == DEVICE_PM_GET_POWER_STATE) {
*((u32_t *)context) = loapic_device_power_state;
}
if (cb) {
cb(port, ret, context, arg);
}
return ret;
}
SYS_DEVICE_DEFINE("loapic", loapic_init, loapic_device_ctrl, PRE_KERNEL_1,
CONFIG_KERNEL_INIT_PRIORITY_DEFAULT);
#else
SYS_INIT(loapic_init, PRE_KERNEL_1, CONFIG_KERNEL_INIT_PRIORITY_DEFAULT);
#endif /* CONFIG_DEVICE_POWER_MANAGEMENT */
#if CONFIG_LOAPIC_SPURIOUS_VECTOR
extern void z_loapic_spurious_handler(void);
NANO_CPU_INT_REGISTER(z_loapic_spurious_handler, NANO_SOFT_IRQ,
LOAPIC_SPURIOUS_VECTOR_ID >> 4,
LOAPIC_SPURIOUS_VECTOR_ID, 0);
#endif
|
266032.c | /* O B J _ P R E P . C
* BRL-CAD
*
* Copyright (c) 2010-2014 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* 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 file; see the file named COPYING for more
* information.
*/
#include "common.h"
#include "raytrace.h"
#include "rt/func.h"
int
rt_obj_prep(struct soltab *stp, struct rt_db_internal *ip, struct rt_i *rtip)
{
int id;
const struct rt_functab *ft;
if (!stp || !ip)
return -1;
RT_CK_SOLTAB(stp);
RT_CK_DB_INTERNAL(ip);
if (rtip) RT_CK_RTI(rtip);
id = stp->st_id;
if (id < 0)
return -2;
ft = &OBJ[id];
if (!ft)
return -3;
if (!ft->ft_prep)
return -4;
return ft->ft_prep(stp, ip, rtip);
}
/*
* Local Variables:
* mode: C
* tab-width: 8
* indent-tabs-mode: t
* c-file-style: "stroustrup"
* End:
* ex: shiftwidth=4 tabstop=8
*/
|
241774.c | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__c_src_wchar_t_cpy_15.c
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_src.label.xml
Template File: sources-sink-15.tmpl.c
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Initialize data as a large string
* GoodSource: Initialize data as a small string
* Sink: cpy
* BadSink : Copy data to string using wcscpy
* Flow Variant: 15 Control flow: switch(6)
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifndef OMITBAD
void CWE122_Heap_Based_Buffer_Overflow__c_src_wchar_t_cpy_15_bad()
{
wchar_t * data;
data = (wchar_t *)malloc(100*sizeof(wchar_t));
switch(6)
{
case 6:
/* FLAW: Initialize data as a large buffer that is larger than the small buffer used in the sink */
wmemset(data, L'A', 100-1); /* fill with L'A's */
data[100-1] = L'\0'; /* null terminate */
break;
default:
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
/* FIX: Initialize data as a small buffer that as small or smaller than the small buffer used in the sink */
wmemset(data, L'A', 50-1); /* fill with L'A's */
data[50-1] = L'\0'; /* null terminate */
break;
}
{
wchar_t dest[50] = L"";
/* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */
wcscpy(dest, data);
printWLine(data);
free(data);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B1() - use goodsource and badsink by changing the switch to switch(5) */
static void goodG2B1()
{
wchar_t * data;
data = (wchar_t *)malloc(100*sizeof(wchar_t));
switch(5)
{
case 6:
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
/* FLAW: Initialize data as a large buffer that is larger than the small buffer used in the sink */
wmemset(data, L'A', 100-1); /* fill with L'A's */
data[100-1] = L'\0'; /* null terminate */
break;
default:
/* FIX: Initialize data as a small buffer that as small or smaller than the small buffer used in the sink */
wmemset(data, L'A', 50-1); /* fill with L'A's */
data[50-1] = L'\0'; /* null terminate */
break;
}
{
wchar_t dest[50] = L"";
/* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */
wcscpy(dest, data);
printWLine(data);
free(data);
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the switch */
static void goodG2B2()
{
wchar_t * data;
data = (wchar_t *)malloc(100*sizeof(wchar_t));
switch(6)
{
case 6:
/* FIX: Initialize data as a small buffer that as small or smaller than the small buffer used in the sink */
wmemset(data, L'A', 50-1); /* fill with L'A's */
data[50-1] = L'\0'; /* null terminate */
break;
default:
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
/* FLAW: Initialize data as a large buffer that is larger than the small buffer used in the sink */
wmemset(data, L'A', 100-1); /* fill with L'A's */
data[100-1] = L'\0'; /* null terminate */
break;
}
{
wchar_t dest[50] = L"";
/* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */
wcscpy(dest, data);
printWLine(data);
free(data);
}
}
void CWE122_Heap_Based_Buffer_Overflow__c_src_wchar_t_cpy_15_good()
{
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE122_Heap_Based_Buffer_Overflow__c_src_wchar_t_cpy_15_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE122_Heap_Based_Buffer_Overflow__c_src_wchar_t_cpy_15_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
348701.c | // SPDX-License-Identifier: GPL-2.0
/*
* VCNL4035 Ambient Light and Proximity Sensor - 7-bit I2C slave address 0x60
*
* Copyright (c) 2018, DENX Software Engineering GmbH
* Author: Parthiban Nallathambi <[email protected]>
*
* TODO: Proximity
*/
#include <linux/bitops.h>
#include <linux/i2c.h>
#include <linux/module.h>
#include <linux/pm_runtime.h>
#include <linux/regmap.h>
#include <linux/iio/buffer.h>
#include <linux/iio/events.h>
#include <linux/iio/iio.h>
#include <linux/iio/sysfs.h>
#include <linux/iio/trigger.h>
#include <linux/iio/trigger_consumer.h>
#include <linux/iio/triggered_buffer.h>
#define VCNL4035_DRV_NAME "vcnl4035"
#define VCNL4035_IRQ_NAME "vcnl4035_event"
#define VCNL4035_REGMAP_NAME "vcnl4035_regmap"
/* Device registers */
#define VCNL4035_ALS_CONF 0x00
#define VCNL4035_ALS_THDH 0x01
#define VCNL4035_ALS_THDL 0x02
#define VCNL4035_ALS_DATA 0x0B
#define VCNL4035_WHITE_DATA 0x0C
#define VCNL4035_INT_FLAG 0x0D
#define VCNL4035_DEV_ID 0x0E
/* Register masks */
#define VCNL4035_MODE_ALS_MASK BIT(0)
#define VCNL4035_MODE_ALS_WHITE_CHAN BIT(8)
#define VCNL4035_MODE_ALS_INT_MASK BIT(1)
#define VCNL4035_ALS_IT_MASK GENMASK(7, 5)
#define VCNL4035_ALS_PERS_MASK GENMASK(3, 2)
#define VCNL4035_INT_ALS_IF_H_MASK BIT(12)
#define VCNL4035_INT_ALS_IF_L_MASK BIT(13)
/* Default values */
#define VCNL4035_MODE_ALS_ENABLE BIT(0)
#define VCNL4035_MODE_ALS_DISABLE 0x00
#define VCNL4035_MODE_ALS_INT_ENABLE BIT(1)
#define VCNL4035_MODE_ALS_INT_DISABLE 0
#define VCNL4035_DEV_ID_VAL 0x80
#define VCNL4035_ALS_IT_DEFAULT 0x01
#define VCNL4035_ALS_PERS_DEFAULT 0x00
#define VCNL4035_ALS_THDH_DEFAULT 5000
#define VCNL4035_ALS_THDL_DEFAULT 100
#define VCNL4035_SLEEP_DELAY_MS 2000
struct vcnl4035_data {
struct i2c_client *client;
struct regmap *regmap;
unsigned int als_it_val;
unsigned int als_persistence;
unsigned int als_thresh_low;
unsigned int als_thresh_high;
struct iio_trigger *drdy_trigger0;
};
static inline bool vcnl4035_is_triggered(struct vcnl4035_data *data)
{
int ret;
int reg;
ret = regmap_read(data->regmap, VCNL4035_INT_FLAG, ®);
if (ret < 0)
return false;
return !!(reg &
(VCNL4035_INT_ALS_IF_H_MASK | VCNL4035_INT_ALS_IF_L_MASK));
}
static irqreturn_t vcnl4035_drdy_irq_thread(int irq, void *private)
{
struct iio_dev *indio_dev = private;
struct vcnl4035_data *data = iio_priv(indio_dev);
if (vcnl4035_is_triggered(data)) {
iio_push_event(indio_dev, IIO_UNMOD_EVENT_CODE(IIO_LIGHT,
0,
IIO_EV_TYPE_THRESH,
IIO_EV_DIR_EITHER),
iio_get_time_ns(indio_dev));
iio_trigger_poll_chained(data->drdy_trigger0);
return IRQ_HANDLED;
}
return IRQ_NONE;
}
/* Triggered buffer */
static irqreturn_t vcnl4035_trigger_consumer_handler(int irq, void *p)
{
struct iio_poll_func *pf = p;
struct iio_dev *indio_dev = pf->indio_dev;
struct vcnl4035_data *data = iio_priv(indio_dev);
/* Ensure naturally aligned timestamp */
u8 buffer[ALIGN(sizeof(u16), sizeof(s64)) + sizeof(s64)] __aligned(8);
int ret;
ret = regmap_read(data->regmap, VCNL4035_ALS_DATA, (int *)buffer);
if (ret < 0) {
dev_err(&data->client->dev,
"Trigger consumer can't read from sensor.\n");
goto fail_read;
}
iio_push_to_buffers_with_timestamp(indio_dev, buffer,
iio_get_time_ns(indio_dev));
fail_read:
iio_trigger_notify_done(indio_dev->trig);
return IRQ_HANDLED;
}
static int vcnl4035_als_drdy_set_state(struct iio_trigger *trigger,
bool enable_drdy)
{
struct iio_dev *indio_dev = iio_trigger_get_drvdata(trigger);
struct vcnl4035_data *data = iio_priv(indio_dev);
int val = enable_drdy ? VCNL4035_MODE_ALS_INT_ENABLE :
VCNL4035_MODE_ALS_INT_DISABLE;
return regmap_update_bits(data->regmap, VCNL4035_ALS_CONF,
VCNL4035_MODE_ALS_INT_MASK,
val);
}
static const struct iio_trigger_ops vcnl4035_trigger_ops = {
.validate_device = iio_trigger_validate_own_device,
.set_trigger_state = vcnl4035_als_drdy_set_state,
};
static int vcnl4035_set_pm_runtime_state(struct vcnl4035_data *data, bool on)
{
int ret;
struct device *dev = &data->client->dev;
if (on) {
ret = pm_runtime_resume_and_get(dev);
} else {
pm_runtime_mark_last_busy(dev);
ret = pm_runtime_put_autosuspend(dev);
}
return ret;
}
/*
* Device IT INT Time (ms) Scale (lux/step)
* 000 50 0.064
* 001 100 0.032
* 010 200 0.016
* 100 400 0.008
* 101 - 111 800 0.004
* Values are proportional, so ALS INT is selected for input due to
* simplicity reason. Integration time value and scaling is
* calculated based on device INT value
*
* Raw value needs to be scaled using ALS steps
*/
static int vcnl4035_read_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan, int *val,
int *val2, long mask)
{
struct vcnl4035_data *data = iio_priv(indio_dev);
int ret;
int raw_data;
unsigned int reg;
switch (mask) {
case IIO_CHAN_INFO_RAW:
ret = vcnl4035_set_pm_runtime_state(data, true);
if (ret < 0)
return ret;
ret = iio_device_claim_direct_mode(indio_dev);
if (!ret) {
if (chan->channel)
reg = VCNL4035_ALS_DATA;
else
reg = VCNL4035_WHITE_DATA;
ret = regmap_read(data->regmap, reg, &raw_data);
iio_device_release_direct_mode(indio_dev);
if (!ret) {
*val = raw_data;
ret = IIO_VAL_INT;
}
}
vcnl4035_set_pm_runtime_state(data, false);
return ret;
case IIO_CHAN_INFO_INT_TIME:
*val = 50;
if (data->als_it_val)
*val = data->als_it_val * 100;
return IIO_VAL_INT;
case IIO_CHAN_INFO_SCALE:
*val = 64;
if (!data->als_it_val)
*val2 = 1000;
else
*val2 = data->als_it_val * 2 * 1000;
return IIO_VAL_FRACTIONAL;
default:
return -EINVAL;
}
}
static int vcnl4035_write_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
int val, int val2, long mask)
{
int ret;
struct vcnl4035_data *data = iio_priv(indio_dev);
switch (mask) {
case IIO_CHAN_INFO_INT_TIME:
if (val <= 0 || val > 800)
return -EINVAL;
ret = vcnl4035_set_pm_runtime_state(data, true);
if (ret < 0)
return ret;
ret = regmap_update_bits(data->regmap, VCNL4035_ALS_CONF,
VCNL4035_ALS_IT_MASK,
val / 100);
if (!ret)
data->als_it_val = val / 100;
vcnl4035_set_pm_runtime_state(data, false);
return ret;
default:
return -EINVAL;
}
}
/* No direct ABI for persistence and threshold, so eventing */
static int vcnl4035_read_thresh(struct iio_dev *indio_dev,
const struct iio_chan_spec *chan, enum iio_event_type type,
enum iio_event_direction dir, enum iio_event_info info,
int *val, int *val2)
{
struct vcnl4035_data *data = iio_priv(indio_dev);
switch (info) {
case IIO_EV_INFO_VALUE:
switch (dir) {
case IIO_EV_DIR_RISING:
*val = data->als_thresh_high;
return IIO_VAL_INT;
case IIO_EV_DIR_FALLING:
*val = data->als_thresh_low;
return IIO_VAL_INT;
default:
return -EINVAL;
}
break;
case IIO_EV_INFO_PERIOD:
*val = data->als_persistence;
return IIO_VAL_INT;
default:
return -EINVAL;
}
}
static int vcnl4035_write_thresh(struct iio_dev *indio_dev,
const struct iio_chan_spec *chan, enum iio_event_type type,
enum iio_event_direction dir, enum iio_event_info info, int val,
int val2)
{
struct vcnl4035_data *data = iio_priv(indio_dev);
int ret;
switch (info) {
case IIO_EV_INFO_VALUE:
/* 16 bit threshold range 0 - 65535 */
if (val < 0 || val > 65535)
return -EINVAL;
if (dir == IIO_EV_DIR_RISING) {
if (val < data->als_thresh_low)
return -EINVAL;
ret = regmap_write(data->regmap, VCNL4035_ALS_THDH,
val);
if (ret)
return ret;
data->als_thresh_high = val;
} else {
if (val > data->als_thresh_high)
return -EINVAL;
ret = regmap_write(data->regmap, VCNL4035_ALS_THDL,
val);
if (ret)
return ret;
data->als_thresh_low = val;
}
return ret;
case IIO_EV_INFO_PERIOD:
/* allow only 1 2 4 8 as persistence value */
if (val < 0 || val > 8 || hweight8(val) != 1)
return -EINVAL;
ret = regmap_update_bits(data->regmap, VCNL4035_ALS_CONF,
VCNL4035_ALS_PERS_MASK, val);
if (!ret)
data->als_persistence = val;
return ret;
default:
return -EINVAL;
}
}
static IIO_CONST_ATTR_INT_TIME_AVAIL("50 100 200 400 800");
static struct attribute *vcnl4035_attributes[] = {
&iio_const_attr_integration_time_available.dev_attr.attr,
NULL,
};
static const struct attribute_group vcnl4035_attribute_group = {
.attrs = vcnl4035_attributes,
};
static const struct iio_info vcnl4035_info = {
.read_raw = vcnl4035_read_raw,
.write_raw = vcnl4035_write_raw,
.read_event_value = vcnl4035_read_thresh,
.write_event_value = vcnl4035_write_thresh,
.attrs = &vcnl4035_attribute_group,
};
static const struct iio_event_spec vcnl4035_event_spec[] = {
{
.type = IIO_EV_TYPE_THRESH,
.dir = IIO_EV_DIR_RISING,
.mask_separate = BIT(IIO_EV_INFO_VALUE),
}, {
.type = IIO_EV_TYPE_THRESH,
.dir = IIO_EV_DIR_FALLING,
.mask_separate = BIT(IIO_EV_INFO_VALUE),
}, {
.type = IIO_EV_TYPE_THRESH,
.dir = IIO_EV_DIR_EITHER,
.mask_separate = BIT(IIO_EV_INFO_PERIOD),
},
};
enum vcnl4035_scan_index_order {
VCNL4035_CHAN_INDEX_LIGHT,
VCNL4035_CHAN_INDEX_WHITE_LED,
};
static const struct iio_buffer_setup_ops iio_triggered_buffer_setup_ops = {
.validate_scan_mask = &iio_validate_scan_mask_onehot,
};
static const struct iio_chan_spec vcnl4035_channels[] = {
{
.type = IIO_LIGHT,
.channel = 0,
.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
BIT(IIO_CHAN_INFO_INT_TIME) |
BIT(IIO_CHAN_INFO_SCALE),
.event_spec = vcnl4035_event_spec,
.num_event_specs = ARRAY_SIZE(vcnl4035_event_spec),
.scan_index = VCNL4035_CHAN_INDEX_LIGHT,
.scan_type = {
.sign = 'u',
.realbits = 16,
.storagebits = 16,
.endianness = IIO_LE,
},
},
{
.type = IIO_INTENSITY,
.channel = 1,
.modified = 1,
.channel2 = IIO_MOD_LIGHT_BOTH,
.info_mask_separate = BIT(IIO_CHAN_INFO_RAW),
.scan_index = VCNL4035_CHAN_INDEX_WHITE_LED,
.scan_type = {
.sign = 'u',
.realbits = 16,
.storagebits = 16,
.endianness = IIO_LE,
},
},
};
static int vcnl4035_set_als_power_state(struct vcnl4035_data *data, u8 status)
{
return regmap_update_bits(data->regmap, VCNL4035_ALS_CONF,
VCNL4035_MODE_ALS_MASK,
status);
}
static int vcnl4035_init(struct vcnl4035_data *data)
{
int ret;
int id;
ret = regmap_read(data->regmap, VCNL4035_DEV_ID, &id);
if (ret < 0) {
dev_err(&data->client->dev, "Failed to read DEV_ID register\n");
return ret;
}
if (id != VCNL4035_DEV_ID_VAL) {
dev_err(&data->client->dev, "Wrong id, got %x, expected %x\n",
id, VCNL4035_DEV_ID_VAL);
return -ENODEV;
}
ret = vcnl4035_set_als_power_state(data, VCNL4035_MODE_ALS_ENABLE);
if (ret < 0)
return ret;
/* ALS white channel enable */
ret = regmap_update_bits(data->regmap, VCNL4035_ALS_CONF,
VCNL4035_MODE_ALS_WHITE_CHAN,
1);
if (ret) {
dev_err(&data->client->dev, "set white channel enable %d\n",
ret);
return ret;
}
/* set default integration time - 100 ms for ALS */
ret = regmap_update_bits(data->regmap, VCNL4035_ALS_CONF,
VCNL4035_ALS_IT_MASK,
VCNL4035_ALS_IT_DEFAULT);
if (ret) {
dev_err(&data->client->dev, "set default ALS IT returned %d\n",
ret);
return ret;
}
data->als_it_val = VCNL4035_ALS_IT_DEFAULT;
/* set default persistence time - 1 for ALS */
ret = regmap_update_bits(data->regmap, VCNL4035_ALS_CONF,
VCNL4035_ALS_PERS_MASK,
VCNL4035_ALS_PERS_DEFAULT);
if (ret) {
dev_err(&data->client->dev, "set default PERS returned %d\n",
ret);
return ret;
}
data->als_persistence = VCNL4035_ALS_PERS_DEFAULT;
/* set default HIGH threshold for ALS */
ret = regmap_write(data->regmap, VCNL4035_ALS_THDH,
VCNL4035_ALS_THDH_DEFAULT);
if (ret) {
dev_err(&data->client->dev, "set default THDH returned %d\n",
ret);
return ret;
}
data->als_thresh_high = VCNL4035_ALS_THDH_DEFAULT;
/* set default LOW threshold for ALS */
ret = regmap_write(data->regmap, VCNL4035_ALS_THDL,
VCNL4035_ALS_THDL_DEFAULT);
if (ret) {
dev_err(&data->client->dev, "set default THDL returned %d\n",
ret);
return ret;
}
data->als_thresh_low = VCNL4035_ALS_THDL_DEFAULT;
return 0;
}
static bool vcnl4035_is_volatile_reg(struct device *dev, unsigned int reg)
{
switch (reg) {
case VCNL4035_ALS_CONF:
case VCNL4035_DEV_ID:
return false;
default:
return true;
}
}
static const struct regmap_config vcnl4035_regmap_config = {
.name = VCNL4035_REGMAP_NAME,
.reg_bits = 8,
.val_bits = 16,
.max_register = VCNL4035_DEV_ID,
.cache_type = REGCACHE_RBTREE,
.volatile_reg = vcnl4035_is_volatile_reg,
.val_format_endian = REGMAP_ENDIAN_LITTLE,
};
static int vcnl4035_probe_trigger(struct iio_dev *indio_dev)
{
int ret;
struct vcnl4035_data *data = iio_priv(indio_dev);
data->drdy_trigger0 = devm_iio_trigger_alloc(
indio_dev->dev.parent,
"%s-dev%d", indio_dev->name, iio_device_id(indio_dev));
if (!data->drdy_trigger0)
return -ENOMEM;
data->drdy_trigger0->ops = &vcnl4035_trigger_ops;
iio_trigger_set_drvdata(data->drdy_trigger0, indio_dev);
ret = devm_iio_trigger_register(indio_dev->dev.parent,
data->drdy_trigger0);
if (ret) {
dev_err(&data->client->dev, "iio trigger register failed\n");
return ret;
}
/* Trigger setup */
ret = devm_iio_triggered_buffer_setup(indio_dev->dev.parent, indio_dev,
NULL, vcnl4035_trigger_consumer_handler,
&iio_triggered_buffer_setup_ops);
if (ret < 0) {
dev_err(&data->client->dev, "iio triggered buffer setup failed\n");
return ret;
}
/* IRQ to trigger mapping */
ret = devm_request_threaded_irq(&data->client->dev, data->client->irq,
NULL, vcnl4035_drdy_irq_thread,
IRQF_TRIGGER_LOW | IRQF_ONESHOT,
VCNL4035_IRQ_NAME, indio_dev);
if (ret < 0)
dev_err(&data->client->dev, "request irq %d for trigger0 failed\n",
data->client->irq);
return ret;
}
static int vcnl4035_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct vcnl4035_data *data;
struct iio_dev *indio_dev;
struct regmap *regmap;
int ret;
indio_dev = devm_iio_device_alloc(&client->dev, sizeof(*data));
if (!indio_dev)
return -ENOMEM;
regmap = devm_regmap_init_i2c(client, &vcnl4035_regmap_config);
if (IS_ERR(regmap)) {
dev_err(&client->dev, "regmap_init failed!\n");
return PTR_ERR(regmap);
}
data = iio_priv(indio_dev);
i2c_set_clientdata(client, indio_dev);
data->client = client;
data->regmap = regmap;
indio_dev->info = &vcnl4035_info;
indio_dev->name = VCNL4035_DRV_NAME;
indio_dev->channels = vcnl4035_channels;
indio_dev->num_channels = ARRAY_SIZE(vcnl4035_channels);
indio_dev->modes = INDIO_DIRECT_MODE;
ret = vcnl4035_init(data);
if (ret < 0) {
dev_err(&client->dev, "vcnl4035 chip init failed\n");
return ret;
}
if (client->irq > 0) {
ret = vcnl4035_probe_trigger(indio_dev);
if (ret < 0) {
dev_err(&client->dev, "vcnl4035 unable init trigger\n");
goto fail_poweroff;
}
}
ret = pm_runtime_set_active(&client->dev);
if (ret < 0)
goto fail_poweroff;
ret = iio_device_register(indio_dev);
if (ret < 0)
goto fail_poweroff;
pm_runtime_enable(&client->dev);
pm_runtime_set_autosuspend_delay(&client->dev, VCNL4035_SLEEP_DELAY_MS);
pm_runtime_use_autosuspend(&client->dev);
return 0;
fail_poweroff:
vcnl4035_set_als_power_state(data, VCNL4035_MODE_ALS_DISABLE);
return ret;
}
static int vcnl4035_remove(struct i2c_client *client)
{
struct iio_dev *indio_dev = i2c_get_clientdata(client);
pm_runtime_dont_use_autosuspend(&client->dev);
pm_runtime_disable(&client->dev);
iio_device_unregister(indio_dev);
pm_runtime_set_suspended(&client->dev);
return vcnl4035_set_als_power_state(iio_priv(indio_dev),
VCNL4035_MODE_ALS_DISABLE);
}
static int __maybe_unused vcnl4035_runtime_suspend(struct device *dev)
{
struct iio_dev *indio_dev = i2c_get_clientdata(to_i2c_client(dev));
struct vcnl4035_data *data = iio_priv(indio_dev);
int ret;
ret = vcnl4035_set_als_power_state(data, VCNL4035_MODE_ALS_DISABLE);
regcache_mark_dirty(data->regmap);
return ret;
}
static int __maybe_unused vcnl4035_runtime_resume(struct device *dev)
{
struct iio_dev *indio_dev = i2c_get_clientdata(to_i2c_client(dev));
struct vcnl4035_data *data = iio_priv(indio_dev);
int ret;
regcache_sync(data->regmap);
ret = vcnl4035_set_als_power_state(data, VCNL4035_MODE_ALS_ENABLE);
if (ret < 0)
return ret;
/* wait for 1 ALS integration cycle */
msleep(data->als_it_val * 100);
return 0;
}
static const struct dev_pm_ops vcnl4035_pm_ops = {
SET_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend,
pm_runtime_force_resume)
SET_RUNTIME_PM_OPS(vcnl4035_runtime_suspend,
vcnl4035_runtime_resume, NULL)
};
static const struct i2c_device_id vcnl4035_id[] = {
{ "vcnl4035", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, vcnl4035_id);
static const struct of_device_id vcnl4035_of_match[] = {
{ .compatible = "vishay,vcnl4035", },
{ }
};
MODULE_DEVICE_TABLE(of, vcnl4035_of_match);
static struct i2c_driver vcnl4035_driver = {
.driver = {
.name = VCNL4035_DRV_NAME,
.pm = &vcnl4035_pm_ops,
.of_match_table = vcnl4035_of_match,
},
.probe = vcnl4035_probe,
.remove = vcnl4035_remove,
.id_table = vcnl4035_id,
};
module_i2c_driver(vcnl4035_driver);
MODULE_AUTHOR("Parthiban Nallathambi <[email protected]>");
MODULE_DESCRIPTION("VCNL4035 Ambient Light Sensor driver");
MODULE_LICENSE("GPL v2");
|
607258.c | #include "../includes/shapes.h"
/* ----------------------------- TEXTURES ------------------------------ */
GLuint loadTexture(const char *filename) {
// Load texture with RGBA
// Transparency enabled
GLuint tex = SOIL_load_OGL_texture(filename,
SOIL_LOAD_RGBA,
SOIL_CREATE_NEW_ID,
SOIL_FLAG_MIPMAPS | SOIL_FLAG_INVERT_Y);
if (!tex) {
return EXIT_FAILURE;
}
// Texture parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
return tex;
}
/* ----------------------------- TEXTURES ------------------------------ */
/* ---------------------------------- TEXT ---------------------------------- */
Text *createText(void *font, const char *string) {
Text *newTxt = (Text *) malloc(sizeof(Text));
newTxt->font = font;
newTxt->string = string;
newTxt->x = 0.0;
newTxt->y = 0.0;
newTxt->z = 0.0;
return newTxt;
}
void drawText(Text *text, int x, int y) {
if(text == NULL || text->font == NULL || text->string == NULL) return;
text->x = x;
text->y = y;
int strsize = strlen(text->string);
glRasterPos3f(text->x, text->y, text->z);
int i = 0;
for(i = 0; i < strsize; i++) {
glutBitmapCharacter(text->font, text->string[i]);
}
}
void freeText(Text *text) {
if(text) {
free(text);
text = NULL;
}
}
/* ---------------------------------- TEXT ---------------------------------- */
/* ---------------------------------- PLANE --------------------------------- */
// Plane Coordinates
Plane* createPlane(){
Plane *plane = (Plane *) malloc(sizeof(Plane));
plane->thickness = 1.0f;
plane->color[0] = 1.0;
plane->color[1] = 1.0;
plane->color[2] = 1.0;
plane->texture = 0;
plane->x[0] = 0.0;
plane->y[0] = 0.0;
plane->z[0] = 0.0;
plane->x[1] = 0.0;
plane->y[1] = 0.0;
plane->z[1] = 0.0;
plane->x[2] = 0.0;
plane->y[2] = 0.0;
plane->z[2] = 0.0;
plane->x[3] = 0.0;
plane->y[3] = 0.0;
plane->z[3] = 0.0;
return plane;
}
void setPlaneCoordinates(Plane *plane, GLfloat x1, GLfloat y1, GLfloat z1,
GLfloat x2, GLfloat y2, GLfloat z2,
GLfloat x3, GLfloat y3, GLfloat z3,
GLfloat x4, GLfloat y4, GLfloat z4) {
if (plane == NULL) return;
plane->x[0] = x1;
plane->y[0] = y1;
plane->z[0] = z1;
plane->x[1] = x2;
plane->y[1] = y2;
plane->z[1] = z2;
plane->x[2] = x3;
plane->y[2] = y3;
plane->z[2] = z3;
plane->x[3] = x4;
plane->y[3] = y4;
plane->z[3] = z4;
}
void setPlaneThickness(Plane *plane, float thickness){
if (plane == NULL) return;
plane->thickness = thickness;
}
void setPlaneColor(Plane *plane, float r, float g, float b){
if (plane == NULL) return;
plane->color[0] = r;
plane->color[1] = g;
plane->color[2] = b;
}
void setPlaneTexture(Plane *plane, GLuint texture){
if (plane == NULL) return;
plane->texture = texture;
}
void drawPlaneHollow(Plane* plane) {
if (plane == NULL) return;
glLineWidth(plane->thickness);
glBegin(GL_LINE_LOOP);
glVertex3f(plane->x[0], plane->y[0], plane->z[0]);
glVertex3f(plane->x[1], plane->y[1], plane->z[1]);
glVertex3f(plane->x[2], plane->y[2], plane->z[2]);
glVertex3f(plane->x[3], plane->y[3], plane->z[3]);
glEnd();
}
void drawPlaneFilled(Plane* plane) {
if (plane == NULL) return;
glBegin(GL_QUADS);
glVertex3f(plane->x[0], plane->y[0], plane->z[0]);
glVertex3f(plane->x[1], plane->y[1], plane->z[1]);
glVertex3f(plane->x[2], plane->y[2], plane->z[2]);
glVertex3f(plane->x[3], plane->y[3], plane->z[3]);
glEnd();
}
void drawPlaneTextured(Plane *plane){
if (plane == NULL) return;
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glBindTexture(GL_TEXTURE_2D, plane->texture);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glColor3f(plane->color[0], plane->color[1], plane->color[2]);
glBegin(GL_QUADS);
glTexCoord2f(0, 0);
glVertex3f(plane->x[0], plane->y[0], plane->z[0]);
glTexCoord2f(0, 1);
glVertex3f(plane->x[1], plane->y[1], plane->z[1]);
glTexCoord2f(1, 1);
glVertex3f(plane->x[2], plane->y[2], plane->z[2]);
glTexCoord2f(1, 0);
glVertex3f(plane->x[3], plane->y[3], plane->z[3]);
glEnd();
glDisable(GL_TEXTURE_2D);
glDisable(GL_BLEND);
}
void freePlane(Plane *plane) {
if(plane){
free(plane);
plane = NULL;
}
}
/* ---------------------------------- PLANE --------------------------------- */
/* ---------------------------------- CUBE ---------------------------------- */
Cube *createCube(){
Cube *cube = (Cube *) malloc(sizeof(Cube));
cube->thickness = 1.0f;
cube->color[0] = 1.0;
cube->color[1] = 1.0;
cube->color[2] = 1.0;
cube->texture = 0;
cube->x = 0.0;
cube->y = 0.0;
cube->z = 0.0;
cube->sizeX = 0.0;
cube->sizeY = 0.0;
cube->sizeZ = 0.0;
return cube;
}
void setCubeColor(Cube *cube, float r, float g, float b){
if (cube == NULL) return;
cube->color[0] = r;
cube->color[1] = g;
cube->color[2] = b;
}
void setCubeCoordinates(Cube *cube, GLfloat x, GLfloat y, GLfloat z){
if (cube == NULL) return;
cube->x = x;
cube->y = y;
cube->z = z;
}
void setCubeThickness(Cube *cube, float thickness){
if (cube == NULL) return;
cube->thickness = thickness;
}
void setCubeSize(Cube *cube, GLfloat x, GLfloat y, GLfloat z){
if (cube == NULL) return;
cube->sizeX = x;
cube->sizeY = y;
cube->sizeZ = z;
}
void setCubeTexture(Cube *cube, GLuint texture){
cube->texture = texture;
}
void drawCubeHollow(Cube *cube){
if (cube == NULL) return;
Plane *plane = createPlane();
setPlaneThickness(plane, cube->thickness);
setPlaneCoordinates(plane, -(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
-(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z);
drawPlaneHollow(plane);
setPlaneCoordinates(plane, -(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z,
-(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z);
drawPlaneHollow(plane);
setPlaneCoordinates(plane, (cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z);
drawPlaneHollow(plane);
setPlaneCoordinates(plane, -(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
-(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
-(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z,
-(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z);
drawPlaneHollow(plane);
setPlaneCoordinates(plane, -(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z,
-(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z);
drawPlaneHollow(plane);
setPlaneCoordinates(plane, -(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z,
-(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z);
drawPlaneHollow(plane);
freePlane(plane);
}
void drawCubeFilled(Cube *cube){
if (cube == NULL) return;
Plane *plane = createPlane();
setPlaneCoordinates(plane, -(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
-(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z);
drawPlaneFilled(plane);
setPlaneCoordinates(plane, -(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z,
-(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z);
drawPlaneFilled(plane);
setPlaneCoordinates(plane, (cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z);
drawPlaneFilled(plane);
setPlaneCoordinates(plane, -(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
-(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
-(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z,
-(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z);
drawPlaneFilled(plane);
setPlaneCoordinates(plane, -(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z,
-(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z);
drawPlaneFilled(plane);
setPlaneCoordinates(plane, -(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z,
-(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z);
drawPlaneFilled(plane);
freePlane(plane);
}
void drawCubeTextured(Cube *cube){
if (cube == NULL) return;
Plane *plane = createPlane();
setPlaneTexture(plane, cube->texture);
setPlaneCoordinates(plane, -(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
-(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z);
drawPlaneTextured(plane);
setPlaneCoordinates(plane, -(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z,
-(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z);
drawPlaneTextured(plane);
setPlaneCoordinates(plane, (cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z);
drawPlaneTextured(plane);
setPlaneCoordinates(plane, -(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
-(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
-(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z,
-(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z);
drawPlaneTextured(plane);
setPlaneCoordinates(plane, -(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z,
-(cube->sizeX/2) + cube->x, (cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z);
drawPlaneTextured(plane);
setPlaneCoordinates(plane, -(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, (cube->sizeZ/2) + cube->z,
(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z,
-(cube->sizeX/2) + cube->x, -(cube->sizeY/2) + cube->y, -(cube->sizeZ/2) + cube->z);
drawPlaneTextured(plane);
freePlane(plane);
}
void freeCube(Cube *cube){
if(cube){
free(cube);
cube = NULL;
}
}
/* ---------------------------------- CUBE ---------------------------------- */
|
108553.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* open_to_owt.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dpuente- <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/10/29 16:32:10 by dpuente- #+# #+# */
/* Updated: 2021/10/29 17:01:11 by dpuente- ### ########.fr */
/* */
/* ************************************************************************** */
#include "exec.h"
#include "hered.h"
void open_to_read(t_element *element)
{
element->fd = open(element->arg[1], O_RDONLY);
if (element->fd < 0)
{
g_state = errno;
printf("**%d**\n", errno);
perror("Error");
ft_putstr_fd(element->arg[1], 2);
exit (g_state);
}
else
dup2(element->fd, STDIN_FILENO);
close(element->fd);
}
void open_to_write(t_element *element)
{
element->fd = open(element->arg[1], O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (element->fd < 0)
{
g_state = errno;
printf("**%d**\n", errno);
perror("Error");
ft_putstr_fd(element->arg[1], 2);
exit (g_state);
}
else
dup2(element->fd, STDOUT_FILENO);
close(element->fd);
}
void open_to_trunk(t_element *element)
{
element->fd = open(element->arg[1], O_APPEND | O_RDWR | O_CREAT, 0644);
if (element->fd < 0)
{
g_state = errno;
printf("**%d**\n", errno);
perror("Error");
ft_putstr_fd(element->arg[1], 2);
exit (g_state);
}
else
dup2(element->fd, STDOUT_FILENO);
close(element->fd);
}
|
481182.c | /*++
Copyright (c) 2005, Intel Corporation
All rights reserved. This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
initplat.c
Abstract:
Revision History
--*/
#include "EfiShellLib.h"
VOID
InitializeLibPlatform (
IN EFI_HANDLE ImageHandle,
IN EFI_SYSTEM_TABLE *SystemTable
)
{
return;
}
|
38387.c | #include <stdio.h>
main()
{
int i,j,m[3][3];
for(i=0;i<3;i++){
for(j=0;j<3;j++){
printf("digite os numeros: %d-%d: ",i,j);
scanf("%d",&m[i][j]);
}
}
for(i=0;i<3;i++){
for(j=0;j<3;j++){
if(i==j){
printf("os numeros com indices iguais e: %d\n",m[i][j]);
}
}
}
}
|
286574.c | /**
* \file
* Threadpool for all concurrent GC work.
*
* Copyright (C) 2015 Xamarin Inc
*
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
#include "config.h"
#ifdef HAVE_SGEN_GC
#include "mono/sgen/sgen-gc.h"
#include "mono/sgen/sgen-thread-pool.h"
#include "mono/sgen/sgen-client.h"
#include "mono/utils/mono-os-mutex.h"
#ifndef DISABLE_SGEN_MAJOR_MARKSWEEP_CONC
static mono_mutex_t lock;
static mono_cond_t work_cond;
static mono_cond_t done_cond;
static int threads_num;
static MonoNativeThreadId threads [SGEN_THREADPOOL_MAX_NUM_THREADS];
static int threads_context [SGEN_THREADPOOL_MAX_NUM_THREADS];
static volatile gboolean threadpool_shutdown;
static volatile int threads_finished;
static int contexts_num;
static SgenThreadPoolContext pool_contexts [SGEN_THREADPOOL_MAX_NUM_CONTEXTS];
enum {
STATE_WAITING,
STATE_IN_PROGRESS,
STATE_DONE
};
/* Assumes that the lock is held. */
static SgenThreadPoolJob*
get_job_and_set_in_progress (SgenThreadPoolContext *context)
{
for (size_t i = 0; i < context->job_queue.next_slot; ++i) {
SgenThreadPoolJob *job = (SgenThreadPoolJob *)context->job_queue.data [i];
if (job->state == STATE_WAITING) {
job->state = STATE_IN_PROGRESS;
return job;
}
}
return NULL;
}
/* Assumes that the lock is held. */
static ssize_t
find_job_in_queue (SgenThreadPoolContext *context, SgenThreadPoolJob *job)
{
for (ssize_t i = 0; i < context->job_queue.next_slot; ++i) {
if (context->job_queue.data [i] == job)
return i;
}
return -1;
}
/* Assumes that the lock is held. */
static void
remove_job (SgenThreadPoolContext *context, SgenThreadPoolJob *job)
{
ssize_t index;
SGEN_ASSERT (0, job->state == STATE_DONE, "Why are we removing a job that's not done?");
index = find_job_in_queue (context, job);
SGEN_ASSERT (0, index >= 0, "Why is the job we're trying to remove not in the queue?");
context->job_queue.data [index] = NULL;
sgen_pointer_queue_remove_nulls (&context->job_queue);
sgen_thread_pool_job_free (job);
}
static gboolean
continue_idle_job (SgenThreadPoolContext *context, void *thread_data)
{
if (!context->continue_idle_job_func)
return FALSE;
return context->continue_idle_job_func (thread_data, context - pool_contexts);
}
static gboolean
should_work (SgenThreadPoolContext *context, void *thread_data)
{
if (!context->should_work_func)
return TRUE;
return context->should_work_func (thread_data);
}
/*
* Tells whether we should lock and attempt to get work from
* a higher priority context.
*/
static gboolean
has_priority_work (int worker_index, int current_context)
{
int i;
for (i = 0; i < current_context; i++) {
SgenThreadPoolContext *context = &pool_contexts [i];
void *thread_data;
if (worker_index >= context->num_threads)
continue;
thread_data = (context->thread_datas) ? context->thread_datas [worker_index] : NULL;
if (!should_work (context, thread_data))
continue;
if (context->job_queue.next_slot > 0)
return TRUE;
if (continue_idle_job (context, thread_data))
return TRUE;
}
/* Return if job enqueued on current context. Jobs have priority over idle work */
if (pool_contexts [current_context].job_queue.next_slot > 0)
return TRUE;
return FALSE;
}
/*
* Gets the highest priority work. If there is none, it waits
* for work_cond. Should always be called with lock held.
*/
static void
get_work (int worker_index, int *work_context, int *do_idle, SgenThreadPoolJob **job)
{
while (!threadpool_shutdown) {
int i;
for (i = 0; i < contexts_num; i++) {
SgenThreadPoolContext *context = &pool_contexts [i];
void *thread_data;
if (worker_index >= context->num_threads)
continue;
thread_data = (context->thread_datas) ? context->thread_datas [worker_index] : NULL;
if (!should_work (context, thread_data))
continue;
/*
* It's important that we check the continue idle flag with the lock held.
* Suppose we didn't check with the lock held, and the result is FALSE. The
* main thread might then set continue idle and signal us before we can take
* the lock, and we'd lose the signal.
*/
*do_idle = continue_idle_job (context, thread_data);
*job = get_job_and_set_in_progress (context);
if (*job || *do_idle) {
*work_context = i;
return;
}
}
/*
* Nothing to do on any context
* pthread_cond_wait() can return successfully despite the condition
* not being signalled, so we have to run this in a loop until we
* really have work to do.
*/
mono_os_cond_wait (&work_cond, &lock);
}
}
static mono_native_thread_return_t
thread_func (void *data)
{
int worker_index = (int)(gsize)data;
int current_context;
void *thread_data = NULL;
sgen_client_thread_register_worker ();
for (current_context = 0; current_context < contexts_num; current_context++) {
if (worker_index >= pool_contexts [current_context].num_threads ||
!pool_contexts [current_context].thread_init_func)
break;
thread_data = (pool_contexts [current_context].thread_datas) ? pool_contexts [current_context].thread_datas [worker_index] : NULL;
pool_contexts [current_context].thread_init_func (thread_data);
}
current_context = 0;
mono_os_mutex_lock (&lock);
for (;;) {
gboolean do_idle = FALSE;
SgenThreadPoolJob *job = NULL;
SgenThreadPoolContext *context = NULL;
threads_context [worker_index] = -1;
get_work (worker_index, ¤t_context, &do_idle, &job);
threads_context [worker_index] = current_context;
if (!threadpool_shutdown) {
context = &pool_contexts [current_context];
thread_data = (context->thread_datas) ? context->thread_datas [worker_index] : NULL;
}
mono_os_mutex_unlock (&lock);
if (job) {
job->func (thread_data, job);
mono_os_mutex_lock (&lock);
SGEN_ASSERT (0, job->state == STATE_IN_PROGRESS, "The job should still be in progress.");
job->state = STATE_DONE;
remove_job (context, job);
/*
* Only the main GC thread will ever wait on the done condition, so we don't
* have to broadcast.
*/
mono_os_cond_signal (&done_cond);
} else if (do_idle) {
SGEN_ASSERT (0, context->idle_job_func, "Why do we have idle work when there's no idle job function?");
do {
context->idle_job_func (thread_data);
do_idle = continue_idle_job (context, thread_data);
} while (do_idle && !has_priority_work (worker_index, current_context));
mono_os_mutex_lock (&lock);
if (!do_idle)
mono_os_cond_signal (&done_cond);
} else {
SGEN_ASSERT (0, threadpool_shutdown, "Why did we unlock if no jobs and not shutting down?");
mono_os_mutex_lock (&lock);
threads_finished++;
mono_os_cond_signal (&done_cond);
mono_os_mutex_unlock (&lock);
return 0;
}
}
return 0;
}
int
sgen_thread_pool_create_context (int num_threads, SgenThreadPoolThreadInitFunc init_func, SgenThreadPoolIdleJobFunc idle_func, SgenThreadPoolContinueIdleJobFunc continue_idle_func, SgenThreadPoolShouldWorkFunc should_work_func, void **thread_datas)
{
int context_id = contexts_num;
SGEN_ASSERT (0, contexts_num < SGEN_THREADPOOL_MAX_NUM_CONTEXTS, "Maximum sgen thread pool contexts reached");
pool_contexts [context_id].thread_init_func = init_func;
pool_contexts [context_id].idle_job_func = idle_func;
pool_contexts [context_id].continue_idle_job_func = continue_idle_func;
pool_contexts [context_id].should_work_func = should_work_func;
pool_contexts [context_id].thread_datas = thread_datas;
SGEN_ASSERT (0, num_threads <= SGEN_THREADPOOL_MAX_NUM_THREADS, "Maximum sgen thread pool threads exceeded");
pool_contexts [context_id].num_threads = num_threads;
sgen_pointer_queue_init (&pool_contexts [contexts_num].job_queue, 0);
// Job batches normally split into num_threads * 4 jobs. Make room for up to four job batches in the deferred queue (should reduce flushes during minor collections).
pool_contexts [context_id].deferred_jobs_len = (num_threads * 4 * 4) + 1;
pool_contexts [context_id].deferred_jobs = (void **)sgen_alloc_internal_dynamic (sizeof (void *) * pool_contexts [context_id].deferred_jobs_len, INTERNAL_MEM_THREAD_POOL_JOB, TRUE);
pool_contexts [context_id].deferred_jobs_count = 0;
contexts_num++;
return context_id;
}
void
sgen_thread_pool_start (void)
{
int i;
for (i = 0; i < contexts_num; i++) {
if (threads_num < pool_contexts [i].num_threads)
threads_num = pool_contexts [i].num_threads;
}
if (!threads_num)
return;
mono_os_mutex_init (&lock);
mono_os_cond_init (&work_cond);
mono_os_cond_init (&done_cond);
threads_finished = 0;
threadpool_shutdown = FALSE;
for (i = 0; i < threads_num; i++) {
mono_native_thread_create (&threads [i], (gpointer)thread_func, (void*)(gsize)i);
}
}
void
sgen_thread_pool_shutdown (void)
{
if (!threads_num)
return;
mono_os_mutex_lock (&lock);
threadpool_shutdown = TRUE;
mono_os_cond_broadcast (&work_cond);
while (threads_finished < threads_num)
mono_os_cond_wait (&done_cond, &lock);
mono_os_mutex_unlock (&lock);
mono_os_mutex_destroy (&lock);
mono_os_cond_destroy (&work_cond);
mono_os_cond_destroy (&done_cond);
for (int i = 0; i < threads_num; i++) {
mono_threads_add_joinable_thread ((gpointer)(gsize)threads [i]);
}
}
SgenThreadPoolJob*
sgen_thread_pool_job_alloc (const char *name, SgenThreadPoolJobFunc func, size_t size)
{
SgenThreadPoolJob *job = (SgenThreadPoolJob *)sgen_alloc_internal_dynamic (size, INTERNAL_MEM_THREAD_POOL_JOB, TRUE);
job->name = name;
job->size = size;
job->state = STATE_WAITING;
job->func = func;
return job;
}
void
sgen_thread_pool_job_free (SgenThreadPoolJob *job)
{
sgen_free_internal_dynamic (job, job->size, INTERNAL_MEM_THREAD_POOL_JOB);
}
void
sgen_thread_pool_job_enqueue (int context_id, SgenThreadPoolJob *job)
{
mono_os_mutex_lock (&lock);
sgen_pointer_queue_add (&pool_contexts [context_id].job_queue, job);
mono_os_cond_broadcast (&work_cond);
mono_os_mutex_unlock (&lock);
}
/*
* LOCKING: Assumes the GC lock is held (or it will race with sgen_thread_pool_flush_deferred_jobs)
*/
void
sgen_thread_pool_job_enqueue_deferred (int context_id, SgenThreadPoolJob *job)
{
// Fast path assumes the GC lock is held.
pool_contexts [context_id].deferred_jobs [pool_contexts [context_id].deferred_jobs_count++] = job;
if (pool_contexts [context_id].deferred_jobs_count >= pool_contexts [context_id].deferred_jobs_len) {
// Slow path, flush jobs into queue, but don't signal workers.
sgen_thread_pool_flush_deferred_jobs (context_id, FALSE);
}
}
/*
* LOCKING: Assumes the GC lock is held (or it will race with sgen_thread_pool_job_enqueue_deferred).
*/
void
sgen_thread_pool_flush_deferred_jobs (int context_id, gboolean signal)
{
if (!signal && !sgen_thread_pool_have_deferred_jobs (context_id))
return;
mono_os_mutex_lock (&lock);
for (int i = 0; i < pool_contexts [context_id].deferred_jobs_count; i++) {
sgen_pointer_queue_add (&pool_contexts[context_id].job_queue, pool_contexts [context_id].deferred_jobs [i]);
pool_contexts [context_id].deferred_jobs [i] = NULL;
}
pool_contexts [context_id].deferred_jobs_count = 0;
if (signal)
mono_os_cond_broadcast (&work_cond);
mono_os_mutex_unlock (&lock);
}
gboolean sgen_thread_pool_have_deferred_jobs (int context_id)
{
return pool_contexts [context_id].deferred_jobs_count != 0;
}
void
sgen_thread_pool_job_wait (int context_id, SgenThreadPoolJob *job)
{
SGEN_ASSERT (0, job, "Where's the job?");
mono_os_mutex_lock (&lock);
while (find_job_in_queue (&pool_contexts [context_id], job) >= 0)
mono_os_cond_wait (&done_cond, &lock);
mono_os_mutex_unlock (&lock);
}
void
sgen_thread_pool_idle_signal (int context_id)
{
SGEN_ASSERT (0, pool_contexts [context_id].idle_job_func, "Why are we signaling idle without an idle function?");
mono_os_mutex_lock (&lock);
if (pool_contexts [context_id].continue_idle_job_func (NULL, context_id))
mono_os_cond_broadcast (&work_cond);
mono_os_mutex_unlock (&lock);
}
void
sgen_thread_pool_idle_wait (int context_id, SgenThreadPoolContinueIdleWaitFunc continue_wait)
{
SGEN_ASSERT (0, pool_contexts [context_id].idle_job_func, "Why are we waiting for idle without an idle function?");
mono_os_mutex_lock (&lock);
while (continue_wait (context_id, threads_context))
mono_os_cond_wait (&done_cond, &lock);
mono_os_mutex_unlock (&lock);
}
void
sgen_thread_pool_wait_for_all_jobs (int context_id)
{
mono_os_mutex_lock (&lock);
while (!sgen_pointer_queue_is_empty (&pool_contexts [context_id].job_queue))
mono_os_cond_wait (&done_cond, &lock);
mono_os_mutex_unlock (&lock);
}
/* Return 0 if is not a thread pool thread or the thread number otherwise */
int
sgen_thread_pool_is_thread_pool_thread (MonoNativeThreadId some_thread)
{
int i;
for (i = 0; i < threads_num; i++) {
if (some_thread == threads [i])
return i + 1;
}
return 0;
}
#else
int
sgen_thread_pool_create_context (int num_threads, SgenThreadPoolThreadInitFunc init_func, SgenThreadPoolIdleJobFunc idle_func, SgenThreadPoolContinueIdleJobFunc continue_idle_func, SgenThreadPoolShouldWorkFunc should_work_func, void **thread_datas)
{
return 0;
}
void
sgen_thread_pool_start (void)
{
}
void
sgen_thread_pool_shutdown (void)
{
}
SgenThreadPoolJob*
sgen_thread_pool_job_alloc (const char *name, SgenThreadPoolJobFunc func, size_t size)
{
SgenThreadPoolJob *job = (SgenThreadPoolJob *)sgen_alloc_internal_dynamic (size, INTERNAL_MEM_THREAD_POOL_JOB, TRUE);
job->name = name;
job->size = size;
job->func = func;
return job;
}
void
sgen_thread_pool_job_free (SgenThreadPoolJob *job)
{
sgen_free_internal_dynamic (job, job->size, INTERNAL_MEM_THREAD_POOL_JOB);
}
void
sgen_thread_pool_job_enqueue (int context_id, SgenThreadPoolJob *job)
{
}
void
sgen_thread_pool_job_enqueue_deferred (int context_id, SgenThreadPoolJob *job)
{
}
void
sgen_thread_pool_flush_deferred_jobs (int context_id, gboolean signal)
{
}
gboolean sgen_thread_pool_have_deferred_jobs (int context_id)
{
return FALSE;
}
void
sgen_thread_pool_job_wait (int context_id, SgenThreadPoolJob *job)
{
}
void
sgen_thread_pool_idle_signal (int context_id)
{
}
void
sgen_thread_pool_idle_wait (int context_id, SgenThreadPoolContinueIdleWaitFunc continue_wait)
{
}
void
sgen_thread_pool_wait_for_all_jobs (int context_id)
{
}
int
sgen_thread_pool_is_thread_pool_thread (MonoNativeThreadId some_thread)
{
return 0;
}
#endif
#endif
|
894903.c | /*-
* BSD LICENSE
*
* Copyright (c) Intel Corporation.
* 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 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 THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "nvme_internal.h"
static inline struct spdk_nvme_ns_data *
_nvme_ns_get_data(struct spdk_nvme_ns *ns)
{
return &ns->ctrlr->nsdata[ns->id - 1];
}
static
int nvme_ns_identify_update(struct spdk_nvme_ns *ns)
{
struct nvme_completion_poll_status status;
struct spdk_nvme_ns_data *nsdata;
int rc;
nsdata = _nvme_ns_get_data(ns);
status.done = false;
rc = nvme_ctrlr_cmd_identify_namespace(ns->ctrlr, ns->id, nsdata,
nvme_completion_poll_cb, &status);
if (rc != 0) {
return rc;
}
while (status.done == false) {
pthread_mutex_lock(&ns->ctrlr->ctrlr_lock);
spdk_nvme_qpair_process_completions(&ns->ctrlr->adminq, 0);
pthread_mutex_unlock(&ns->ctrlr->ctrlr_lock);
}
if (spdk_nvme_cpl_is_error(&status.cpl)) {
/* This can occur if the namespace is not active. Simply zero the
* namespace data and continue. */
memset(nsdata, 0, sizeof(*nsdata));
ns->stripe_size = 0;
ns->sector_size = 0;
ns->md_size = 0;
ns->pi_type = 0;
ns->sectors_per_max_io = 0;
ns->sectors_per_stripe = 0;
ns->flags = 0;
return 0;
}
ns->sector_size = 1 << nsdata->lbaf[nsdata->flbas.format].lbads;
ns->sectors_per_max_io = spdk_nvme_ns_get_max_io_xfer_size(ns) / ns->sector_size;
ns->sectors_per_stripe = ns->stripe_size / ns->sector_size;
ns->flags = 0x0000;
if (ns->ctrlr->cdata.oncs.dsm) {
ns->flags |= SPDK_NVME_NS_DEALLOCATE_SUPPORTED;
}
if (ns->ctrlr->cdata.vwc.present) {
ns->flags |= SPDK_NVME_NS_FLUSH_SUPPORTED;
}
if (ns->ctrlr->cdata.oncs.write_zeroes) {
ns->flags |= SPDK_NVME_NS_WRITE_ZEROES_SUPPORTED;
}
if (nsdata->nsrescap.raw) {
ns->flags |= SPDK_NVME_NS_RESERVATION_SUPPORTED;
}
ns->md_size = nsdata->lbaf[nsdata->flbas.format].ms;
ns->pi_type = SPDK_NVME_FMT_NVM_PROTECTION_DISABLE;
if (nsdata->lbaf[nsdata->flbas.format].ms && nsdata->dps.pit) {
ns->flags |= SPDK_NVME_NS_DPS_PI_SUPPORTED;
ns->pi_type = nsdata->dps.pit;
if (nsdata->flbas.extended)
ns->flags |= SPDK_NVME_NS_EXTENDED_LBA_SUPPORTED;
}
return rc;
}
uint32_t
spdk_nvme_ns_get_id(struct spdk_nvme_ns *ns)
{
return ns->id;
}
bool
spdk_nvme_ns_is_active(struct spdk_nvme_ns *ns)
{
const struct spdk_nvme_ns_data *nsdata = _nvme_ns_get_data(ns);
/*
* According to the spec, Identify Namespace will return a zero-filled structure for
* inactive namespace IDs.
* Check NCAP since it must be nonzero for an active namespace.
*/
return nsdata->ncap != 0;
}
uint32_t
spdk_nvme_ns_get_max_io_xfer_size(struct spdk_nvme_ns *ns)
{
return ns->ctrlr->max_xfer_size;
}
uint32_t
spdk_nvme_ns_get_sector_size(struct spdk_nvme_ns *ns)
{
return ns->sector_size;
}
uint64_t
spdk_nvme_ns_get_num_sectors(struct spdk_nvme_ns *ns)
{
return _nvme_ns_get_data(ns)->nsze;
}
uint64_t
spdk_nvme_ns_get_size(struct spdk_nvme_ns *ns)
{
return spdk_nvme_ns_get_num_sectors(ns) * spdk_nvme_ns_get_sector_size(ns);
}
uint32_t
spdk_nvme_ns_get_flags(struct spdk_nvme_ns *ns)
{
return ns->flags;
}
enum spdk_nvme_pi_type
spdk_nvme_ns_get_pi_type(struct spdk_nvme_ns *ns) {
return ns->pi_type;
}
bool
spdk_nvme_ns_supports_extended_lba(struct spdk_nvme_ns *ns)
{
return (ns->flags & SPDK_NVME_NS_EXTENDED_LBA_SUPPORTED) ? true : false;
}
uint32_t
spdk_nvme_ns_get_md_size(struct spdk_nvme_ns *ns)
{
return ns->md_size;
}
const struct spdk_nvme_ns_data *
spdk_nvme_ns_get_data(struct spdk_nvme_ns *ns)
{
nvme_ns_identify_update(ns);
return _nvme_ns_get_data(ns);
}
int nvme_ns_construct(struct spdk_nvme_ns *ns, uint16_t id,
struct spdk_nvme_ctrlr *ctrlr)
{
struct pci_id pci_id;
assert(id > 0);
ns->ctrlr = ctrlr;
ns->id = id;
ns->stripe_size = 0;
if (ctrlr->transport->ctrlr_get_pci_id(ctrlr, &pci_id) == 0) {
if (pci_id.vendor_id == SPDK_PCI_VID_INTEL &&
pci_id.dev_id == INTEL_DC_P3X00_DEVID &&
ctrlr->cdata.vs[3] != 0) {
ns->stripe_size = (1 << ctrlr->cdata.vs[3]) * ctrlr->min_page_size;
}
}
return nvme_ns_identify_update(ns);
}
void nvme_ns_destruct(struct spdk_nvme_ns *ns)
{
}
|
621696.c | /*********************************************************************
main.c - AnalyzeCopy - exercise hardlinked files with /bin/cp
Copyright (c) 2011 - opcoders.com
Simon Strandgaard <[email protected]>
if hardlinked files are preserved then this test should output
TEST SUCCESS: hardlinked files are copied correct, inodes the same
however this test fails on my Mac OS X 10.6.6 (10J567) and outputs
TEST FAILED: hardlinked files are not copied correct, inodes differs: 30537084 30537085 30537086
*********************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
void print_cwd() {
char* cwd = getcwd(0, 0);
if(!cwd) {
printf("getcwd failed: %s\n", strerror (errno));
exit(EXIT_FAILURE);
}
printf("%s\n", cwd);
free(cwd);
}
void mkdir_source() {
int ret = mkdir("source", 0755);
if(ret != 0) {
printf("mkdir failed: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
}
void chdir_source() {
int ret = chdir("source");
if(ret != 0) {
printf("chdir failed: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
}
void create_file(const char* filename) {
FILE* file = fopen(filename, "w");
fprintf(file, "hello", 0);
fclose(file);
}
void create_hardlink(const char* path1, const char* path2) {
int ret = link(path1, path2);
if(ret != 0) {
printf("link failed: %s\n", strerror (errno));
exit(EXIT_FAILURE);
}
}
void chdir_parent() {
int ret = chdir("..");
if(ret != 0) {
printf("chdir failed: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
}
void chdir_target() {
int ret = chdir("target");
if(ret != 0) {
printf("chdir failed: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
}
ino_t get_inode(const char* filename) {
struct stat buf;
int ret = stat(filename, &buf);
if(ret != 0) {
printf("stat failed: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
return buf.st_ino;
}
int main (int argc, const char * argv[]) {
print_cwd();
// prepare source dir content
{
mkdir_source();
chdir_source();
create_file("file1");
create_hardlink("file1", "file2");
create_hardlink("file2", "file3");
chdir_parent();
}
// copy content from source dir to target dir
system("/bin/cp -Rp source target");
// verify target dir content
{
chdir_target();
ino_t i1 = get_inode("file1");
ino_t i2 = get_inode("file2");
ino_t i3 = get_inode("file3");
if((i1 != i2) || (i1 != i3)) {
printf("TEST FAILED: hardlinked files are not copied correct, inodes differs: %lli %lli %lli\n", i1, i2, i3);
} else {
printf("TEST SUCCESS: hardlinked files are copied correct, inodes the same");
}
chdir_parent();
}
return EXIT_SUCCESS;
}
|
915672.c | /* Copyright (C) 1995-1998 Eric Young ([email protected])
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young ([email protected]).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson ([email protected]).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* 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 copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young ([email protected])"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson ([email protected])"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.] */
#include <ctype.h>
#include <string.h>
#include <CNIOBoringSSL_asn1.h>
#include <CNIOBoringSSL_asn1t.h>
#include <CNIOBoringSSL_buf.h>
#include <CNIOBoringSSL_err.h>
#include <CNIOBoringSSL_mem.h>
#include <CNIOBoringSSL_obj.h>
#include <CNIOBoringSSL_stack.h>
#include <CNIOBoringSSL_x509.h>
#include "../asn1/internal.h"
#include "../internal.h"
#include "internal.h"
typedef STACK_OF(X509_NAME_ENTRY) STACK_OF_X509_NAME_ENTRY;
DEFINE_STACK_OF(STACK_OF_X509_NAME_ENTRY)
/*
* Maximum length of X509_NAME: much larger than anything we should
* ever see in practice.
*/
#define X509_NAME_MAX (1024 * 1024)
static int x509_name_ex_d2i(ASN1_VALUE **val,
const unsigned char **in, long len,
const ASN1_ITEM *it,
int tag, int aclass, char opt, ASN1_TLC *ctx);
static int x509_name_ex_i2d(ASN1_VALUE **val, unsigned char **out,
const ASN1_ITEM *it, int tag, int aclass);
static int x509_name_ex_new(ASN1_VALUE **val, const ASN1_ITEM *it);
static void x509_name_ex_free(ASN1_VALUE **val, const ASN1_ITEM *it);
static int x509_name_encode(X509_NAME *a);
static int x509_name_canon(X509_NAME *a);
static int asn1_string_canon(ASN1_STRING *out, ASN1_STRING *in);
static int i2d_name_canon(STACK_OF(STACK_OF_X509_NAME_ENTRY) * intname,
unsigned char **in);
ASN1_SEQUENCE(X509_NAME_ENTRY) = {
ASN1_SIMPLE(X509_NAME_ENTRY, object, ASN1_OBJECT),
ASN1_SIMPLE(X509_NAME_ENTRY, value, ASN1_PRINTABLE)
} ASN1_SEQUENCE_END(X509_NAME_ENTRY)
IMPLEMENT_ASN1_FUNCTIONS(X509_NAME_ENTRY)
IMPLEMENT_ASN1_DUP_FUNCTION(X509_NAME_ENTRY)
/*
* For the "Name" type we need a SEQUENCE OF { SET OF X509_NAME_ENTRY } so
* declare two template wrappers for this
*/
ASN1_ITEM_TEMPLATE(X509_NAME_ENTRIES) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SET_OF, 0, RDNS, X509_NAME_ENTRY)
ASN1_ITEM_TEMPLATE_END(X509_NAME_ENTRIES)
ASN1_ITEM_TEMPLATE(X509_NAME_INTERNAL) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, Name, X509_NAME_ENTRIES)
ASN1_ITEM_TEMPLATE_END(X509_NAME_INTERNAL)
/*
* Normally that's where it would end: we'd have two nested STACK structures
* representing the ASN1. Unfortunately X509_NAME uses a completely different
* form and caches encodings so we have to process the internal form and
* convert to the external form.
*/
static const ASN1_EXTERN_FUNCS x509_name_ff = {
NULL,
x509_name_ex_new,
x509_name_ex_free,
0, /* Default clear behaviour is OK */
x509_name_ex_d2i,
x509_name_ex_i2d,
NULL,
};
IMPLEMENT_EXTERN_ASN1(X509_NAME, V_ASN1_SEQUENCE, x509_name_ff)
IMPLEMENT_ASN1_FUNCTIONS(X509_NAME)
IMPLEMENT_ASN1_DUP_FUNCTION(X509_NAME)
static int x509_name_ex_new(ASN1_VALUE **val, const ASN1_ITEM *it)
{
X509_NAME *ret = NULL;
ret = OPENSSL_malloc(sizeof(X509_NAME));
if (!ret)
goto memerr;
if ((ret->entries = sk_X509_NAME_ENTRY_new_null()) == NULL)
goto memerr;
if ((ret->bytes = BUF_MEM_new()) == NULL)
goto memerr;
ret->canon_enc = NULL;
ret->canon_enclen = 0;
ret->modified = 1;
*val = (ASN1_VALUE *)ret;
return 1;
memerr:
OPENSSL_PUT_ERROR(X509, ERR_R_MALLOC_FAILURE);
if (ret) {
if (ret->entries)
sk_X509_NAME_ENTRY_free(ret->entries);
OPENSSL_free(ret);
}
return 0;
}
static void x509_name_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it)
{
X509_NAME *a;
if (!pval || !*pval)
return;
a = (X509_NAME *)*pval;
BUF_MEM_free(a->bytes);
sk_X509_NAME_ENTRY_pop_free(a->entries, X509_NAME_ENTRY_free);
if (a->canon_enc)
OPENSSL_free(a->canon_enc);
OPENSSL_free(a);
*pval = NULL;
}
static void local_sk_X509_NAME_ENTRY_free(STACK_OF(X509_NAME_ENTRY) *ne)
{
sk_X509_NAME_ENTRY_free(ne);
}
static void local_sk_X509_NAME_ENTRY_pop_free(STACK_OF(X509_NAME_ENTRY) *ne)
{
sk_X509_NAME_ENTRY_pop_free(ne, X509_NAME_ENTRY_free);
}
static int x509_name_ex_d2i(ASN1_VALUE **val,
const unsigned char **in, long len,
const ASN1_ITEM *it, int tag, int aclass,
char opt, ASN1_TLC *ctx)
{
const unsigned char *p = *in, *q;
STACK_OF(STACK_OF_X509_NAME_ENTRY) *intname = NULL;
X509_NAME *nm = NULL;
size_t i, j;
int ret;
STACK_OF(X509_NAME_ENTRY) *entries;
X509_NAME_ENTRY *entry;
/* Bound the size of an X509_NAME we are willing to parse. */
if (len > X509_NAME_MAX) {
len = X509_NAME_MAX;
}
q = p;
/* Get internal representation of Name */
ASN1_VALUE *intname_val = NULL;
ret = ASN1_item_ex_d2i(&intname_val,
&p, len, ASN1_ITEM_rptr(X509_NAME_INTERNAL),
tag, aclass, opt, ctx);
if (ret <= 0)
return ret;
intname = (STACK_OF(STACK_OF_X509_NAME_ENTRY) *)intname_val;
if (*val)
x509_name_ex_free(val, NULL);
ASN1_VALUE *nm_val = NULL;
if (!x509_name_ex_new(&nm_val, NULL))
goto err;
nm = (X509_NAME *)nm_val;
/* We've decoded it: now cache encoding */
if (!BUF_MEM_grow(nm->bytes, p - q))
goto err;
OPENSSL_memcpy(nm->bytes->data, q, p - q);
/* Convert internal representation to X509_NAME structure */
for (i = 0; i < sk_STACK_OF_X509_NAME_ENTRY_num(intname); i++) {
entries = sk_STACK_OF_X509_NAME_ENTRY_value(intname, i);
for (j = 0; j < sk_X509_NAME_ENTRY_num(entries); j++) {
entry = sk_X509_NAME_ENTRY_value(entries, j);
entry->set = i;
if (!sk_X509_NAME_ENTRY_push(nm->entries, entry))
goto err;
(void)sk_X509_NAME_ENTRY_set(entries, j, NULL);
}
}
ret = x509_name_canon(nm);
if (!ret)
goto err;
sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname,
local_sk_X509_NAME_ENTRY_free);
nm->modified = 0;
*val = (ASN1_VALUE *)nm;
*in = p;
return ret;
err:
X509_NAME_free(nm);
sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname,
local_sk_X509_NAME_ENTRY_pop_free);
OPENSSL_PUT_ERROR(X509, ERR_R_ASN1_LIB);
return 0;
}
static int x509_name_ex_i2d(ASN1_VALUE **val, unsigned char **out,
const ASN1_ITEM *it, int tag, int aclass)
{
X509_NAME *a = (X509_NAME *)*val;
if (a->modified &&
(!x509_name_encode(a) ||
!x509_name_canon(a))) {
return -1;
}
int ret = a->bytes->length;
if (out != NULL) {
OPENSSL_memcpy(*out, a->bytes->data, ret);
*out += ret;
}
return ret;
}
static int x509_name_encode(X509_NAME *a)
{
int len;
unsigned char *p;
STACK_OF(X509_NAME_ENTRY) *entries = NULL;
X509_NAME_ENTRY *entry;
int set = -1;
size_t i;
STACK_OF(STACK_OF_X509_NAME_ENTRY) *intname =
sk_STACK_OF_X509_NAME_ENTRY_new_null();
if (!intname)
goto memerr;
for (i = 0; i < sk_X509_NAME_ENTRY_num(a->entries); i++) {
entry = sk_X509_NAME_ENTRY_value(a->entries, i);
if (entry->set != set) {
entries = sk_X509_NAME_ENTRY_new_null();
if (!entries)
goto memerr;
if (!sk_STACK_OF_X509_NAME_ENTRY_push(intname, entries)) {
sk_X509_NAME_ENTRY_free(entries);
goto memerr;
}
set = entry->set;
}
if (!sk_X509_NAME_ENTRY_push(entries, entry))
goto memerr;
}
ASN1_VALUE *intname_val = (ASN1_VALUE *)intname;
len =
ASN1_item_ex_i2d(&intname_val, NULL, ASN1_ITEM_rptr(X509_NAME_INTERNAL),
/*tag=*/-1, /*aclass=*/0);
if (len <= 0) {
goto err;
}
if (!BUF_MEM_grow(a->bytes, len))
goto memerr;
p = (unsigned char *)a->bytes->data;
if (ASN1_item_ex_i2d(&intname_val, &p, ASN1_ITEM_rptr(X509_NAME_INTERNAL),
/*tag=*/-1, /*aclass=*/0) <= 0) {
goto err;
}
sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname,
local_sk_X509_NAME_ENTRY_free);
a->modified = 0;
return 1;
memerr:
OPENSSL_PUT_ERROR(X509, ERR_R_MALLOC_FAILURE);
err:
sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname,
local_sk_X509_NAME_ENTRY_free);
return 0;
}
/*
* This function generates the canonical encoding of the Name structure. In
* it all strings are converted to UTF8, leading, trailing and multiple
* spaces collapsed, converted to lower case and the leading SEQUENCE header
* removed. In future we could also normalize the UTF8 too. By doing this
* comparison of Name structures can be rapidly perfomed by just using
* OPENSSL_memcmp() of the canonical encoding. By omitting the leading SEQUENCE name
* constraints of type dirName can also be checked with a simple OPENSSL_memcmp().
*/
static int x509_name_canon(X509_NAME *a)
{
unsigned char *p;
STACK_OF(STACK_OF_X509_NAME_ENTRY) *intname = NULL;
STACK_OF(X509_NAME_ENTRY) *entries = NULL;
X509_NAME_ENTRY *entry, *tmpentry = NULL;
int set = -1, ret = 0, len;
size_t i;
if (a->canon_enc) {
OPENSSL_free(a->canon_enc);
a->canon_enc = NULL;
}
/* Special case: empty X509_NAME => null encoding */
if (sk_X509_NAME_ENTRY_num(a->entries) == 0) {
a->canon_enclen = 0;
return 1;
}
intname = sk_STACK_OF_X509_NAME_ENTRY_new_null();
if (!intname)
goto err;
for (i = 0; i < sk_X509_NAME_ENTRY_num(a->entries); i++) {
entry = sk_X509_NAME_ENTRY_value(a->entries, i);
if (entry->set != set) {
entries = sk_X509_NAME_ENTRY_new_null();
if (!entries)
goto err;
if (!sk_STACK_OF_X509_NAME_ENTRY_push(intname, entries)) {
sk_X509_NAME_ENTRY_free(entries);
goto err;
}
set = entry->set;
}
tmpentry = X509_NAME_ENTRY_new();
if (tmpentry == NULL)
goto err;
tmpentry->object = OBJ_dup(entry->object);
if (!asn1_string_canon(tmpentry->value, entry->value))
goto err;
if (!sk_X509_NAME_ENTRY_push(entries, tmpentry))
goto err;
tmpentry = NULL;
}
/* Finally generate encoding */
len = i2d_name_canon(intname, NULL);
if (len < 0) {
goto err;
}
a->canon_enclen = len;
p = OPENSSL_malloc(a->canon_enclen);
if (!p)
goto err;
a->canon_enc = p;
i2d_name_canon(intname, &p);
ret = 1;
err:
if (tmpentry)
X509_NAME_ENTRY_free(tmpentry);
if (intname)
sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname,
local_sk_X509_NAME_ENTRY_pop_free);
return ret;
}
/* Bitmap of all the types of string that will be canonicalized. */
#define ASN1_MASK_CANON \
(B_ASN1_UTF8STRING | B_ASN1_BMPSTRING | B_ASN1_UNIVERSALSTRING \
| B_ASN1_PRINTABLESTRING | B_ASN1_T61STRING | B_ASN1_IA5STRING \
| B_ASN1_VISIBLESTRING)
static int asn1_string_canon(ASN1_STRING *out, ASN1_STRING *in)
{
unsigned char *to, *from;
int len, i;
/* If type not in bitmask just copy string across */
if (!(ASN1_tag2bit(in->type) & ASN1_MASK_CANON)) {
if (!ASN1_STRING_copy(out, in))
return 0;
return 1;
}
out->type = V_ASN1_UTF8STRING;
out->length = ASN1_STRING_to_UTF8(&out->data, in);
if (out->length == -1)
return 0;
to = out->data;
from = to;
len = out->length;
/*
* Convert string in place to canonical form. Ultimately we may need to
* handle a wider range of characters but for now ignore anything with
* MSB set and rely on the isspace() and tolower() functions.
*/
/* Ignore leading spaces */
while ((len > 0) && !(*from & 0x80) && isspace(*from)) {
from++;
len--;
}
to = from + len;
/* Ignore trailing spaces */
while ((len > 0) && !(to[-1] & 0x80) && isspace(to[-1])) {
to--;
len--;
}
to = out->data;
i = 0;
while (i < len) {
/* If MSB set just copy across */
if (*from & 0x80) {
*to++ = *from++;
i++;
}
/* Collapse multiple spaces */
else if (isspace(*from)) {
/* Copy one space across */
*to++ = ' ';
/*
* Ignore subsequent spaces. Note: don't need to check len here
* because we know the last character is a non-space so we can't
* overflow.
*/
do {
from++;
i++;
}
while (!(*from & 0x80) && isspace(*from));
} else {
*to++ = OPENSSL_tolower(*from);
from++;
i++;
}
}
out->length = to - out->data;
return 1;
}
static int i2d_name_canon(STACK_OF(STACK_OF_X509_NAME_ENTRY) * _intname,
unsigned char **in)
{
int len, ltmp;
size_t i;
ASN1_VALUE *v;
STACK_OF(ASN1_VALUE) *intname = (STACK_OF(ASN1_VALUE) *)_intname;
len = 0;
for (i = 0; i < sk_ASN1_VALUE_num(intname); i++) {
v = sk_ASN1_VALUE_value(intname, i);
ltmp = ASN1_item_ex_i2d(&v, in, ASN1_ITEM_rptr(X509_NAME_ENTRIES),
/*tag=*/-1, /*aclass=*/0);
if (ltmp < 0)
return ltmp;
len += ltmp;
}
return len;
}
int X509_NAME_set(X509_NAME **xn, X509_NAME *name)
{
if ((name = X509_NAME_dup(name)) == NULL)
return 0;
X509_NAME_free(*xn);
*xn = name;
return 1;
}
int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
{
return ne->set;
}
int X509_NAME_get0_der(X509_NAME *nm, const unsigned char **pder,
size_t *pderlen)
{
/* Make sure encoding is valid */
if (i2d_X509_NAME(nm, NULL) <= 0)
return 0;
if (pder != NULL)
*pder = (unsigned char *)nm->bytes->data;
if (pderlen != NULL)
*pderlen = nm->bytes->length;
return 1;
}
|
932134.c | //*****************************************************************************
//
//! @page xrtc_testcase xrtc register test
//!
//! File: @ref xrtctest.c
//!
//! <h2>Description</h2>
//! This module implements the test sequence for the xrtc sub component.<br><br>
//! - \p Board: HT32F125x <br><br>
//! - \p Last-Time(about): 0.5s <br><br>
//! - \p Phenomenon: Success or failure information will be printed on the UART. <br><br>
//! .
//!
//! <h2>Preconditions</h2>
//! The module requires the following options:<br><br>
//! - \p Option-define:
//! <br>(1)None.<br><br>
//! - \p Option-hardware:
//! <br>(1)Connect an USB cable to the development board.<br><br>
//! - \p Option-OtherModule:
//! <br>Connect an COM cable to the development board.<br>
//! .
//! In case some of the required options are not enabled then some or all tests
//! may be skipped or result FAILED.<br>
//!
//! <h2>Test Cases</h2>
//! The module contain those sub tests:<br><br>
//! - \subpage test_xrtc_register
//! .
//! \file xrtctest.c
//! \brief xrtc test source file
//! \brief xrtc test header file <br>
//
//*****************************************************************************
#include "test.h"
#include "xrtc.h"
#include "xhw_rtc.h"
unsigned long i = 0, j = 0;
unsigned long ulTimeAlarm[2] = {RTC_TIME_CURRENT, RTC_TIME_ALARM};
tTime tTime1, tTime2;
unsigned long xRTCCallback(void *pvCBData,
unsigned long ulEvent,
unsigned long ulMsgParam,
void *pvMsgData)
{
if(1==(xHWREG(RTC_SR)) & RTC_SR_CSECFLAG)
{
RTCTimeRead(&tTime1, ulTimeAlarm[0]);
}
TestEmitToken('a');
return 0;
}
//*****************************************************************************
//
//! \page test_xrtc test_xrtc
//!
//! <h2>Description</h2>
//! Test xrtc. <br>
//!
//
//*****************************************************************************
//*****************************************************************************
//
//! \brief Get the Test description of xrtc001 test.
//!
//! \return the desccription of the xrtc001 test.
//
//*****************************************************************************
static char* xrtc001GetTest(void)
{
return "xrtc[001]: xrtc initalization test";
}
//*****************************************************************************
//
//! \brief Something should do before the test execute of xrtc001 test.
//!
//! \return None.
//
//*****************************************************************************
static void xrtc001Setup(void)
{
SysCtlPeripheralEnable(SYSCTL_PERIPH_RTC);
}
//*****************************************************************************
//
//! \brief Something should do after the test execute of xrtc001 test.
//!
//! \return None.
//
//*****************************************************************************
static void xrtc001TearDown(void)
{
SysCtlPeripheralEnable(SYSCTL_PERIPH_RTC);
}
//*****************************************************************************
//
//! \brief xrtc001 test main body for rtc initialization.
//!
//! \return None.
//
//*****************************************************************************
static void xrtc001Execute_Init()
{
unsigned long ulTemp;
//
// RTC initialization.
//
RTCTimeInit(RTC_CLOCK_SRC_LSE | RTC_CR_LSEEN);
ulTemp = xHWREG(RTC_CR);
TestAssert((RTC_CLOCK_SRC_LSE | RTC_CR_LSEEN) == ulTemp, "xrtc API error!");
RTCTimeInit(RTC_CLOCK_SRC_LSI | RTC_CR_LSIEN);
ulTemp = xHWREG(RTC_CR);
TestAssert((RTC_CLOCK_SRC_LSI | RTC_CR_LSIEN) == ulTemp, "xrtc API error!");
}
//*****************************************************************************
//
//! \brief xrtc001 test case struct.
//!
//! \return None.
//
//*****************************************************************************
const tTestCase sTestxrtc001Init = {
xrtc001GetTest,
xrtc001Setup,
xrtc001TearDown,
xrtc001Execute_Init
};
//*****************************************************************************
//
//! \brief Get the Test description of xrtc002 test.
//!
//! \return the desccription of the xrtc002 test.
//
//*****************************************************************************
static char* xrtc002GetTest(void)
{
return "xrtc[002]: xrtc enable test";
}
//*****************************************************************************
//
//! \brief Something should do before the test execute of xrtc002 test.
//!
//! \return None.
//
//*****************************************************************************
static void xrtc002Setup(void)
{
}
//*****************************************************************************
//
//! \brief Something should do after the test execute of xrtc002 test.
//!
//! \return None.
//
//*****************************************************************************
static void xrtc002TearDown(void)
{
}
//*****************************************************************************
//
//! \brief xrtc002 test for rtc enable.
//!
//! \return None.
//
//*****************************************************************************
static void xrtc002Execute_ENset()
{
unsigned long ulTemp;
//
// Stop and Start Enable
//
RTCStart();
ulTemp = xHWREG(RTC_CR) & RTC_CR_RTCEN;
TestAssert(ulTemp == RTC_CR_RTCEN, "xrtc API error!");
RTCStop();
ulTemp = xHWREG(RTC_CR) & RTC_CR_RTCEN;
TestAssert(0 == ulTemp, "xrtc API error!");
//
// Interrupt enable test
//
RTCIntEnable(RTC_INT_TIME_TICK);
ulTemp = xHWREG(RTC_IWEN) & RTC_INT_TIME_TICK;
TestAssert(ulTemp == RTC_INT_TIME_TICK, "xrtc API error!");
RTCIntDisable(RTC_INT_TIME_TICK);
ulTemp = xHWREG(RTC_IWEN) & RTC_INT_TIME_TICK;
TestAssert(ulTemp == 0, "xrtc API error!");
RTCIntEnable(RTC_INT_ALARM);
ulTemp = xHWREG(RTC_IWEN) & RTC_INT_ALARM;
TestAssert(ulTemp == RTC_INT_ALARM, "xrtc API error!");
RTCIntDisable(RTC_INT_ALARM);
ulTemp = xHWREG(RTC_IWEN) & RTC_INT_ALARM;
TestAssert(ulTemp == 0, "xrtc API error!");
RTCIntEnable(RTC_INT_OVERFLOW);
ulTemp = xHWREG(RTC_IWEN) & RTC_INT_OVERFLOW;
TestAssert(ulTemp == RTC_INT_OVERFLOW, "xrtc API error!");
RTCIntDisable(RTC_INT_OVERFLOW);
ulTemp = xHWREG(RTC_IWEN) & RTC_INT_OVERFLOW;
TestAssert(ulTemp == 0, "xrtc API error!");
//
// Wakeup enbale test
//
RTCWakeupEnable(RTC_WAKEUP_TIME_TICK);
ulTemp = xHWREG(RTC_IWEN) & RTC_WAKEUP_TIME_TICK;
TestAssert(ulTemp == RTC_WAKEUP_TIME_TICK, "xrtc API error!");
RTCWakeupDisable(RTC_WAKEUP_TIME_TICK);
ulTemp = xHWREG(RTC_IWEN) & RTC_WAKEUP_TIME_TICK;
TestAssert(ulTemp == 0, "xrtc API error!");
RTCWakeupEnable(RTC_WAKEUP_ALARM);
ulTemp = xHWREG(RTC_IWEN) & RTC_WAKEUP_ALARM;
TestAssert(ulTemp == RTC_WAKEUP_ALARM, "xrtc API error!");
RTCWakeupDisable(RTC_WAKEUP_ALARM);
ulTemp = xHWREG(RTC_IWEN) & RTC_WAKEUP_ALARM;
TestAssert(ulTemp == 0, "xrtc API error!");
RTCWakeupEnable(RTC_WAKEUP_OVERFLOW);
ulTemp = xHWREG(RTC_IWEN) & RTC_WAKEUP_OVERFLOW;
TestAssert(ulTemp == RTC_WAKEUP_OVERFLOW, "xrtc API error!");
RTCWakeupDisable(RTC_WAKEUP_OVERFLOW);
ulTemp = xHWREG(RTC_IWEN) & RTC_WAKEUP_OVERFLOW;
TestAssert(ulTemp == 0, "xrtc API error!");
//
// Output enable
//
RTCOutputEnable();
ulTemp = xHWREG(RTC_CR) & RTC_CR_ROEN;
TestAssert(ulTemp == RTC_CR_ROEN, "xrtc API error!");
RTCOutputDisable();
ulTemp = xHWREG(RTC_CR) & RTC_CR_ROEN;
TestAssert(ulTemp == 0, "xrtc API error!");
}
//*****************************************************************************
//
//! \brief xrtc002 test case struct.
//!
//! \return None.
//
//*****************************************************************************
const tTestCase sTestxrtc002ENset = {
xrtc002GetTest,
xrtc002Setup,
xrtc002TearDown,
xrtc002Execute_ENset
};
//*****************************************************************************
//
//! \brief Get the Test description of xrtc003 test.
//!
//! \return the desccription of the xrtc003 test.
//
//*****************************************************************************
static char* xrtc003GetTest(void)
{
return "xrtc[003]: xrtc output configure test";
}
//*****************************************************************************
//
//! \brief Something should do before the test execute of xrtc003 test.
//!
//! \return None.
//
//*****************************************************************************
static void xrtc003Setup(void)
{
}
//*****************************************************************************
//
//! \brief Something should do after the test execute of xrtc003 test.
//!
//! \return None.
//
//*****************************************************************************
static void xrtc003TearDown(void)
{
}
//*****************************************************************************
//
//! \brief xrtc003 test for rtc output configure set.
//!
//! \return None.
//
//*****************************************************************************
static void xrtc003Execute_OutputConfigTest()
{
unsigned long ulTemp;
RTCOutputConfig(RTC_CR_ROAP | RTC_CR_ROWM | RTC_CR_ROES);
ulTemp = xHWREG(RTC_CR) & (RTC_CR_ROAP | RTC_CR_ROWM | RTC_CR_ROES);
TestAssert(ulTemp == (RTC_CR_ROAP | RTC_CR_ROWM | RTC_CR_ROES), "xrtc API error!");
RTCOutputConfig(~(RTC_CR_ROAP | RTC_CR_ROWM | RTC_CR_ROES));
ulTemp = xHWREG(RTC_CR) & (RTC_CR_ROAP | RTC_CR_ROWM | RTC_CR_ROES);
TestAssert(ulTemp == 0, "xrtc API error!");
}
//*****************************************************************************
//
//! \brief xrtc003 test case struct.
//!
//! \return None.
//
//*****************************************************************************
const tTestCase sTestxrtc003Outut = {
xrtc003GetTest,
xrtc003Setup,
xrtc003TearDown,
xrtc003Execute_OutputConfigTest
};
//*****************************************************************************
//
//! \brief Get the Test description of xrtc004 test.
//!
//! \return the desccription of the xrtc004 test.
//
//*****************************************************************************
static char* xrtc004GetTest(void)
{
return "xrtc[004]: xrtc interrupt test";
}
//*****************************************************************************
//
//! \brief Something should do before the test execute of xrtc004 test.
//!
//! \return None.
//
//*****************************************************************************
static void xrtc004Setup(void)
{
}
//*****************************************************************************
//
//! \brief Something should do after the test execute of xrtc004 test.
//!
//! \return None.
//
//*****************************************************************************
static void xrtc004TearDown(void)
{
}
//*****************************************************************************
//
//! \brief xrtc004 test for rtc interrupt.
//!
//! \return None.
//
//*****************************************************************************
static void xrtc004Execute_Int()
{
tTime2.ulSecond = 40;
tTime2.ulMinute = 20;
tTime2.ulHour = 17;
tTime2.ulMDay = 11;
tTime2.ulMonth = 8;
tTime2.ulYear = 2011;
tTime2.ulWDay = 3;
//
// Writes current time to corresponding register.
//
RTCTimeWrite(&tTime2, ulTimeAlarm[0]);
//
// Alarm interrupt after 10 seconds.
//
tTime2.ulSecond +=10;
//
// Writes alarm time to corresponding register.
//
RTCTimeWrite(&tTime2, ulTimeAlarm[1]);
for(j = 0; j < 0xffff; j ++);
RTCTimeRead(&tTime1, ulTimeAlarm[1]);
TestAssert(2011 == tTime1.ulYear && 8 == tTime1.ulMonth
&& 11 == tTime1.ulMDay && 50 == tTime1.ulSecond
&& 17 == tTime1.ulHour && 20 == tTime1.ulMinute
,"xrtc API \" RTCTimeWrite()\" or \"RTCTimeRead()\" error!");
RTCIntCallbackInit(xRTCCallback);
xIntEnable(INT_RTC);
xIntMasterEnable();
//
// Enables alarm interrupt.
//
RTCIntEnable(RTC_INT_ALARM);
// TestAssertQBreak("a","Alarm interrupt failed!", 0xffffffff);
for(j = 0; j < 0xffff; j ++);
TestAssert(2011 == tTime1.ulYear && 8 == tTime1.ulMonth
&& 11 == tTime1.ulMDay && 50 == tTime1.ulSecond
&& 17 == tTime1.ulHour && 20 == tTime1.ulMinute
,"xrtc API \" RTCTimeWrite()\" or \"RTCTimeRead()\" error!");
//
// Disables alarm interrupt.
//
RTCIntDisable(RTC_INT_ALARM);
}
//*****************************************************************************
//
//! \brief xrtc004 test case struct.
//!
//! \return None.
//
//*****************************************************************************
const tTestCase sTestxrtc004Int = {
xrtc004GetTest,
xrtc004Setup,
xrtc004TearDown,
xrtc004Execute_Int
};
//
// xrtc test suits.
//
const tTestCase * const psPatternxrtc[] =
{
&sTestxrtc001Init,
&sTestxrtc002ENset,
&sTestxrtc003Outut,
&sTestxrtc004Int,
0
};
|
349489.c | /*
* PLink - a command-line (stdin/stdout) variant of PuTTY.
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <assert.h>
#include <stdarg.h>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <pwd.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#ifndef HAVE_NO_SYS_SELECT_H
#include <sys/select.h>
#endif
#define PUTTY_DO_GLOBALS /* actually _define_ globals */
#include "putty.h"
#include "storage.h"
#include "tree234.h"
#define MAX_STDIN_BACKLOG 4096
static void *logctx;
static struct termios orig_termios;
void fatalbox(const char *p, ...)
{
struct termios cf;
va_list ap;
premsg(&cf);
fprintf(stderr, "FATAL ERROR: ");
va_start(ap, p);
vfprintf(stderr, p, ap);
va_end(ap);
fputc('\n', stderr);
postmsg(&cf);
if (logctx) {
log_free(logctx);
logctx = NULL;
}
cleanup_exit(1);
}
void modalfatalbox(const char *p, ...)
{
struct termios cf;
va_list ap;
premsg(&cf);
fprintf(stderr, "FATAL ERROR: ");
va_start(ap, p);
vfprintf(stderr, p, ap);
va_end(ap);
fputc('\n', stderr);
postmsg(&cf);
if (logctx) {
log_free(logctx);
logctx = NULL;
}
cleanup_exit(1);
}
void nonfatal(const char *p, ...)
{
struct termios cf;
va_list ap;
premsg(&cf);
fprintf(stderr, "ERROR: ");
va_start(ap, p);
vfprintf(stderr, p, ap);
va_end(ap);
fputc('\n', stderr);
postmsg(&cf);
}
void connection_fatal(void *frontend, const char *p, ...)
{
struct termios cf;
va_list ap;
premsg(&cf);
fprintf(stderr, "FATAL ERROR: ");
va_start(ap, p);
vfprintf(stderr, p, ap);
va_end(ap);
fputc('\n', stderr);
postmsg(&cf);
if (logctx) {
log_free(logctx);
logctx = NULL;
}
cleanup_exit(1);
}
void cmdline_error(const char *p, ...)
{
struct termios cf;
va_list ap;
premsg(&cf);
fprintf(stderr, "plink: ");
va_start(ap, p);
vfprintf(stderr, p, ap);
va_end(ap);
fputc('\n', stderr);
postmsg(&cf);
exit(1);
}
static int local_tty = FALSE; /* do we have a local tty? */
static Backend *back;
static void *backhandle;
static Conf *conf;
/*
* Default settings that are specific to Unix plink.
*/
char *platform_default_s(const char *name)
{
if (!strcmp(name, "TermType"))
return dupstr(getenv("TERM"));
if (!strcmp(name, "SerialLine"))
return dupstr("/dev/ttyS0");
return NULL;
}
int platform_default_i(const char *name, int def)
{
return def;
}
FontSpec *platform_default_fontspec(const char *name)
{
return fontspec_new("");
}
Filename *platform_default_filename(const char *name)
{
if (!strcmp(name, "LogFileName"))
return filename_from_str("putty.log");
else
return filename_from_str("");
}
char *x_get_default(const char *key)
{
return NULL; /* this is a stub */
}
int term_ldisc(Terminal *term, int mode)
{
return FALSE;
}
void frontend_echoedit_update(void *frontend, int echo, int edit)
{
/* Update stdin read mode to reflect changes in line discipline. */
struct termios mode;
if (!local_tty) return;
mode = orig_termios;
if (echo)
mode.c_lflag |= ECHO;
else
mode.c_lflag &= ~ECHO;
if (edit) {
mode.c_iflag |= ICRNL;
mode.c_lflag |= ISIG | ICANON;
mode.c_oflag |= OPOST;
} else {
mode.c_iflag &= ~ICRNL;
mode.c_lflag &= ~(ISIG | ICANON);
mode.c_oflag &= ~OPOST;
/* Solaris sets these to unhelpful values */
mode.c_cc[VMIN] = 1;
mode.c_cc[VTIME] = 0;
/* FIXME: perhaps what we do with IXON/IXOFF should be an
* argument to frontend_echoedit_update(), to allow
* implementation of SSH-2 "xon-xoff" and Rlogin's
* equivalent? */
mode.c_iflag &= ~IXON;
mode.c_iflag &= ~IXOFF;
}
/*
* Mark parity errors and (more important) BREAK on input. This
* is more complex than it need be because POSIX-2001 suggests
* that escaping of valid 0xff in the input stream is dependent on
* IGNPAR being clear even though marking of BREAK isn't. NetBSD
* 2.0 goes one worse and makes it dependent on INPCK too. We
* deal with this by forcing these flags into a useful state and
* then faking the state in which we found them in from_tty() if
* we get passed a parity or framing error.
*/
mode.c_iflag = (mode.c_iflag | INPCK | PARMRK) & ~IGNPAR;
tcsetattr(STDIN_FILENO, TCSANOW, &mode);
}
/* Helper function to extract a special character from a termios. */
static char *get_ttychar(struct termios *t, int index)
{
cc_t c = t->c_cc[index];
#if defined(_POSIX_VDISABLE)
if (c == _POSIX_VDISABLE)
return dupstr("");
#endif
return dupprintf("^<%d>", c);
}
char *get_ttymode(void *frontend, const char *mode)
{
/*
* Propagate appropriate terminal modes from the local terminal,
* if any.
*/
if (!local_tty) return NULL;
#define GET_CHAR(ourname, uxname) \
do { \
if (strcmp(mode, ourname) == 0) \
return get_ttychar(&orig_termios, uxname); \
} while(0)
#define GET_BOOL(ourname, uxname, uxmemb, transform) \
do { \
if (strcmp(mode, ourname) == 0) { \
int b = (orig_termios.uxmemb & uxname) != 0; \
transform; \
return dupprintf("%d", b); \
} \
} while (0)
/*
* Modes that want to be the same on all terminal devices involved.
*/
/* All the special characters supported by SSH */
#if defined(VINTR)
GET_CHAR("INTR", VINTR);
#endif
#if defined(VQUIT)
GET_CHAR("QUIT", VQUIT);
#endif
#if defined(VERASE)
GET_CHAR("ERASE", VERASE);
#endif
#if defined(VKILL)
GET_CHAR("KILL", VKILL);
#endif
#if defined(VEOF)
GET_CHAR("EOF", VEOF);
#endif
#if defined(VEOL)
GET_CHAR("EOL", VEOL);
#endif
#if defined(VEOL2)
GET_CHAR("EOL2", VEOL2);
#endif
#if defined(VSTART)
GET_CHAR("START", VSTART);
#endif
#if defined(VSTOP)
GET_CHAR("STOP", VSTOP);
#endif
#if defined(VSUSP)
GET_CHAR("SUSP", VSUSP);
#endif
#if defined(VDSUSP)
GET_CHAR("DSUSP", VDSUSP);
#endif
#if defined(VREPRINT)
GET_CHAR("REPRINT", VREPRINT);
#endif
#if defined(VWERASE)
GET_CHAR("WERASE", VWERASE);
#endif
#if defined(VLNEXT)
GET_CHAR("LNEXT", VLNEXT);
#endif
#if defined(VFLUSH)
GET_CHAR("FLUSH", VFLUSH);
#endif
#if defined(VSWTCH)
GET_CHAR("SWTCH", VSWTCH);
#endif
#if defined(VSTATUS)
GET_CHAR("STATUS", VSTATUS);
#endif
#if defined(VDISCARD)
GET_CHAR("DISCARD", VDISCARD);
#endif
/* Modes that "configure" other major modes. These should probably be
* considered as user preferences. */
/* Configuration of ICANON */
#if defined(ECHOK)
GET_BOOL("ECHOK", ECHOK, c_lflag, );
#endif
#if defined(ECHOKE)
GET_BOOL("ECHOKE", ECHOKE, c_lflag, );
#endif
#if defined(ECHOE)
GET_BOOL("ECHOE", ECHOE, c_lflag, );
#endif
#if defined(ECHONL)
GET_BOOL("ECHONL", ECHONL, c_lflag, );
#endif
#if defined(XCASE)
GET_BOOL("XCASE", XCASE, c_lflag, );
#endif
#if defined(IUTF8)
GET_BOOL("IUTF8", IUTF8, c_iflag, );
#endif
/* Configuration of ECHO */
#if defined(ECHOCTL)
GET_BOOL("ECHOCTL", ECHOCTL, c_lflag, );
#endif
/* Configuration of IXON/IXOFF */
#if defined(IXANY)
GET_BOOL("IXANY", IXANY, c_iflag, );
#endif
/* Configuration of OPOST */
#if defined(OLCUC)
GET_BOOL("OLCUC", OLCUC, c_oflag, );
#endif
#if defined(ONLCR)
GET_BOOL("ONLCR", ONLCR, c_oflag, );
#endif
#if defined(OCRNL)
GET_BOOL("OCRNL", OCRNL, c_oflag, );
#endif
#if defined(ONOCR)
GET_BOOL("ONOCR", ONOCR, c_oflag, );
#endif
#if defined(ONLRET)
GET_BOOL("ONLRET", ONLRET, c_oflag, );
#endif
/*
* Modes that want to be set in only one place, and that we have
* squashed locally.
*/
#if defined(ISIG)
GET_BOOL("ISIG", ISIG, c_lflag, );
#endif
#if defined(ICANON)
GET_BOOL("ICANON", ICANON, c_lflag, );
#endif
#if defined(ECHO)
GET_BOOL("ECHO", ECHO, c_lflag, );
#endif
#if defined(IXON)
GET_BOOL("IXON", IXON, c_iflag, );
#endif
#if defined(IXOFF)
GET_BOOL("IXOFF", IXOFF, c_iflag, );
#endif
#if defined(OPOST)
GET_BOOL("OPOST", OPOST, c_oflag, );
#endif
/*
* We do not propagate the following modes:
* - Parity/serial settings, which are a local affair and don't
* make sense propagated over SSH's 8-bit byte-stream.
* IGNPAR PARMRK INPCK CS7 CS8 PARENB PARODD
* - Things that want to be enabled in one place that we don't
* squash locally.
* IUCLC
* - Status bits.
* PENDIN
* - Things I don't know what to do with. (FIXME)
* ISTRIP IMAXBEL NOFLSH TOSTOP IEXTEN
* INLCR IGNCR ICRNL
*/
#undef GET_CHAR
#undef GET_BOOL
/* Fall through to here for unrecognised names, or ones that are
* unsupported on this platform */
return NULL;
}
void cleanup_termios(void)
{
if (local_tty)
tcsetattr(STDIN_FILENO, TCSANOW, &orig_termios);
}
bufchain stdout_data, stderr_data;
enum { EOF_NO, EOF_PENDING, EOF_SENT } outgoingeof;
int try_output(int is_stderr)
{
bufchain *chain = (is_stderr ? &stderr_data : &stdout_data);
int fd = (is_stderr ? STDERR_FILENO : STDOUT_FILENO);
void *senddata;
int sendlen, ret;
if (bufchain_size(chain) > 0) {
int prev_nonblock = nonblock(fd);
do {
bufchain_prefix(chain, &senddata, &sendlen);
ret = write(fd, senddata, sendlen);
if (ret > 0)
bufchain_consume(chain, ret);
} while (ret == sendlen && bufchain_size(chain) != 0);
if (!prev_nonblock)
no_nonblock(fd);
if (ret < 0 && errno != EAGAIN) {
perror(is_stderr ? "stderr: write" : "stdout: write");
exit(1);
}
}
if (outgoingeof == EOF_PENDING && bufchain_size(&stdout_data) == 0) {
close(STDOUT_FILENO);
outgoingeof = EOF_SENT;
}
return bufchain_size(&stdout_data) + bufchain_size(&stderr_data);
}
int from_backend(void *frontend_handle, int is_stderr,
const char *data, int len)
{
if (is_stderr) {
bufchain_add(&stderr_data, data, len);
return try_output(TRUE);
} else {
assert(outgoingeof == EOF_NO);
bufchain_add(&stdout_data, data, len);
return try_output(FALSE);
}
}
int from_backend_untrusted(void *frontend_handle, const char *data, int len)
{
/*
* No "untrusted" output should get here (the way the code is
* currently, it's all diverted by FLAG_STDERR).
*/
assert(!"Unexpected call to from_backend_untrusted()");
return 0; /* not reached */
}
int from_backend_eof(void *frontend_handle)
{
assert(outgoingeof == EOF_NO);
outgoingeof = EOF_PENDING;
try_output(FALSE);
return FALSE; /* do not respond to incoming EOF with outgoing */
}
int get_userpass_input(prompts_t *p, const unsigned char *in, int inlen)
{
int ret;
ret = cmdline_get_passwd_input(p, in, inlen);
if (ret == -1)
ret = console_get_userpass_input(p, in, inlen);
return ret;
}
/*
* Handle data from a local tty in PARMRK format.
*/
static void from_tty(void *vbuf, unsigned len)
{
char *p, *q, *end, *buf = vbuf;
static enum {NORMAL, FF, FF00} state = NORMAL;
p = buf; end = buf + len;
while (p < end) {
switch (state) {
case NORMAL:
if (*p == '\xff') {
p++;
state = FF;
} else {
q = memchr(p, '\xff', end - p);
if (q == NULL) q = end;
back->send(backhandle, p, q - p);
p = q;
}
break;
case FF:
if (*p == '\xff') {
back->send(backhandle, p, 1);
p++;
state = NORMAL;
} else if (*p == '\0') {
p++;
state = FF00;
} else abort();
break;
case FF00:
if (*p == '\0') {
back->special(backhandle, TS_BRK);
} else {
/*
* Pretend that PARMRK wasn't set. This involves
* faking what INPCK and IGNPAR would have done if
* we hadn't overridden them. Unfortunately, we
* can't do this entirely correctly because INPCK
* distinguishes between framing and parity
* errors, but PARMRK format represents both in
* the same way. We assume that parity errors are
* more common than framing errors, and hence
* treat all input errors as being subject to
* INPCK.
*/
if (orig_termios.c_iflag & INPCK) {
/* If IGNPAR is set, we throw away the character. */
if (!(orig_termios.c_iflag & IGNPAR)) {
/* PE/FE get passed on as NUL. */
*p = 0;
back->send(backhandle, p, 1);
}
} else {
/* INPCK not set. Assume we got a parity error. */
back->send(backhandle, p, 1);
}
}
p++;
state = NORMAL;
}
}
}
int signalpipe[2];
void sigwinch(int signum)
{
if (write(signalpipe[1], "x", 1) <= 0)
/* not much we can do about it */;
}
/*
* In Plink our selects are synchronous, so these functions are
* empty stubs.
*/
uxsel_id *uxsel_input_add(int fd, int rwx) { return NULL; }
void uxsel_input_remove(uxsel_id *id) { }
/*
* Short description of parameters.
*/
static void usage(void)
{
printf("Plink: command-line connection utility\n");
printf("%s\n", ver);
printf("Usage: plink [options] [user@]host [command]\n");
printf(" (\"host\" can also be a PuTTY saved session name)\n");
printf("Options:\n");
printf(" -V print version information and exit\n");
printf(" -pgpfp print PGP key fingerprints and exit\n");
printf(" -v show verbose messages\n");
printf(" -load sessname Load settings from saved session\n");
printf(" -ssh -telnet -rlogin -raw -serial\n");
printf(" force use of a particular protocol\n");
printf(" -P port connect to specified port\n");
printf(" -l user connect with specified username\n");
printf(" -batch disable all interactive prompts\n");
printf(" -proxycmd command\n");
printf(" use 'command' as local proxy\n");
printf(" -sercfg configuration-string (e.g. 19200,8,n,1,X)\n");
printf(" Specify the serial configuration (serial only)\n");
printf("The following options only apply to SSH connections:\n");
printf(" -pw passw login with specified password\n");
printf(" -D [listen-IP:]listen-port\n");
printf(" Dynamic SOCKS-based port forwarding\n");
printf(" -L [listen-IP:]listen-port:host:port\n");
printf(" Forward local port to remote address\n");
printf(" -R [listen-IP:]listen-port:host:port\n");
printf(" Forward remote port to local address\n");
printf(" -X -x enable / disable X11 forwarding\n");
printf(" -A -a enable / disable agent forwarding\n");
printf(" -t -T enable / disable pty allocation\n");
printf(" -1 -2 force use of particular protocol version\n");
printf(" -4 -6 force use of IPv4 or IPv6\n");
printf(" -C enable compression\n");
printf(" -i key private key file for user authentication\n");
printf(" -noagent disable use of Pageant\n");
printf(" -agent enable use of Pageant\n");
printf(" -hostkey aa:bb:cc:...\n");
printf(" manually specify a host key (may be repeated)\n");
printf(" -m file read remote command(s) from file\n");
printf(" -s remote command is an SSH subsystem (SSH-2 only)\n");
printf(" -N don't start a shell/command (SSH-2 only)\n");
printf(" -nc host:port\n");
printf(" open tunnel in place of session (SSH-2 only)\n");
printf(" -sshlog file\n");
printf(" -sshrawlog file\n");
printf(" log protocol details to a file\n");
printf(" -shareexists\n");
printf(" test whether a connection-sharing upstream exists\n");
exit(1);
}
static void version(void)
{
char *buildinfo_text = buildinfo("\n");
printf("plink: %s\n%s\n", ver, buildinfo_text);
sfree(buildinfo_text);
exit(0);
}
void frontend_net_error_pending(void) {}
const int share_can_be_downstream = TRUE;
const int share_can_be_upstream = TRUE;
const int buildinfo_gtk_relevant = FALSE;
int main(int argc, char **argv)
{
int sending;
int portnumber = -1;
int *fdlist;
int fd;
int i, fdcount, fdsize, fdstate;
int exitcode;
int errors;
int use_subsystem = 0;
int got_host = FALSE;
int just_test_share_exists = FALSE;
unsigned long now;
struct winsize size;
fdlist = NULL;
fdcount = fdsize = 0;
/*
* Initialise port and protocol to sensible defaults. (These
* will be overridden by more or less anything.)
*/
default_protocol = PROT_SSH;
default_port = 22;
bufchain_init(&stdout_data);
bufchain_init(&stderr_data);
outgoingeof = EOF_NO;
flags = FLAG_STDERR | FLAG_STDERR_TTY;
stderr_tty_init();
/*
* Process the command line.
*/
conf = conf_new();
do_defaults(NULL, conf);
loaded_session = FALSE;
default_protocol = conf_get_int(conf, CONF_protocol);
default_port = conf_get_int(conf, CONF_port);
errors = 0;
{
/*
* Override the default protocol if PLINK_PROTOCOL is set.
*/
char *p = getenv("PLINK_PROTOCOL");
if (p) {
const Backend *b = backend_from_name(p);
if (b) {
default_protocol = b->protocol;
default_port = b->default_port;
conf_set_int(conf, CONF_protocol, default_protocol);
conf_set_int(conf, CONF_port, default_port);
}
}
}
while (--argc) {
char *p = *++argv;
if (*p == '-') {
int ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
1, conf);
if (ret == -2) {
fprintf(stderr,
"plink: option \"%s\" requires an argument\n", p);
errors = 1;
} else if (ret == 2) {
--argc, ++argv;
} else if (ret == 1) {
continue;
} else if (!strcmp(p, "-batch")) {
console_batch_mode = 1;
} else if (!strcmp(p, "-s")) {
/* Save status to write to conf later. */
use_subsystem = 1;
} else if (!strcmp(p, "-V") || !strcmp(p, "--version")) {
version();
} else if (!strcmp(p, "--help")) {
usage();
exit(0);
} else if (!strcmp(p, "-pgpfp")) {
pgp_fingerprints();
exit(1);
} else if (!strcmp(p, "-o")) {
if (argc <= 1) {
fprintf(stderr,
"plink: option \"-o\" requires an argument\n");
errors = 1;
} else {
--argc;
provide_xrm_string(*++argv);
}
} else if (!strcmp(p, "-shareexists")) {
just_test_share_exists = TRUE;
} else if (!strcmp(p, "-fuzznet")) {
conf_set_int(conf, CONF_proxy_type, PROXY_FUZZ);
conf_set_str(conf, CONF_proxy_telnet_command,
"%host");
} else {
fprintf(stderr, "plink: unknown option \"%s\"\n", p);
errors = 1;
}
} else if (*p) {
if (!conf_launchable(conf) || !(got_host || loaded_session)) {
char *q = p;
/*
* If the hostname starts with "telnet:", set the
* protocol to Telnet and process the string as a
* Telnet URL.
*/
if (!strncmp(q, "telnet:", 7)) {
char c;
q += 7;
if (q[0] == '/' && q[1] == '/')
q += 2;
conf_set_int(conf, CONF_protocol, PROT_TELNET);
p = q;
p += host_strcspn(p, ":/");
c = *p;
if (*p)
*p++ = '\0';
if (c == ':')
conf_set_int(conf, CONF_port, atoi(p));
else
conf_set_int(conf, CONF_port, -1);
conf_set_str(conf, CONF_host, q);
got_host = TRUE;
} else {
char *r, *user, *host;
/*
* Before we process the [user@]host string, we
* first check for the presence of a protocol
* prefix (a protocol name followed by ",").
*/
r = strchr(p, ',');
if (r) {
const Backend *b;
*r = '\0';
b = backend_from_name(p);
if (b) {
default_protocol = b->protocol;
conf_set_int(conf, CONF_protocol,
default_protocol);
portnumber = b->default_port;
}
p = r + 1;
}
/*
* A nonzero length string followed by an @ is treated
* as a username. (We discount an _initial_ @.) The
* rest of the string (or the whole string if no @)
* is treated as a session name and/or hostname.
*/
r = strrchr(p, '@');
if (r == p)
p++, r = NULL; /* discount initial @ */
if (r) {
*r++ = '\0';
user = p, host = r;
} else {
user = NULL, host = p;
}
/*
* Now attempt to load a saved session with the
* same name as the hostname.
*/
{
Conf *conf2 = conf_new();
do_defaults(host, conf2);
if (loaded_session || !conf_launchable(conf2)) {
/* No settings for this host; use defaults */
/* (or session was already loaded with -load) */
conf_set_str(conf, CONF_host, host);
conf_set_int(conf, CONF_port, default_port);
got_host = TRUE;
} else {
conf_copy_into(conf, conf2);
loaded_session = TRUE;
}
conf_free(conf2);
}
if (user) {
/* Patch in specified username. */
conf_set_str(conf, CONF_username, user);
}
}
} else {
char *command;
int cmdlen, cmdsize;
cmdlen = cmdsize = 0;
command = NULL;
while (argc) {
while (*p) {
if (cmdlen >= cmdsize) {
cmdsize = cmdlen + 512;
command = sresize(command, cmdsize, char);
}
command[cmdlen++]=*p++;
}
if (cmdlen >= cmdsize) {
cmdsize = cmdlen + 512;
command = sresize(command, cmdsize, char);
}
command[cmdlen++]=' '; /* always add trailing space */
if (--argc) p = *++argv;
}
if (cmdlen) command[--cmdlen]='\0';
/* change trailing blank to NUL */
conf_set_str(conf, CONF_remote_cmd, command);
conf_set_str(conf, CONF_remote_cmd2, "");
conf_set_int(conf, CONF_nopty, TRUE); /* command => no tty */
break; /* done with cmdline */
}
}
}
if (errors)
return 1;
if (!conf_launchable(conf) || !(got_host || loaded_session)) {
usage();
}
/*
* Muck about with the hostname in various ways.
*/
{
char *hostbuf = dupstr(conf_get_str(conf, CONF_host));
char *host = hostbuf;
char *p, *q;
/*
* Trim leading whitespace.
*/
host += strspn(host, " \t");
/*
* See if host is of the form user@host, and separate out
* the username if so.
*/
if (host[0] != '\0') {
char *atsign = strrchr(host, '@');
if (atsign) {
*atsign = '\0';
conf_set_str(conf, CONF_username, host);
host = atsign + 1;
}
}
/*
* Trim a colon suffix off the hostname if it's there. In
* order to protect unbracketed IPv6 address literals
* against this treatment, we do not do this if there's
* _more_ than one colon.
*/
{
char *c = host_strchr(host, ':');
if (c) {
char *d = host_strchr(c+1, ':');
if (!d)
*c = '\0';
}
}
/*
* Remove any remaining whitespace.
*/
p = hostbuf;
q = host;
while (*q) {
if (*q != ' ' && *q != '\t')
*p++ = *q;
q++;
}
*p = '\0';
conf_set_str(conf, CONF_host, hostbuf);
sfree(hostbuf);
}
/*
* Perform command-line overrides on session configuration.
*/
cmdline_run_saved(conf);
/*
* If we have no better ideas for the remote username, use the local
* one, as 'ssh' does.
*/
if (conf_get_str(conf, CONF_username)[0] == '\0') {
char *user = get_username();
if (user) {
conf_set_str(conf, CONF_username, user);
sfree(user);
}
}
/*
* Apply subsystem status.
*/
if (use_subsystem)
conf_set_int(conf, CONF_ssh_subsys, TRUE);
if (!*conf_get_str(conf, CONF_remote_cmd) &&
!*conf_get_str(conf, CONF_remote_cmd2) &&
!*conf_get_str(conf, CONF_ssh_nc_host))
flags |= FLAG_INTERACTIVE;
/*
* Select protocol. This is farmed out into a table in a
* separate file to enable an ssh-free variant.
*/
back = backend_from_proto(conf_get_int(conf, CONF_protocol));
if (back == NULL) {
fprintf(stderr,
"Internal fault: Unsupported protocol found\n");
return 1;
}
/*
* Select port.
*/
if (portnumber != -1)
conf_set_int(conf, CONF_port, portnumber);
/*
* Block SIGPIPE, so that we'll get EPIPE individually on
* particular network connections that go wrong.
*/
putty_signal(SIGPIPE, SIG_IGN);
/*
* Set up the pipe we'll use to tell us about SIGWINCH.
*/
if (pipe(signalpipe) < 0) {
perror("pipe");
exit(1);
}
/* We don't want the signal handler to block if the pipe's full. */
nonblock(signalpipe[0]);
nonblock(signalpipe[1]);
cloexec(signalpipe[0]);
cloexec(signalpipe[1]);
putty_signal(SIGWINCH, sigwinch);
/*
* Now that we've got the SIGWINCH handler installed, try to find
* out the initial terminal size.
*/
if (ioctl(STDIN_FILENO, TIOCGWINSZ, &size) >= 0) {
conf_set_int(conf, CONF_width, size.ws_col);
conf_set_int(conf, CONF_height, size.ws_row);
}
sk_init();
uxsel_init();
/*
* Plink doesn't provide any way to add forwardings after the
* connection is set up, so if there are none now, we can safely set
* the "simple" flag.
*/
if (conf_get_int(conf, CONF_protocol) == PROT_SSH &&
!conf_get_int(conf, CONF_x11_forward) &&
!conf_get_int(conf, CONF_agentfwd) &&
!conf_get_str_nthstrkey(conf, CONF_portfwd, 0))
conf_set_int(conf, CONF_ssh_simple, TRUE);
if (just_test_share_exists) {
if (!back->test_for_upstream) {
fprintf(stderr, "Connection sharing not supported for connection "
"type '%s'\n", back->name);
return 1;
}
if (back->test_for_upstream(conf_get_str(conf, CONF_host),
conf_get_int(conf, CONF_port), conf))
return 0;
else
return 1;
}
/*
* Start up the connection.
*/
logctx = log_init(NULL, conf);
console_provide_logctx(logctx);
{
const char *error;
char *realhost;
/* nodelay is only useful if stdin is a terminal device */
int nodelay = conf_get_int(conf, CONF_tcp_nodelay) && isatty(0);
/* This is a good place for a fuzzer to fork us. */
#ifdef __AFL_HAVE_MANUAL_CONTROL
__AFL_INIT();
#endif
error = back->init(NULL, &backhandle, conf,
conf_get_str(conf, CONF_host),
conf_get_int(conf, CONF_port),
&realhost, nodelay,
conf_get_int(conf, CONF_tcp_keepalives));
if (error) {
fprintf(stderr, "Unable to open connection:\n%s\n", error);
return 1;
}
back->provide_logctx(backhandle, logctx);
ldisc_create(conf, NULL, back, backhandle, NULL);
sfree(realhost);
}
/*
* Set up the initial console mode. We don't care if this call
* fails, because we know we aren't necessarily running in a
* console.
*/
local_tty = (tcgetattr(STDIN_FILENO, &orig_termios) == 0);
atexit(cleanup_termios);
frontend_echoedit_update(NULL, 1, 1);
sending = FALSE;
now = GETTICKCOUNT();
while (1) {
fd_set rset, wset, xset;
int maxfd;
int rwx;
int ret;
unsigned long next;
FD_ZERO(&rset);
FD_ZERO(&wset);
FD_ZERO(&xset);
maxfd = 0;
FD_SET_MAX(signalpipe[0], maxfd, rset);
if (!sending &&
back->connected(backhandle) &&
back->sendok(backhandle) &&
back->sendbuffer(backhandle) < MAX_STDIN_BACKLOG) {
/* If we're OK to send, then try to read from stdin. */
FD_SET_MAX(STDIN_FILENO, maxfd, rset);
}
if (bufchain_size(&stdout_data) > 0) {
/* If we have data for stdout, try to write to stdout. */
FD_SET_MAX(STDOUT_FILENO, maxfd, wset);
}
if (bufchain_size(&stderr_data) > 0) {
/* If we have data for stderr, try to write to stderr. */
FD_SET_MAX(STDERR_FILENO, maxfd, wset);
}
/* Count the currently active fds. */
i = 0;
for (fd = first_fd(&fdstate, &rwx); fd >= 0;
fd = next_fd(&fdstate, &rwx)) i++;
/* Expand the fdlist buffer if necessary. */
if (i > fdsize) {
fdsize = i + 16;
fdlist = sresize(fdlist, fdsize, int);
}
/*
* Add all currently open fds to the select sets, and store
* them in fdlist as well.
*/
fdcount = 0;
for (fd = first_fd(&fdstate, &rwx); fd >= 0;
fd = next_fd(&fdstate, &rwx)) {
fdlist[fdcount++] = fd;
if (rwx & 1)
FD_SET_MAX(fd, maxfd, rset);
if (rwx & 2)
FD_SET_MAX(fd, maxfd, wset);
if (rwx & 4)
FD_SET_MAX(fd, maxfd, xset);
}
if (toplevel_callback_pending()) {
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 0;
ret = select(maxfd, &rset, &wset, &xset, &tv);
} else if (run_timers(now, &next)) {
do {
unsigned long then;
long ticks;
struct timeval tv;
then = now;
now = GETTICKCOUNT();
if (now - then > next - then)
ticks = 0;
else
ticks = next - now;
tv.tv_sec = ticks / 1000;
tv.tv_usec = ticks % 1000 * 1000;
ret = select(maxfd, &rset, &wset, &xset, &tv);
if (ret == 0)
now = next;
else
now = GETTICKCOUNT();
} while (ret < 0 && errno == EINTR);
} else {
ret = select(maxfd, &rset, &wset, &xset, NULL);
}
if (ret < 0 && errno == EINTR)
continue;
if (ret < 0) {
perror("select");
exit(1);
}
for (i = 0; i < fdcount; i++) {
fd = fdlist[i];
/*
* We must process exceptional notifications before
* ordinary readability ones, or we may go straight
* past the urgent marker.
*/
if (FD_ISSET(fd, &xset))
select_result(fd, 4);
if (FD_ISSET(fd, &rset))
select_result(fd, 1);
if (FD_ISSET(fd, &wset))
select_result(fd, 2);
}
if (FD_ISSET(signalpipe[0], &rset)) {
char c[1];
struct winsize size;
if (read(signalpipe[0], c, 1) <= 0)
/* ignore error */;
/* ignore its value; it'll be `x' */
if (ioctl(STDIN_FILENO, TIOCGWINSZ, (void *)&size) >= 0)
back->size(backhandle, size.ws_col, size.ws_row);
}
if (FD_ISSET(STDIN_FILENO, &rset)) {
char buf[4096];
int ret;
if (back->connected(backhandle)) {
ret = read(STDIN_FILENO, buf, sizeof(buf));
if (ret < 0) {
perror("stdin: read");
exit(1);
} else if (ret == 0) {
back->special(backhandle, TS_EOF);
sending = FALSE; /* send nothing further after this */
} else {
if (local_tty)
from_tty(buf, ret);
else
back->send(backhandle, buf, ret);
}
}
}
if (FD_ISSET(STDOUT_FILENO, &wset)) {
back->unthrottle(backhandle, try_output(FALSE));
}
if (FD_ISSET(STDERR_FILENO, &wset)) {
back->unthrottle(backhandle, try_output(TRUE));
}
run_toplevel_callbacks();
if (!back->connected(backhandle) &&
bufchain_size(&stdout_data) == 0 &&
bufchain_size(&stderr_data) == 0)
break; /* we closed the connection */
}
exitcode = back->exitcode(backhandle);
if (exitcode < 0) {
fprintf(stderr, "Remote process exit code unavailable\n");
exitcode = 1; /* this is an error condition */
}
cleanup_exit(exitcode);
return exitcode; /* shouldn't happen, but placates gcc */
}
|
446382.c | /*
* Unit tests for security functions
*
* Copyright (c) 2004 Mike McCormack
* Copyright (c) 2011 Dmitry Timoshkov
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include <stdarg.h>
#include <stdio.h>
#include "ntstatus.h"
#define WIN32_NO_STATUS
#include "windef.h"
#include "winbase.h"
#include "winerror.h"
#include "winternl.h"
#include "aclapi.h"
#include "winnt.h"
#include "sddl.h"
#include "ntsecapi.h"
#include "lmcons.h"
#include "wine/test.h"
#ifndef PROCESS_QUERY_LIMITED_INFORMATION
#define PROCESS_QUERY_LIMITED_INFORMATION 0x1000
#endif
/* PROCESS_ALL_ACCESS in Vista+ PSDKs is incompatible with older Windows versions */
#define PROCESS_ALL_ACCESS_NT4 (PROCESS_ALL_ACCESS & ~0xf000)
#define PROCESS_ALL_ACCESS_VISTA (PROCESS_ALL_ACCESS | 0xf000)
#ifndef EVENT_QUERY_STATE
#define EVENT_QUERY_STATE 0x0001
#endif
#ifndef SEMAPHORE_QUERY_STATE
#define SEMAPHORE_QUERY_STATE 0x0001
#endif
#ifndef THREAD_SET_LIMITED_INFORMATION
#define THREAD_SET_LIMITED_INFORMATION 0x0400
#define THREAD_QUERY_LIMITED_INFORMATION 0x0800
#endif
#define THREAD_ALL_ACCESS_NT4 (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x3ff)
#define THREAD_ALL_ACCESS_VISTA (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0xffff)
#define expect_eq(expr, value, type, format) { type ret_ = expr; ok((value) == ret_, #expr " expected " format " got " format "\n", (value), (ret_)); }
static BOOL (WINAPI *pAddAccessAllowedAceEx)(PACL, DWORD, DWORD, DWORD, PSID);
static BOOL (WINAPI *pAddAccessDeniedAceEx)(PACL, DWORD, DWORD, DWORD, PSID);
static BOOL (WINAPI *pAddAuditAccessAceEx)(PACL, DWORD, DWORD, DWORD, PSID, BOOL, BOOL);
static BOOL (WINAPI *pAddMandatoryAce)(PACL,DWORD,DWORD,DWORD,PSID);
static VOID (WINAPI *pBuildTrusteeWithSidA)( PTRUSTEEA pTrustee, PSID pSid );
static VOID (WINAPI *pBuildTrusteeWithNameA)( PTRUSTEEA pTrustee, LPSTR pName );
static VOID (WINAPI *pBuildTrusteeWithObjectsAndNameA)( PTRUSTEEA pTrustee,
POBJECTS_AND_NAME_A pObjName,
SE_OBJECT_TYPE ObjectType,
LPSTR ObjectTypeName,
LPSTR InheritedObjectTypeName,
LPSTR Name );
static VOID (WINAPI *pBuildTrusteeWithObjectsAndSidA)( PTRUSTEEA pTrustee,
POBJECTS_AND_SID pObjSid,
GUID* pObjectGuid,
GUID* pInheritedObjectGuid,
PSID pSid );
static LPSTR (WINAPI *pGetTrusteeNameA)( PTRUSTEEA pTrustee );
static BOOL (WINAPI *pMakeSelfRelativeSD)( PSECURITY_DESCRIPTOR, PSECURITY_DESCRIPTOR, LPDWORD );
static BOOL (WINAPI *pConvertStringSidToSidA)( LPCSTR str, PSID pSid );
static BOOL (WINAPI *pCheckTokenMembership)(HANDLE, PSID, PBOOL);
static BOOL (WINAPI *pConvertStringSecurityDescriptorToSecurityDescriptorA)(LPCSTR, DWORD,
PSECURITY_DESCRIPTOR*, PULONG );
static BOOL (WINAPI *pConvertStringSecurityDescriptorToSecurityDescriptorW)(LPCWSTR, DWORD,
PSECURITY_DESCRIPTOR*, PULONG );
static BOOL (WINAPI *pConvertSecurityDescriptorToStringSecurityDescriptorA)(PSECURITY_DESCRIPTOR, DWORD,
SECURITY_INFORMATION, LPSTR *, PULONG );
static BOOL (WINAPI *pGetFileSecurityA)(LPCSTR, SECURITY_INFORMATION,
PSECURITY_DESCRIPTOR, DWORD, LPDWORD);
static BOOL (WINAPI *pSetFileSecurityA)(LPCSTR, SECURITY_INFORMATION,
PSECURITY_DESCRIPTOR);
static DWORD (WINAPI *pGetNamedSecurityInfoA)(LPSTR, SE_OBJECT_TYPE, SECURITY_INFORMATION,
PSID*, PSID*, PACL*, PACL*,
PSECURITY_DESCRIPTOR*);
static DWORD (WINAPI *pSetNamedSecurityInfoA)(LPSTR, SE_OBJECT_TYPE, SECURITY_INFORMATION,
PSID, PSID, PACL, PACL);
static PDWORD (WINAPI *pGetSidSubAuthority)(PSID, DWORD);
static PUCHAR (WINAPI *pGetSidSubAuthorityCount)(PSID);
static BOOL (WINAPI *pIsValidSid)(PSID);
static DWORD (WINAPI *pRtlAdjustPrivilege)(ULONG,BOOLEAN,BOOLEAN,PBOOLEAN);
static BOOL (WINAPI *pCreateWellKnownSid)(WELL_KNOWN_SID_TYPE,PSID,PSID,DWORD*);
static BOOL (WINAPI *pDuplicateTokenEx)(HANDLE,DWORD,LPSECURITY_ATTRIBUTES,
SECURITY_IMPERSONATION_LEVEL,TOKEN_TYPE,PHANDLE);
static NTSTATUS (WINAPI *pLsaQueryInformationPolicy)(LSA_HANDLE,POLICY_INFORMATION_CLASS,PVOID*);
static NTSTATUS (WINAPI *pLsaClose)(LSA_HANDLE);
static NTSTATUS (WINAPI *pLsaFreeMemory)(PVOID);
static NTSTATUS (WINAPI *pLsaOpenPolicy)(PLSA_UNICODE_STRING,PLSA_OBJECT_ATTRIBUTES,ACCESS_MASK,PLSA_HANDLE);
static NTSTATUS (WINAPI *pNtQueryObject)(HANDLE,OBJECT_INFORMATION_CLASS,PVOID,ULONG,PULONG);
static DWORD (WINAPI *pSetEntriesInAclW)(ULONG, PEXPLICIT_ACCESSW, PACL, PACL*);
static DWORD (WINAPI *pSetEntriesInAclA)(ULONG, PEXPLICIT_ACCESSA, PACL, PACL*);
static BOOL (WINAPI *pSetSecurityDescriptorControl)(PSECURITY_DESCRIPTOR, SECURITY_DESCRIPTOR_CONTROL,
SECURITY_DESCRIPTOR_CONTROL);
static DWORD (WINAPI *pGetSecurityInfo)(HANDLE, SE_OBJECT_TYPE, SECURITY_INFORMATION,
PSID*, PSID*, PACL*, PACL*, PSECURITY_DESCRIPTOR*);
static DWORD (WINAPI *pSetSecurityInfo)(HANDLE, SE_OBJECT_TYPE, SECURITY_INFORMATION,
PSID, PSID, PACL, PACL);
static NTSTATUS (WINAPI *pNtAccessCheck)(PSECURITY_DESCRIPTOR, HANDLE, ACCESS_MASK, PGENERIC_MAPPING,
PPRIVILEGE_SET, PULONG, PULONG, NTSTATUS*);
static BOOL (WINAPI *pCreateRestrictedToken)(HANDLE, DWORD, DWORD, PSID_AND_ATTRIBUTES, DWORD,
PLUID_AND_ATTRIBUTES, DWORD, PSID_AND_ATTRIBUTES, PHANDLE);
static BOOL (WINAPI *pGetAclInformation)(PACL,LPVOID,DWORD,ACL_INFORMATION_CLASS);
static BOOL (WINAPI *pGetAce)(PACL,DWORD,LPVOID*);
static NTSTATUS (WINAPI *pNtSetSecurityObject)(HANDLE,SECURITY_INFORMATION,PSECURITY_DESCRIPTOR);
static NTSTATUS (WINAPI *pNtCreateFile)(PHANDLE,ACCESS_MASK,POBJECT_ATTRIBUTES,PIO_STATUS_BLOCK,PLARGE_INTEGER,ULONG,ULONG,ULONG,ULONG,PVOID,ULONG);
static BOOL (WINAPI *pRtlDosPathNameToNtPathName_U)(LPCWSTR,PUNICODE_STRING,PWSTR*,CURDIR*);
static NTSTATUS (WINAPI *pRtlAnsiStringToUnicodeString)(PUNICODE_STRING,PCANSI_STRING,BOOLEAN);
static BOOL (WINAPI *pGetWindowsAccountDomainSid)(PSID,PSID,DWORD*);
static void (WINAPI *pRtlInitAnsiString)(PANSI_STRING,PCSZ);
static NTSTATUS (WINAPI *pRtlFreeUnicodeString)(PUNICODE_STRING);
static PSID_IDENTIFIER_AUTHORITY (WINAPI *pGetSidIdentifierAuthority)(PSID);
static DWORD (WINAPI *pGetExplicitEntriesFromAclW)(PACL,PULONG,PEXPLICIT_ACCESSW*);
static HMODULE hmod;
static int myARGC;
static char** myARGV;
#define SID_SLOTS 4
static char debugsid_str[SID_SLOTS][256];
static int debugsid_index = 0;
static const char* debugstr_sid(PSID sid)
{
LPSTR sidstr;
DWORD le = GetLastError();
char* res = debugsid_str[debugsid_index];
debugsid_index = (debugsid_index + 1) % SID_SLOTS;
if (!ConvertSidToStringSidA(sid, &sidstr))
sprintf(res, "ConvertSidToStringSidA failed le=%u", GetLastError());
else if (strlen(sidstr) > sizeof(*debugsid_str) - 1)
{
memcpy(res, sidstr, sizeof(*debugsid_str) - 4);
strcpy(res + sizeof(*debugsid_str) - 4, "...");
LocalFree(sidstr);
}
else
{
strcpy(res, sidstr);
LocalFree(sidstr);
}
/* Restore the last error in case ConvertSidToStringSidA() modified it */
SetLastError(le);
return res;
}
struct sidRef
{
SID_IDENTIFIER_AUTHORITY auth;
const char *refStr;
};
static void init(void)
{
HMODULE hntdll;
hntdll = GetModuleHandleA("ntdll.dll");
pNtQueryObject = (void *)GetProcAddress( hntdll, "NtQueryObject" );
pNtAccessCheck = (void *)GetProcAddress( hntdll, "NtAccessCheck" );
pNtSetSecurityObject = (void *)GetProcAddress(hntdll, "NtSetSecurityObject");
pNtCreateFile = (void *)GetProcAddress(hntdll, "NtCreateFile");
pRtlDosPathNameToNtPathName_U = (void *)GetProcAddress(hntdll, "RtlDosPathNameToNtPathName_U");
pRtlAnsiStringToUnicodeString = (void *)GetProcAddress(hntdll, "RtlAnsiStringToUnicodeString");
pRtlInitAnsiString = (void *)GetProcAddress(hntdll, "RtlInitAnsiString");
pRtlFreeUnicodeString = (void *)GetProcAddress(hntdll, "RtlFreeUnicodeString");
hmod = GetModuleHandleA("advapi32.dll");
pAddAccessAllowedAceEx = (void *)GetProcAddress(hmod, "AddAccessAllowedAceEx");
pAddAccessDeniedAceEx = (void *)GetProcAddress(hmod, "AddAccessDeniedAceEx");
pAddAuditAccessAceEx = (void *)GetProcAddress(hmod, "AddAuditAccessAceEx");
pAddMandatoryAce = (void *)GetProcAddress(hmod, "AddMandatoryAce");
pCheckTokenMembership = (void *)GetProcAddress(hmod, "CheckTokenMembership");
pConvertStringSecurityDescriptorToSecurityDescriptorA =
(void *)GetProcAddress(hmod, "ConvertStringSecurityDescriptorToSecurityDescriptorA" );
pConvertStringSecurityDescriptorToSecurityDescriptorW =
(void *)GetProcAddress(hmod, "ConvertStringSecurityDescriptorToSecurityDescriptorW" );
pConvertSecurityDescriptorToStringSecurityDescriptorA =
(void *)GetProcAddress(hmod, "ConvertSecurityDescriptorToStringSecurityDescriptorA" );
pGetFileSecurityA = (void *)GetProcAddress(hmod, "GetFileSecurityA" );
pSetFileSecurityA = (void *)GetProcAddress(hmod, "SetFileSecurityA" );
pCreateWellKnownSid = (void *)GetProcAddress( hmod, "CreateWellKnownSid" );
pGetNamedSecurityInfoA = (void *)GetProcAddress(hmod, "GetNamedSecurityInfoA");
pSetNamedSecurityInfoA = (void *)GetProcAddress(hmod, "SetNamedSecurityInfoA");
pGetSidSubAuthority = (void *)GetProcAddress(hmod, "GetSidSubAuthority");
pGetSidSubAuthorityCount = (void *)GetProcAddress(hmod, "GetSidSubAuthorityCount");
pIsValidSid = (void *)GetProcAddress(hmod, "IsValidSid");
pMakeSelfRelativeSD = (void *)GetProcAddress(hmod, "MakeSelfRelativeSD");
pSetEntriesInAclW = (void *)GetProcAddress(hmod, "SetEntriesInAclW");
pSetEntriesInAclA = (void *)GetProcAddress(hmod, "SetEntriesInAclA");
pSetSecurityDescriptorControl = (void *)GetProcAddress(hmod, "SetSecurityDescriptorControl");
pGetSecurityInfo = (void *)GetProcAddress(hmod, "GetSecurityInfo");
pSetSecurityInfo = (void *)GetProcAddress(hmod, "SetSecurityInfo");
pCreateRestrictedToken = (void *)GetProcAddress(hmod, "CreateRestrictedToken");
pConvertStringSidToSidA = (void *)GetProcAddress(hmod, "ConvertStringSidToSidA");
pGetAclInformation = (void *)GetProcAddress(hmod, "GetAclInformation");
pGetAce = (void *)GetProcAddress(hmod, "GetAce");
pGetWindowsAccountDomainSid = (void *)GetProcAddress(hmod, "GetWindowsAccountDomainSid");
pGetSidIdentifierAuthority = (void *)GetProcAddress(hmod, "GetSidIdentifierAuthority");
pDuplicateTokenEx = (void *)GetProcAddress(hmod, "DuplicateTokenEx");
pGetExplicitEntriesFromAclW = (void *)GetProcAddress(hmod, "GetExplicitEntriesFromAclW");
myARGC = winetest_get_mainargs( &myARGV );
}
static SECURITY_DESCRIPTOR* test_get_security_descriptor(HANDLE handle, int line)
{
/* use HeapFree(GetProcessHeap(), 0, sd); when done */
DWORD ret, length, needed;
SECURITY_DESCRIPTOR *sd;
needed = 0xdeadbeef;
SetLastError(0xdeadbeef);
ret = GetKernelObjectSecurity(handle, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
NULL, 0, &needed);
ok_(__FILE__, line)(!ret, "GetKernelObjectSecurity should fail\n");
ok_(__FILE__, line)(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
ok_(__FILE__, line)(needed != 0xdeadbeef, "GetKernelObjectSecurity should return required buffer length\n");
length = needed;
sd = HeapAlloc(GetProcessHeap(), 0, length);
needed = 0xdeadbeef;
SetLastError(0xdeadbeef);
ret = GetKernelObjectSecurity(handle, OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
sd, length, &needed);
ok_(__FILE__, line)(ret, "GetKernelObjectSecurity error %d\n", GetLastError());
ok_(__FILE__, line)(needed == length || needed == 0 /* file, pipe */, "GetKernelObjectSecurity should return %u instead of %u\n", length, needed);
return sd;
}
static void test_owner_equal(HANDLE Handle, PSID expected, int line)
{
BOOL res;
SECURITY_DESCRIPTOR *queriedSD = NULL;
PSID owner;
BOOL owner_defaulted;
queriedSD = test_get_security_descriptor( Handle, line );
res = GetSecurityDescriptorOwner(queriedSD, &owner, &owner_defaulted);
ok_(__FILE__, line)(res, "GetSecurityDescriptorOwner failed with error %d\n", GetLastError());
ok_(__FILE__, line)(EqualSid(owner, expected), "Owner SIDs are not equal %s != %s\n",
debugstr_sid(owner), debugstr_sid(expected));
ok_(__FILE__, line)(!owner_defaulted, "Defaulted is true\n");
HeapFree(GetProcessHeap(), 0, queriedSD);
}
static void test_group_equal(HANDLE Handle, PSID expected, int line)
{
BOOL res;
SECURITY_DESCRIPTOR *queriedSD = NULL;
PSID group;
BOOL group_defaulted;
queriedSD = test_get_security_descriptor( Handle, line );
res = GetSecurityDescriptorGroup(queriedSD, &group, &group_defaulted);
ok_(__FILE__, line)(res, "GetSecurityDescriptorGroup failed with error %d\n", GetLastError());
ok_(__FILE__, line)(EqualSid(group, expected), "Group SIDs are not equal %s != %s\n",
debugstr_sid(group), debugstr_sid(expected));
ok_(__FILE__, line)(!group_defaulted, "Defaulted is true\n");
HeapFree(GetProcessHeap(), 0, queriedSD);
}
static void test_sid(void)
{
struct sidRef refs[] = {
{ { {0x00,0x00,0x33,0x44,0x55,0x66} }, "S-1-860116326-1" },
{ { {0x00,0x00,0x01,0x02,0x03,0x04} }, "S-1-16909060-1" },
{ { {0x00,0x00,0x00,0x01,0x02,0x03} }, "S-1-66051-1" },
{ { {0x00,0x00,0x00,0x00,0x01,0x02} }, "S-1-258-1" },
{ { {0x00,0x00,0x00,0x00,0x00,0x02} }, "S-1-2-1" },
{ { {0x00,0x00,0x00,0x00,0x00,0x0c} }, "S-1-12-1" },
};
static const struct
{
const char *name;
const char *sid;
unsigned int optional;
}
str_to_sid_tests[] =
{
{ "WD", "S-1-1-0" },
{ "CO", "S-1-3-0" },
{ "CG", "S-1-3-1" },
{ "OW", "S-1-3-4", 1 }, /* Vista+ */
{ "NU", "S-1-5-2" },
{ "IU", "S-1-5-4" },
{ "SU", "S-1-5-6" },
{ "AN", "S-1-5-7" },
{ "ED", "S-1-5-9" },
{ "PS", "S-1-5-10" },
{ "AU", "S-1-5-11" },
{ "RC", "S-1-5-12" },
{ "SY", "S-1-5-18" },
{ "LS", "S-1-5-19" },
{ "NS", "S-1-5-20" },
{ "LA", "S-1-5-21-*-*-*-500" },
{ "LG", "S-1-5-21-*-*-*-501" },
{ "BO", "S-1-5-32-551" },
{ "BA", "S-1-5-32-544" },
{ "BU", "S-1-5-32-545" },
{ "BG", "S-1-5-32-546" },
{ "PU", "S-1-5-32-547" },
{ "AO", "S-1-5-32-548" },
{ "SO", "S-1-5-32-549" },
{ "PO", "S-1-5-32-550" },
{ "RE", "S-1-5-32-552" },
{ "RU", "S-1-5-32-554" },
{ "RD", "S-1-5-32-555" },
{ "NO", "S-1-5-32-556" },
{ "AC", "S-1-15-2-1", 1 }, /* Win8+ */
{ "CA", "", 1 },
{ "DA", "", 1 },
{ "DC", "", 1 },
{ "DD", "", 1 },
{ "DG", "", 1 },
{ "DU", "", 1 },
{ "EA", "", 1 },
{ "PA", "", 1 },
{ "RS", "", 1 },
{ "SA", "", 1 },
};
const char noSubAuthStr[] = "S-1-5";
unsigned int i;
PSID psid = NULL;
SID *pisid;
BOOL r, ret;
LPSTR str = NULL;
if( !pConvertStringSidToSidA )
{
win_skip("ConvertSidToStringSidA or ConvertStringSidToSidA not available\n");
return;
}
r = pConvertStringSidToSidA( NULL, NULL );
ok( !r, "expected failure with NULL parameters\n" );
if( GetLastError() == ERROR_CALL_NOT_IMPLEMENTED )
return;
ok( GetLastError() == ERROR_INVALID_PARAMETER,
"expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
GetLastError() );
r = pConvertStringSidToSidA( refs[0].refStr, NULL );
ok( !r && GetLastError() == ERROR_INVALID_PARAMETER,
"expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
GetLastError() );
r = pConvertStringSidToSidA( NULL, &str );
ok( !r && GetLastError() == ERROR_INVALID_PARAMETER,
"expected GetLastError() is ERROR_INVALID_PARAMETER, got %d\n",
GetLastError() );
r = pConvertStringSidToSidA( noSubAuthStr, &psid );
ok( !r,
"expected failure with no sub authorities\n" );
ok( GetLastError() == ERROR_INVALID_SID,
"expected GetLastError() is ERROR_INVALID_SID, got %d\n",
GetLastError() );
ok(pConvertStringSidToSidA("S-1-5-21-93476-23408-4576", &psid), "ConvertStringSidToSidA failed\n");
pisid = psid;
ok(pisid->SubAuthorityCount == 4, "Invalid sub authority count - expected 4, got %d\n", pisid->SubAuthorityCount);
ok(pisid->SubAuthority[0] == 21, "Invalid subauthority 0 - expected 21, got %d\n", pisid->SubAuthority[0]);
ok(pisid->SubAuthority[3] == 4576, "Invalid subauthority 0 - expected 4576, got %d\n", pisid->SubAuthority[3]);
LocalFree(str);
LocalFree(psid);
for( i = 0; i < ARRAY_SIZE(refs); i++ )
{
r = AllocateAndInitializeSid( &refs[i].auth, 1,1,0,0,0,0,0,0,0,
&psid );
ok( r, "failed to allocate sid\n" );
r = ConvertSidToStringSidA( psid, &str );
ok( r, "failed to convert sid\n" );
if (r)
{
ok( !strcmp( str, refs[i].refStr ),
"incorrect sid, expected %s, got %s\n", refs[i].refStr, str );
LocalFree( str );
}
if( psid )
FreeSid( psid );
r = pConvertStringSidToSidA( refs[i].refStr, &psid );
ok( r, "failed to parse sid string\n" );
pisid = psid;
ok( pisid &&
!memcmp( pisid->IdentifierAuthority.Value, refs[i].auth.Value,
sizeof(refs[i].auth) ),
"string sid %s didn't parse to expected value\n"
"(got 0x%04x%08x, expected 0x%04x%08x)\n",
refs[i].refStr,
MAKEWORD( pisid->IdentifierAuthority.Value[1],
pisid->IdentifierAuthority.Value[0] ),
MAKELONG( MAKEWORD( pisid->IdentifierAuthority.Value[5],
pisid->IdentifierAuthority.Value[4] ),
MAKEWORD( pisid->IdentifierAuthority.Value[3],
pisid->IdentifierAuthority.Value[2] ) ),
MAKEWORD( refs[i].auth.Value[1], refs[i].auth.Value[0] ),
MAKELONG( MAKEWORD( refs[i].auth.Value[5], refs[i].auth.Value[4] ),
MAKEWORD( refs[i].auth.Value[3], refs[i].auth.Value[2] ) ) );
if( psid )
LocalFree( psid );
}
for (i = 0; i < ARRAY_SIZE(str_to_sid_tests); i++)
{
char *str;
ret = ConvertStringSidToSidA(str_to_sid_tests[i].name, &psid);
if (!ret && str_to_sid_tests[i].optional)
{
skip("%u: failed to convert %s.\n", i, str_to_sid_tests[i].name);
continue;
}
ok(ret, "%u: failed to convert string to sid.\n", i);
if (str_to_sid_tests[i].optional || !strcmp(str_to_sid_tests[i].name, "LA") ||
!strcmp(str_to_sid_tests[i].name, "LG"))
{
LocalFree(psid);
continue;
}
ret = ConvertSidToStringSidA(psid, &str);
ok(ret, "%u: failed to convert SID to string.\n", i);
ok(!strcmp(str, str_to_sid_tests[i].sid), "%u: unexpected sid %s.\n", i, str);
LocalFree(psid);
LocalFree(str);
}
}
static void test_trustee(void)
{
GUID ObjectType = {0x12345678, 0x1234, 0x5678, {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}};
GUID InheritedObjectType = {0x23456789, 0x2345, 0x6786, {0x2, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99}};
GUID ZeroGuid;
OBJECTS_AND_NAME_A oan;
OBJECTS_AND_SID oas;
TRUSTEEA trustee;
PSID psid;
char szObjectTypeName[] = "ObjectTypeName";
char szInheritedObjectTypeName[] = "InheritedObjectTypeName";
char szTrusteeName[] = "szTrusteeName";
SID_IDENTIFIER_AUTHORITY auth = { {0x11,0x22,0,0,0, 0} };
memset( &ZeroGuid, 0x00, sizeof (ZeroGuid) );
pBuildTrusteeWithSidA = (void *)GetProcAddress( hmod, "BuildTrusteeWithSidA" );
pBuildTrusteeWithNameA = (void *)GetProcAddress( hmod, "BuildTrusteeWithNameA" );
pBuildTrusteeWithObjectsAndNameA = (void *)GetProcAddress (hmod, "BuildTrusteeWithObjectsAndNameA" );
pBuildTrusteeWithObjectsAndSidA = (void *)GetProcAddress (hmod, "BuildTrusteeWithObjectsAndSidA" );
pGetTrusteeNameA = (void *)GetProcAddress (hmod, "GetTrusteeNameA" );
if( !pBuildTrusteeWithSidA || !pBuildTrusteeWithNameA ||
!pBuildTrusteeWithObjectsAndNameA || !pBuildTrusteeWithObjectsAndSidA ||
!pGetTrusteeNameA )
return;
if ( ! AllocateAndInitializeSid( &auth, 1, 42, 0,0,0,0,0,0,0,&psid ) )
{
trace( "failed to init SID\n" );
return;
}
/* test BuildTrusteeWithSidA */
memset( &trustee, 0xff, sizeof trustee );
pBuildTrusteeWithSidA( &trustee, psid );
ok( trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
ok( trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE,
"MultipleTrusteeOperation wrong\n");
ok( trustee.TrusteeForm == TRUSTEE_IS_SID, "TrusteeForm wrong\n");
ok( trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
ok( trustee.ptstrName == psid, "ptstrName wrong\n" );
/* test BuildTrusteeWithObjectsAndSidA (test 1) */
memset( &trustee, 0xff, sizeof trustee );
memset( &oas, 0xff, sizeof(oas) );
pBuildTrusteeWithObjectsAndSidA(&trustee, &oas, &ObjectType,
&InheritedObjectType, psid);
ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_SID, "TrusteeForm wrong\n");
ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
ok(trustee.ptstrName == (LPSTR)&oas, "ptstrName wrong\n");
ok(oas.ObjectsPresent == (ACE_OBJECT_TYPE_PRESENT | ACE_INHERITED_OBJECT_TYPE_PRESENT), "ObjectsPresent wrong\n");
ok(!memcmp(&oas.ObjectTypeGuid, &ObjectType, sizeof(GUID)), "ObjectTypeGuid wrong\n");
ok(!memcmp(&oas.InheritedObjectTypeGuid, &InheritedObjectType, sizeof(GUID)), "InheritedObjectTypeGuid wrong\n");
ok(oas.pSid == psid, "pSid wrong\n");
/* test GetTrusteeNameA */
ok(pGetTrusteeNameA(&trustee) == (LPSTR)&oas, "GetTrusteeName returned wrong value\n");
/* test BuildTrusteeWithObjectsAndSidA (test 2) */
memset( &trustee, 0xff, sizeof trustee );
memset( &oas, 0xff, sizeof(oas) );
pBuildTrusteeWithObjectsAndSidA(&trustee, &oas, NULL,
&InheritedObjectType, psid);
ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_SID, "TrusteeForm wrong\n");
ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
ok(trustee.ptstrName == (LPSTR)&oas, "ptstrName wrong\n");
ok(oas.ObjectsPresent == ACE_INHERITED_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
ok(!memcmp(&oas.ObjectTypeGuid, &ZeroGuid, sizeof(GUID)), "ObjectTypeGuid wrong\n");
ok(!memcmp(&oas.InheritedObjectTypeGuid, &InheritedObjectType, sizeof(GUID)), "InheritedObjectTypeGuid wrong\n");
ok(oas.pSid == psid, "pSid wrong\n");
FreeSid( psid );
/* test BuildTrusteeWithNameA */
memset( &trustee, 0xff, sizeof trustee );
pBuildTrusteeWithNameA( &trustee, szTrusteeName );
ok( trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
ok( trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE,
"MultipleTrusteeOperation wrong\n");
ok( trustee.TrusteeForm == TRUSTEE_IS_NAME, "TrusteeForm wrong\n");
ok( trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
ok( trustee.ptstrName == szTrusteeName, "ptstrName wrong\n" );
/* test BuildTrusteeWithObjectsAndNameA (test 1) */
memset( &trustee, 0xff, sizeof trustee );
memset( &oan, 0xff, sizeof(oan) );
pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, szObjectTypeName,
szInheritedObjectTypeName, szTrusteeName);
ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
ok(trustee.ptstrName == (LPSTR)&oan, "ptstrName wrong\n");
ok(oan.ObjectsPresent == (ACE_OBJECT_TYPE_PRESENT | ACE_INHERITED_OBJECT_TYPE_PRESENT), "ObjectsPresent wrong\n");
ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
ok(oan.InheritedObjectTypeName == szInheritedObjectTypeName, "InheritedObjectTypeName wrong\n");
ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
/* test GetTrusteeNameA */
ok(pGetTrusteeNameA(&trustee) == (LPSTR)&oan, "GetTrusteeName returned wrong value\n");
/* test BuildTrusteeWithObjectsAndNameA (test 2) */
memset( &trustee, 0xff, sizeof trustee );
memset( &oan, 0xff, sizeof(oan) );
pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, NULL,
szInheritedObjectTypeName, szTrusteeName);
ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
ok(trustee.ptstrName == (LPSTR)&oan, "ptstrName wrong\n");
ok(oan.ObjectsPresent == ACE_INHERITED_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
ok(oan.InheritedObjectTypeName == szInheritedObjectTypeName, "InheritedObjectTypeName wrong\n");
ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
/* test BuildTrusteeWithObjectsAndNameA (test 3) */
memset( &trustee, 0xff, sizeof trustee );
memset( &oan, 0xff, sizeof(oan) );
pBuildTrusteeWithObjectsAndNameA(&trustee, &oan, SE_KERNEL_OBJECT, szObjectTypeName,
NULL, szTrusteeName);
ok(trustee.pMultipleTrustee == NULL, "pMultipleTrustee wrong\n");
ok(trustee.MultipleTrusteeOperation == NO_MULTIPLE_TRUSTEE, "MultipleTrusteeOperation wrong\n");
ok(trustee.TrusteeForm == TRUSTEE_IS_OBJECTS_AND_NAME, "TrusteeForm wrong\n");
ok(trustee.TrusteeType == TRUSTEE_IS_UNKNOWN, "TrusteeType wrong\n");
ok(trustee.ptstrName == (LPSTR)&oan, "ptstrName wrong\n");
ok(oan.ObjectsPresent == ACE_OBJECT_TYPE_PRESENT, "ObjectsPresent wrong\n");
ok(oan.ObjectType == SE_KERNEL_OBJECT, "ObjectType wrong\n");
ok(oan.InheritedObjectTypeName == NULL, "InheritedObjectTypeName wrong\n");
ok(oan.ptstrName == szTrusteeName, "szTrusteeName wrong\n");
}
/* If the first isn't defined, assume none is */
#ifndef SE_MIN_WELL_KNOWN_PRIVILEGE
#define SE_MIN_WELL_KNOWN_PRIVILEGE 2L
#define SE_CREATE_TOKEN_PRIVILEGE 2L
#define SE_ASSIGNPRIMARYTOKEN_PRIVILEGE 3L
#define SE_LOCK_MEMORY_PRIVILEGE 4L
#define SE_INCREASE_QUOTA_PRIVILEGE 5L
#define SE_MACHINE_ACCOUNT_PRIVILEGE 6L
#define SE_TCB_PRIVILEGE 7L
#define SE_SECURITY_PRIVILEGE 8L
#define SE_TAKE_OWNERSHIP_PRIVILEGE 9L
#define SE_LOAD_DRIVER_PRIVILEGE 10L
#define SE_SYSTEM_PROFILE_PRIVILEGE 11L
#define SE_SYSTEMTIME_PRIVILEGE 12L
#define SE_PROF_SINGLE_PROCESS_PRIVILEGE 13L
#define SE_INC_BASE_PRIORITY_PRIVILEGE 14L
#define SE_CREATE_PAGEFILE_PRIVILEGE 15L
#define SE_CREATE_PERMANENT_PRIVILEGE 16L
#define SE_BACKUP_PRIVILEGE 17L
#define SE_RESTORE_PRIVILEGE 18L
#define SE_SHUTDOWN_PRIVILEGE 19L
#define SE_DEBUG_PRIVILEGE 20L
#define SE_AUDIT_PRIVILEGE 21L
#define SE_SYSTEM_ENVIRONMENT_PRIVILEGE 22L
#define SE_CHANGE_NOTIFY_PRIVILEGE 23L
#define SE_REMOTE_SHUTDOWN_PRIVILEGE 24L
#define SE_UNDOCK_PRIVILEGE 25L
#define SE_SYNC_AGENT_PRIVILEGE 26L
#define SE_ENABLE_DELEGATION_PRIVILEGE 27L
#define SE_MANAGE_VOLUME_PRIVILEGE 28L
#define SE_IMPERSONATE_PRIVILEGE 29L
#define SE_CREATE_GLOBAL_PRIVILEGE 30L
#define SE_MAX_WELL_KNOWN_PRIVILEGE SE_CREATE_GLOBAL_PRIVILEGE
#endif /* ndef SE_MIN_WELL_KNOWN_PRIVILEGE */
static void test_allocateLuid(void)
{
BOOL (WINAPI *pAllocateLocallyUniqueId)(PLUID);
LUID luid1, luid2;
BOOL ret;
pAllocateLocallyUniqueId = (void*)GetProcAddress(hmod, "AllocateLocallyUniqueId");
if (!pAllocateLocallyUniqueId) return;
ret = pAllocateLocallyUniqueId(&luid1);
if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
return;
ok(ret,
"AllocateLocallyUniqueId failed: %d\n", GetLastError());
ret = pAllocateLocallyUniqueId(&luid2);
ok( ret,
"AllocateLocallyUniqueId failed: %d\n", GetLastError());
ok(luid1.LowPart > SE_MAX_WELL_KNOWN_PRIVILEGE || luid1.HighPart != 0,
"AllocateLocallyUniqueId returned a well-known LUID\n");
ok(luid1.LowPart != luid2.LowPart || luid1.HighPart != luid2.HighPart,
"AllocateLocallyUniqueId returned non-unique LUIDs\n");
ret = pAllocateLocallyUniqueId(NULL);
ok( !ret && GetLastError() == ERROR_NOACCESS,
"AllocateLocallyUniqueId(NULL) didn't return ERROR_NOACCESS: %d\n",
GetLastError());
}
static void test_lookupPrivilegeName(void)
{
BOOL (WINAPI *pLookupPrivilegeNameA)(LPCSTR, PLUID, LPSTR, LPDWORD);
char buf[MAX_PATH]; /* arbitrary, seems long enough */
DWORD cchName = sizeof(buf);
LUID luid = { 0, 0 };
LONG i;
BOOL ret;
/* check whether it's available first */
pLookupPrivilegeNameA = (void*)GetProcAddress(hmod, "LookupPrivilegeNameA");
if (!pLookupPrivilegeNameA) return;
luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
return;
/* check with a short buffer */
cchName = 0;
luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
ret = pLookupPrivilegeNameA(NULL, &luid, NULL, &cchName);
ok( !ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"LookupPrivilegeNameA didn't fail with ERROR_INSUFFICIENT_BUFFER: %d\n",
GetLastError());
ok(cchName == strlen("SeCreateTokenPrivilege") + 1,
"LookupPrivilegeNameA returned an incorrect required length for\n"
"SeCreateTokenPrivilege (got %d, expected %d)\n", cchName,
lstrlenA("SeCreateTokenPrivilege") + 1);
/* check a known value and its returned length on success */
cchName = sizeof(buf);
ok(pLookupPrivilegeNameA(NULL, &luid, buf, &cchName) &&
cchName == strlen("SeCreateTokenPrivilege"),
"LookupPrivilegeNameA returned an incorrect output length for\n"
"SeCreateTokenPrivilege (got %d, expected %d)\n", cchName,
(int)strlen("SeCreateTokenPrivilege"));
/* check known values */
for (i = SE_MIN_WELL_KNOWN_PRIVILEGE; i <= SE_MAX_WELL_KNOWN_PRIVILEGE; i++)
{
luid.LowPart = i;
cchName = sizeof(buf);
ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
ok( ret || GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
"LookupPrivilegeNameA(0.%d) failed: %d\n", i, GetLastError());
}
/* check a bogus LUID */
luid.LowPart = 0xdeadbeef;
cchName = sizeof(buf);
ret = pLookupPrivilegeNameA(NULL, &luid, buf, &cchName);
ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
"LookupPrivilegeNameA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
GetLastError());
/* check on a bogus system */
luid.LowPart = SE_CREATE_TOKEN_PRIVILEGE;
cchName = sizeof(buf);
ret = pLookupPrivilegeNameA("b0gu5.Nam3", &luid, buf, &cchName);
ok( !ret && (GetLastError() == RPC_S_SERVER_UNAVAILABLE ||
GetLastError() == RPC_S_INVALID_NET_ADDR) /* w2k8 */,
"LookupPrivilegeNameA didn't fail with RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR: %d\n",
GetLastError());
}
struct NameToLUID
{
const char *name;
DWORD lowPart;
};
static void test_lookupPrivilegeValue(void)
{
static const struct NameToLUID privs[] = {
{ "SeCreateTokenPrivilege", SE_CREATE_TOKEN_PRIVILEGE },
{ "SeAssignPrimaryTokenPrivilege", SE_ASSIGNPRIMARYTOKEN_PRIVILEGE },
{ "SeLockMemoryPrivilege", SE_LOCK_MEMORY_PRIVILEGE },
{ "SeIncreaseQuotaPrivilege", SE_INCREASE_QUOTA_PRIVILEGE },
{ "SeMachineAccountPrivilege", SE_MACHINE_ACCOUNT_PRIVILEGE },
{ "SeTcbPrivilege", SE_TCB_PRIVILEGE },
{ "SeSecurityPrivilege", SE_SECURITY_PRIVILEGE },
{ "SeTakeOwnershipPrivilege", SE_TAKE_OWNERSHIP_PRIVILEGE },
{ "SeLoadDriverPrivilege", SE_LOAD_DRIVER_PRIVILEGE },
{ "SeSystemProfilePrivilege", SE_SYSTEM_PROFILE_PRIVILEGE },
{ "SeSystemtimePrivilege", SE_SYSTEMTIME_PRIVILEGE },
{ "SeProfileSingleProcessPrivilege", SE_PROF_SINGLE_PROCESS_PRIVILEGE },
{ "SeIncreaseBasePriorityPrivilege", SE_INC_BASE_PRIORITY_PRIVILEGE },
{ "SeCreatePagefilePrivilege", SE_CREATE_PAGEFILE_PRIVILEGE },
{ "SeCreatePermanentPrivilege", SE_CREATE_PERMANENT_PRIVILEGE },
{ "SeBackupPrivilege", SE_BACKUP_PRIVILEGE },
{ "SeRestorePrivilege", SE_RESTORE_PRIVILEGE },
{ "SeShutdownPrivilege", SE_SHUTDOWN_PRIVILEGE },
{ "SeDebugPrivilege", SE_DEBUG_PRIVILEGE },
{ "SeAuditPrivilege", SE_AUDIT_PRIVILEGE },
{ "SeSystemEnvironmentPrivilege", SE_SYSTEM_ENVIRONMENT_PRIVILEGE },
{ "SeChangeNotifyPrivilege", SE_CHANGE_NOTIFY_PRIVILEGE },
{ "SeRemoteShutdownPrivilege", SE_REMOTE_SHUTDOWN_PRIVILEGE },
{ "SeUndockPrivilege", SE_UNDOCK_PRIVILEGE },
{ "SeSyncAgentPrivilege", SE_SYNC_AGENT_PRIVILEGE },
{ "SeEnableDelegationPrivilege", SE_ENABLE_DELEGATION_PRIVILEGE },
{ "SeManageVolumePrivilege", SE_MANAGE_VOLUME_PRIVILEGE },
{ "SeImpersonatePrivilege", SE_IMPERSONATE_PRIVILEGE },
{ "SeCreateGlobalPrivilege", SE_CREATE_GLOBAL_PRIVILEGE },
};
BOOL (WINAPI *pLookupPrivilegeValueA)(LPCSTR, LPCSTR, PLUID);
unsigned int i;
LUID luid;
BOOL ret;
/* check whether it's available first */
pLookupPrivilegeValueA = (void*)GetProcAddress(hmod, "LookupPrivilegeValueA");
if (!pLookupPrivilegeValueA) return;
ret = pLookupPrivilegeValueA(NULL, "SeCreateTokenPrivilege", &luid);
if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
return;
/* check a bogus system name */
ret = pLookupPrivilegeValueA("b0gu5.Nam3", "SeCreateTokenPrivilege", &luid);
ok( !ret && (GetLastError() == RPC_S_SERVER_UNAVAILABLE ||
GetLastError() == RPC_S_INVALID_NET_ADDR) /* w2k8 */,
"LookupPrivilegeValueA didn't fail with RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR: %d\n",
GetLastError());
/* check a NULL string */
ret = pLookupPrivilegeValueA(NULL, 0, &luid);
ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
"LookupPrivilegeValueA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
GetLastError());
/* check a bogus privilege name */
ret = pLookupPrivilegeValueA(NULL, "SeBogusPrivilege", &luid);
ok( !ret && GetLastError() == ERROR_NO_SUCH_PRIVILEGE,
"LookupPrivilegeValueA didn't fail with ERROR_NO_SUCH_PRIVILEGE: %d\n",
GetLastError());
/* check case insensitive */
ret = pLookupPrivilegeValueA(NULL, "sEcREATEtOKENpRIVILEGE", &luid);
ok( ret,
"LookupPrivilegeValueA(NULL, sEcREATEtOKENpRIVILEGE, &luid) failed: %d\n",
GetLastError());
for (i = 0; i < ARRAY_SIZE(privs); i++)
{
/* Not all privileges are implemented on all Windows versions, so
* don't worry if the call fails
*/
if (pLookupPrivilegeValueA(NULL, privs[i].name, &luid))
{
ok(luid.LowPart == privs[i].lowPart,
"LookupPrivilegeValueA returned an invalid LUID for %s\n",
privs[i].name);
}
}
}
static void test_luid(void)
{
test_allocateLuid();
test_lookupPrivilegeName();
test_lookupPrivilegeValue();
}
static void test_FileSecurity(void)
{
char wintmpdir [MAX_PATH];
char path [MAX_PATH];
char file [MAX_PATH];
HANDLE fh, token;
DWORD sdSize, retSize, rc, granted, priv_set_len;
PRIVILEGE_SET priv_set;
BOOL status;
BYTE *sd;
GENERIC_MAPPING mapping = { FILE_READ_DATA, FILE_WRITE_DATA, FILE_EXECUTE, FILE_ALL_ACCESS };
const SECURITY_INFORMATION request = OWNER_SECURITY_INFORMATION
| GROUP_SECURITY_INFORMATION
| DACL_SECURITY_INFORMATION;
if (!pGetFileSecurityA) {
win_skip ("GetFileSecurity is not available\n");
return;
}
if (!pSetFileSecurityA) {
win_skip ("SetFileSecurity is not available\n");
return;
}
if (!GetTempPathA (sizeof (wintmpdir), wintmpdir)) {
win_skip ("GetTempPathA failed\n");
return;
}
/* Create a temporary directory and in it a temporary file */
strcat (strcpy (path, wintmpdir), "rary");
SetLastError(0xdeadbeef);
rc = CreateDirectoryA (path, NULL);
ok (rc || GetLastError() == ERROR_ALREADY_EXISTS, "CreateDirectoryA "
"failed for '%s' with %d\n", path, GetLastError());
strcat (strcpy (file, path), "\\ess");
SetLastError(0xdeadbeef);
fh = CreateFileA (file, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
ok (fh != INVALID_HANDLE_VALUE, "CreateFileA "
"failed for '%s' with %d\n", file, GetLastError());
CloseHandle (fh);
/* For the temporary file ... */
/* Get size needed */
retSize = 0;
SetLastError(0xdeadbeef);
rc = pGetFileSecurityA (file, request, NULL, 0, &retSize);
if (!rc && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)) {
win_skip("GetFileSecurityA is not implemented\n");
goto cleanup;
}
ok (!rc, "GetFileSecurityA "
"was expected to fail for '%s'\n", file);
ok (GetLastError() == ERROR_INSUFFICIENT_BUFFER, "GetFileSecurityA "
"returned %d; expected ERROR_INSUFFICIENT_BUFFER\n", GetLastError());
ok (retSize > sizeof (SECURITY_DESCRIPTOR), "GetFileSecurityA returned size %d\n", retSize);
sdSize = retSize;
sd = HeapAlloc (GetProcessHeap (), 0, sdSize);
/* Get security descriptor for real */
retSize = -1;
SetLastError(0xdeadbeef);
rc = pGetFileSecurityA (file, request, sd, sdSize, &retSize);
ok (rc, "GetFileSecurityA "
"was not expected to fail '%s': %d\n", file, GetLastError());
ok (retSize == sdSize ||
broken(retSize == 0), /* NT4 */
"GetFileSecurityA returned size %d; expected %d\n", retSize, sdSize);
/* Use it to set security descriptor */
SetLastError(0xdeadbeef);
rc = pSetFileSecurityA (file, request, sd);
ok (rc, "SetFileSecurityA "
"was not expected to fail '%s': %d\n", file, GetLastError());
HeapFree (GetProcessHeap (), 0, sd);
/* Repeat for the temporary directory ... */
/* Get size needed */
retSize = 0;
SetLastError(0xdeadbeef);
rc = pGetFileSecurityA (path, request, NULL, 0, &retSize);
ok (!rc, "GetFileSecurityA "
"was expected to fail for '%s'\n", path);
ok (GetLastError() == ERROR_INSUFFICIENT_BUFFER, "GetFileSecurityA "
"returned %d; expected ERROR_INSUFFICIENT_BUFFER\n", GetLastError());
ok (retSize > sizeof (SECURITY_DESCRIPTOR), "GetFileSecurityA returned size %d\n", retSize);
sdSize = retSize;
sd = HeapAlloc (GetProcessHeap (), 0, sdSize);
/* Get security descriptor for real */
retSize = -1;
SetLastError(0xdeadbeef);
rc = pGetFileSecurityA (path, request, sd, sdSize, &retSize);
ok (rc, "GetFileSecurityA "
"was not expected to fail '%s': %d\n", path, GetLastError());
ok (retSize == sdSize ||
broken(retSize == 0), /* NT4 */
"GetFileSecurityA returned size %d; expected %d\n", retSize, sdSize);
/* Use it to set security descriptor */
SetLastError(0xdeadbeef);
rc = pSetFileSecurityA (path, request, sd);
ok (rc, "SetFileSecurityA "
"was not expected to fail '%s': %d\n", path, GetLastError());
HeapFree (GetProcessHeap (), 0, sd);
/* Old test */
strcpy (wintmpdir, "\\Should not exist");
SetLastError(0xdeadbeef);
rc = pGetFileSecurityA (wintmpdir, OWNER_SECURITY_INFORMATION, NULL, 0, &sdSize);
ok (!rc, "GetFileSecurityA should fail for not existing directories/files\n");
ok (GetLastError() == ERROR_FILE_NOT_FOUND,
"last error ERROR_FILE_NOT_FOUND expected, got %d\n", GetLastError());
cleanup:
/* Remove temporary file and directory */
DeleteFileA(file);
RemoveDirectoryA(path);
/* Test file access permissions for a file with FILE_ATTRIBUTE_ARCHIVE */
SetLastError(0xdeadbeef);
rc = GetTempPathA(sizeof(wintmpdir), wintmpdir);
ok(rc, "GetTempPath error %d\n", GetLastError());
SetLastError(0xdeadbeef);
rc = GetTempFileNameA(wintmpdir, "tmp", 0, file);
ok(rc, "GetTempFileName error %d\n", GetLastError());
rc = GetFileAttributesA(file);
rc &= ~(FILE_ATTRIBUTE_NOT_CONTENT_INDEXED|FILE_ATTRIBUTE_COMPRESSED);
ok(rc == FILE_ATTRIBUTE_ARCHIVE, "expected FILE_ATTRIBUTE_ARCHIVE got %#x\n", rc);
rc = GetFileSecurityA(file, OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION,
NULL, 0, &sdSize);
ok(!rc, "GetFileSecurity should fail\n");
ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"expected ERROR_INSUFFICIENT_BUFFER got %d\n", GetLastError());
ok(sdSize > sizeof(SECURITY_DESCRIPTOR), "got sd size %d\n", sdSize);
sd = HeapAlloc(GetProcessHeap (), 0, sdSize);
retSize = 0xdeadbeef;
SetLastError(0xdeadbeef);
rc = GetFileSecurityA(file, OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION,
sd, sdSize, &retSize);
ok(rc, "GetFileSecurity error %d\n", GetLastError());
ok(retSize == sdSize || broken(retSize == 0) /* NT4 */, "expected %d, got %d\n", sdSize, retSize);
SetLastError(0xdeadbeef);
rc = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &token);
ok(!rc, "OpenThreadToken should fail\n");
ok(GetLastError() == ERROR_NO_TOKEN, "expected ERROR_NO_TOKEN, got %d\n", GetLastError());
SetLastError(0xdeadbeef);
rc = ImpersonateSelf(SecurityIdentification);
ok(rc, "ImpersonateSelf error %d\n", GetLastError());
SetLastError(0xdeadbeef);
rc = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &token);
ok(rc, "OpenThreadToken error %d\n", GetLastError());
SetLastError(0xdeadbeef);
rc = RevertToSelf();
ok(rc, "RevertToSelf error %d\n", GetLastError());
priv_set_len = sizeof(priv_set);
granted = 0xdeadbeef;
status = 0xdeadbeef;
SetLastError(0xdeadbeef);
rc = AccessCheck(sd, token, FILE_READ_DATA, &mapping, &priv_set, &priv_set_len, &granted, &status);
ok(rc, "AccessCheck error %d\n", GetLastError());
ok(status == 1, "expected 1, got %d\n", status);
ok(granted == FILE_READ_DATA, "expected FILE_READ_DATA, got %#x\n", granted);
granted = 0xdeadbeef;
status = 0xdeadbeef;
SetLastError(0xdeadbeef);
rc = AccessCheck(sd, token, FILE_WRITE_DATA, &mapping, &priv_set, &priv_set_len, &granted, &status);
ok(rc, "AccessCheck error %d\n", GetLastError());
ok(status == 1, "expected 1, got %d\n", status);
ok(granted == FILE_WRITE_DATA, "expected FILE_WRITE_DATA, got %#x\n", granted);
granted = 0xdeadbeef;
status = 0xdeadbeef;
SetLastError(0xdeadbeef);
rc = AccessCheck(sd, token, FILE_EXECUTE, &mapping, &priv_set, &priv_set_len, &granted, &status);
ok(rc, "AccessCheck error %d\n", GetLastError());
ok(status == 1, "expected 1, got %d\n", status);
ok(granted == FILE_EXECUTE, "expected FILE_EXECUTE, got %#x\n", granted);
granted = 0xdeadbeef;
status = 0xdeadbeef;
SetLastError(0xdeadbeef);
rc = AccessCheck(sd, token, DELETE, &mapping, &priv_set, &priv_set_len, &granted, &status);
ok(rc, "AccessCheck error %d\n", GetLastError());
ok(status == 1, "expected 1, got %d\n", status);
ok(granted == DELETE, "expected DELETE, got %#x\n", granted);
granted = 0xdeadbeef;
status = 0xdeadbeef;
SetLastError(0xdeadbeef);
rc = AccessCheck(sd, token, FILE_DELETE_CHILD, &mapping, &priv_set, &priv_set_len, &granted, &status);
ok(rc, "AccessCheck error %d\n", GetLastError());
ok(status == 1, "expected 1, got %d\n", status);
ok(granted == FILE_DELETE_CHILD, "expected FILE_DELETE_CHILD, got %#x\n", granted);
granted = 0xdeadbeef;
status = 0xdeadbeef;
SetLastError(0xdeadbeef);
rc = AccessCheck(sd, token, 0x1ff, &mapping, &priv_set, &priv_set_len, &granted, &status);
ok(rc, "AccessCheck error %d\n", GetLastError());
ok(status == 1, "expected 1, got %d\n", status);
ok(granted == 0x1ff, "expected 0x1ff, got %#x\n", granted);
granted = 0xdeadbeef;
status = 0xdeadbeef;
SetLastError(0xdeadbeef);
rc = AccessCheck(sd, token, FILE_ALL_ACCESS, &mapping, &priv_set, &priv_set_len, &granted, &status);
ok(rc, "AccessCheck error %d\n", GetLastError());
ok(status == 1, "expected 1, got %d\n", status);
ok(granted == FILE_ALL_ACCESS, "expected FILE_ALL_ACCESS, got %#x\n", granted);
SetLastError(0xdeadbeef);
rc = AccessCheck(sd, token, 0xffffffff, &mapping, &priv_set, &priv_set_len, &granted, &status);
ok(!rc, "AccessCheck should fail\n");
ok(GetLastError() == ERROR_GENERIC_NOT_MAPPED, "expected ERROR_GENERIC_NOT_MAPPED, got %d\n", GetLastError());
/* Test file access permissions for a file with FILE_ATTRIBUTE_READONLY */
SetLastError(0xdeadbeef);
fh = CreateFileA(file, FILE_READ_DATA, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_READONLY, 0);
ok(fh != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
retSize = 0xdeadbeef;
SetLastError(0xdeadbeef);
rc = WriteFile(fh, "1", 1, &retSize, NULL);
ok(!rc, "WriteFile should fail\n");
ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
ok(retSize == 0, "expected 0, got %d\n", retSize);
CloseHandle(fh);
rc = GetFileAttributesA(file);
rc &= ~(FILE_ATTRIBUTE_NOT_CONTENT_INDEXED|FILE_ATTRIBUTE_COMPRESSED);
todo_wine
ok(rc == (FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_READONLY),
"expected FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_READONLY got %#x\n", rc);
SetLastError(0xdeadbeef);
rc = SetFileAttributesA(file, FILE_ATTRIBUTE_ARCHIVE);
ok(rc, "SetFileAttributes error %d\n", GetLastError());
SetLastError(0xdeadbeef);
rc = DeleteFileA(file);
ok(rc, "DeleteFile error %d\n", GetLastError());
SetLastError(0xdeadbeef);
fh = CreateFileA(file, FILE_READ_DATA, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_READONLY, 0);
ok(fh != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
retSize = 0xdeadbeef;
SetLastError(0xdeadbeef);
rc = WriteFile(fh, "1", 1, &retSize, NULL);
ok(!rc, "WriteFile should fail\n");
ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
ok(retSize == 0, "expected 0, got %d\n", retSize);
CloseHandle(fh);
rc = GetFileAttributesA(file);
rc &= ~(FILE_ATTRIBUTE_NOT_CONTENT_INDEXED|FILE_ATTRIBUTE_COMPRESSED);
ok(rc == (FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_READONLY),
"expected FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_READONLY got %#x\n", rc);
retSize = 0xdeadbeef;
SetLastError(0xdeadbeef);
rc = GetFileSecurityA(file, OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION,
sd, sdSize, &retSize);
ok(rc, "GetFileSecurity error %d\n", GetLastError());
ok(retSize == sdSize || broken(retSize == 0) /* NT4 */, "expected %d, got %d\n", sdSize, retSize);
priv_set_len = sizeof(priv_set);
granted = 0xdeadbeef;
status = 0xdeadbeef;
SetLastError(0xdeadbeef);
rc = AccessCheck(sd, token, FILE_READ_DATA, &mapping, &priv_set, &priv_set_len, &granted, &status);
ok(rc, "AccessCheck error %d\n", GetLastError());
ok(status == 1, "expected 1, got %d\n", status);
ok(granted == FILE_READ_DATA, "expected FILE_READ_DATA, got %#x\n", granted);
granted = 0xdeadbeef;
status = 0xdeadbeef;
SetLastError(0xdeadbeef);
rc = AccessCheck(sd, token, FILE_WRITE_DATA, &mapping, &priv_set, &priv_set_len, &granted, &status);
ok(rc, "AccessCheck error %d\n", GetLastError());
todo_wine {
ok(status == 1, "expected 1, got %d\n", status);
ok(granted == FILE_WRITE_DATA, "expected FILE_WRITE_DATA, got %#x\n", granted);
}
granted = 0xdeadbeef;
status = 0xdeadbeef;
SetLastError(0xdeadbeef);
rc = AccessCheck(sd, token, FILE_EXECUTE, &mapping, &priv_set, &priv_set_len, &granted, &status);
ok(rc, "AccessCheck error %d\n", GetLastError());
ok(status == 1, "expected 1, got %d\n", status);
ok(granted == FILE_EXECUTE, "expected FILE_EXECUTE, got %#x\n", granted);
granted = 0xdeadbeef;
status = 0xdeadbeef;
SetLastError(0xdeadbeef);
rc = AccessCheck(sd, token, DELETE, &mapping, &priv_set, &priv_set_len, &granted, &status);
ok(rc, "AccessCheck error %d\n", GetLastError());
todo_wine {
ok(status == 1, "expected 1, got %d\n", status);
ok(granted == DELETE, "expected DELETE, got %#x\n", granted);
}
granted = 0xdeadbeef;
status = 0xdeadbeef;
SetLastError(0xdeadbeef);
rc = AccessCheck(sd, token, FILE_DELETE_CHILD, &mapping, &priv_set, &priv_set_len, &granted, &status);
ok(rc, "AccessCheck error %d\n", GetLastError());
todo_wine {
ok(status == 1, "expected 1, got %d\n", status);
ok(granted == FILE_DELETE_CHILD, "expected FILE_DELETE_CHILD, got %#x\n", granted);
}
granted = 0xdeadbeef;
status = 0xdeadbeef;
SetLastError(0xdeadbeef);
rc = AccessCheck(sd, token, 0x1ff, &mapping, &priv_set, &priv_set_len, &granted, &status);
ok(rc, "AccessCheck error %d\n", GetLastError());
todo_wine {
ok(status == 1, "expected 1, got %d\n", status);
ok(granted == 0x1ff, "expected 0x1ff, got %#x\n", granted);
}
granted = 0xdeadbeef;
status = 0xdeadbeef;
SetLastError(0xdeadbeef);
rc = AccessCheck(sd, token, FILE_ALL_ACCESS, &mapping, &priv_set, &priv_set_len, &granted, &status);
ok(rc, "AccessCheck error %d\n", GetLastError());
todo_wine {
ok(status == 1, "expected 1, got %d\n", status);
ok(granted == FILE_ALL_ACCESS, "expected FILE_ALL_ACCESS, got %#x\n", granted);
}
SetLastError(0xdeadbeef);
rc = DeleteFileA(file);
ok(!rc, "DeleteFile should fail\n");
ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
SetLastError(0xdeadbeef);
rc = SetFileAttributesA(file, FILE_ATTRIBUTE_ARCHIVE);
ok(rc, "SetFileAttributes error %d\n", GetLastError());
SetLastError(0xdeadbeef);
rc = DeleteFileA(file);
ok(rc, "DeleteFile error %d\n", GetLastError());
CloseHandle(token);
HeapFree(GetProcessHeap(), 0, sd);
}
static void test_AccessCheck(void)
{
PSID EveryoneSid = NULL, AdminSid = NULL, UsersSid = NULL;
PACL Acl = NULL;
SECURITY_DESCRIPTOR *SecurityDescriptor = NULL;
SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
GENERIC_MAPPING Mapping = { KEY_READ, KEY_WRITE, KEY_EXECUTE, KEY_ALL_ACCESS };
ACCESS_MASK Access;
BOOL AccessStatus;
HANDLE Token;
HANDLE ProcessToken;
BOOL ret;
DWORD PrivSetLen;
PRIVILEGE_SET *PrivSet;
BOOL res;
HMODULE NtDllModule;
BOOLEAN Enabled;
DWORD err;
NTSTATUS ntret, ntAccessStatus;
NtDllModule = GetModuleHandleA("ntdll.dll");
if (!NtDllModule)
{
skip("not running on NT, skipping test\n");
return;
}
pRtlAdjustPrivilege = (void *)GetProcAddress(NtDllModule, "RtlAdjustPrivilege");
if (!pRtlAdjustPrivilege)
{
win_skip("missing RtlAdjustPrivilege, skipping test\n");
return;
}
Acl = HeapAlloc(GetProcessHeap(), 0, 256);
res = InitializeAcl(Acl, 256, ACL_REVISION);
if(!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
{
skip("ACLs not implemented - skipping tests\n");
HeapFree(GetProcessHeap(), 0, Acl);
return;
}
ok(res, "InitializeAcl failed with error %d\n", GetLastError());
res = AllocateAndInitializeSid( &SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &EveryoneSid);
ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &AdminSid);
ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &UsersSid);
ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
SecurityDescriptor = HeapAlloc(GetProcessHeap(), 0, SECURITY_DESCRIPTOR_MIN_LENGTH);
res = InitializeSecurityDescriptor(SecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
ok(res, "InitializeSecurityDescriptor failed with error %d\n", GetLastError());
res = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
ok(res, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
PrivSetLen = FIELD_OFFSET(PRIVILEGE_SET, Privilege[16]);
PrivSet = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, PrivSetLen);
PrivSet->PrivilegeCount = 16;
res = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE|TOKEN_QUERY, &ProcessToken);
ok(res, "OpenProcessToken failed with error %d\n", GetLastError());
pRtlAdjustPrivilege(SE_SECURITY_PRIVILEGE, FALSE, TRUE, &Enabled);
res = DuplicateToken(ProcessToken, SecurityImpersonation, &Token);
ok(res, "DuplicateToken failed with error %d\n", GetLastError());
/* SD without owner/group */
SetLastError(0xdeadbeef);
Access = AccessStatus = 0x1abe11ed;
ret = AccessCheck(SecurityDescriptor, Token, KEY_QUERY_VALUE, &Mapping,
PrivSet, &PrivSetLen, &Access, &AccessStatus);
err = GetLastError();
ok(!ret && err == ERROR_INVALID_SECURITY_DESCR, "AccessCheck should have "
"failed with ERROR_INVALID_SECURITY_DESCR, instead of %d\n", err);
ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
"Access and/or AccessStatus were changed!\n");
/* Set owner and group */
res = SetSecurityDescriptorOwner(SecurityDescriptor, AdminSid, FALSE);
ok(res, "SetSecurityDescriptorOwner failed with error %d\n", GetLastError());
res = SetSecurityDescriptorGroup(SecurityDescriptor, UsersSid, TRUE);
ok(res, "SetSecurityDescriptorGroup failed with error %d\n", GetLastError());
/* Generic access mask */
SetLastError(0xdeadbeef);
Access = AccessStatus = 0x1abe11ed;
ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
PrivSet, &PrivSetLen, &Access, &AccessStatus);
err = GetLastError();
ok(!ret && err == ERROR_GENERIC_NOT_MAPPED, "AccessCheck should have failed "
"with ERROR_GENERIC_NOT_MAPPED, instead of %d\n", err);
ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
"Access and/or AccessStatus were changed!\n");
/* Generic access mask - no privilegeset buffer */
SetLastError(0xdeadbeef);
Access = AccessStatus = 0x1abe11ed;
ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
NULL, &PrivSetLen, &Access, &AccessStatus);
err = GetLastError();
ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have failed "
"with ERROR_NOACCESS, instead of %d\n", err);
ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
"Access and/or AccessStatus were changed!\n");
/* Generic access mask - no returnlength */
SetLastError(0xdeadbeef);
Access = AccessStatus = 0x1abe11ed;
ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
PrivSet, NULL, &Access, &AccessStatus);
err = GetLastError();
ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have failed "
"with ERROR_NOACCESS, instead of %d\n", err);
ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
"Access and/or AccessStatus were changed!\n");
/* Generic access mask - no privilegeset buffer, no returnlength */
SetLastError(0xdeadbeef);
Access = AccessStatus = 0x1abe11ed;
ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
NULL, NULL, &Access, &AccessStatus);
err = GetLastError();
ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have failed "
"with ERROR_NOACCESS, instead of %d\n", err);
ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
"Access and/or AccessStatus were changed!\n");
/* sd with no dacl present */
Access = AccessStatus = 0x1abe11ed;
ret = SetSecurityDescriptorDacl(SecurityDescriptor, FALSE, NULL, FALSE);
ok(ret, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
PrivSet, &PrivSetLen, &Access, &AccessStatus);
ok(ret, "AccessCheck failed with error %d\n", GetLastError());
ok(AccessStatus && (Access == KEY_READ),
"AccessCheck failed to grant access with error %d\n",
GetLastError());
/* sd with no dacl present - no privilegeset buffer */
SetLastError(0xdeadbeef);
Access = AccessStatus = 0x1abe11ed;
ret = AccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
NULL, &PrivSetLen, &Access, &AccessStatus);
err = GetLastError();
ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have failed "
"with ERROR_NOACCESS, instead of %d\n", err);
ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
"Access and/or AccessStatus were changed!\n");
if(pNtAccessCheck)
{
DWORD ntPrivSetLen = sizeof(PRIVILEGE_SET);
/* Generic access mask - no privilegeset buffer */
SetLastError(0xdeadbeef);
Access = ntAccessStatus = 0x1abe11ed;
ntret = pNtAccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
NULL, &ntPrivSetLen, &Access, &ntAccessStatus);
err = GetLastError();
ok(ntret == STATUS_ACCESS_VIOLATION,
"NtAccessCheck should have failed with STATUS_ACCESS_VIOLATION, got %x\n", ntret);
ok(err == 0xdeadbeef,
"NtAccessCheck shouldn't set last error, got %d\n", err);
ok(Access == 0x1abe11ed && ntAccessStatus == 0x1abe11ed,
"Access and/or AccessStatus were changed!\n");
ok(ntPrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", ntPrivSetLen);
/* Generic access mask - no returnlength */
SetLastError(0xdeadbeef);
Access = ntAccessStatus = 0x1abe11ed;
ntret = pNtAccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
PrivSet, NULL, &Access, &ntAccessStatus);
err = GetLastError();
ok(ntret == STATUS_ACCESS_VIOLATION,
"NtAccessCheck should have failed with STATUS_ACCESS_VIOLATION, got %x\n", ntret);
ok(err == 0xdeadbeef,
"NtAccessCheck shouldn't set last error, got %d\n", err);
ok(Access == 0x1abe11ed && ntAccessStatus == 0x1abe11ed,
"Access and/or AccessStatus were changed!\n");
/* Generic access mask - no privilegeset buffer, no returnlength */
SetLastError(0xdeadbeef);
Access = ntAccessStatus = 0x1abe11ed;
ntret = pNtAccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
NULL, NULL, &Access, &ntAccessStatus);
err = GetLastError();
ok(ntret == STATUS_ACCESS_VIOLATION,
"NtAccessCheck should have failed with STATUS_ACCESS_VIOLATION, got %x\n", ntret);
ok(err == 0xdeadbeef,
"NtAccessCheck shouldn't set last error, got %d\n", err);
ok(Access == 0x1abe11ed && ntAccessStatus == 0x1abe11ed,
"Access and/or AccessStatus were changed!\n");
/* Generic access mask - zero returnlength */
SetLastError(0xdeadbeef);
Access = ntAccessStatus = 0x1abe11ed;
ntPrivSetLen = 0;
ntret = pNtAccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
PrivSet, &ntPrivSetLen, &Access, &ntAccessStatus);
err = GetLastError();
ok(ntret == STATUS_GENERIC_NOT_MAPPED,
"NtAccessCheck should have failed with STATUS_GENERIC_NOT_MAPPED, got %x\n", ntret);
ok(err == 0xdeadbeef,
"NtAccessCheck shouldn't set last error, got %d\n", err);
ok(Access == 0x1abe11ed && ntAccessStatus == 0x1abe11ed,
"Access and/or AccessStatus were changed!\n");
todo_wine ok(ntPrivSetLen == 0, "PrivSetLen returns %d\n", ntPrivSetLen);
/* Generic access mask - insufficient returnlength */
SetLastError(0xdeadbeef);
Access = ntAccessStatus = 0x1abe11ed;
ntPrivSetLen = sizeof(PRIVILEGE_SET)-1;
ntret = pNtAccessCheck(SecurityDescriptor, Token, GENERIC_READ, &Mapping,
PrivSet, &ntPrivSetLen, &Access, &ntAccessStatus);
err = GetLastError();
ok(ntret == STATUS_GENERIC_NOT_MAPPED,
"NtAccessCheck should have failed with STATUS_GENERIC_NOT_MAPPED, got %x\n", ntret);
ok(err == 0xdeadbeef,
"NtAccessCheck shouldn't set last error, got %d\n", err);
ok(Access == 0x1abe11ed && ntAccessStatus == 0x1abe11ed,
"Access and/or AccessStatus were changed!\n");
todo_wine ok(ntPrivSetLen == sizeof(PRIVILEGE_SET)-1, "PrivSetLen returns %d\n", ntPrivSetLen);
/* Key access mask - zero returnlength */
SetLastError(0xdeadbeef);
Access = ntAccessStatus = 0x1abe11ed;
ntPrivSetLen = 0;
ntret = pNtAccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
PrivSet, &ntPrivSetLen, &Access, &ntAccessStatus);
err = GetLastError();
todo_wine ok(ntret == STATUS_BUFFER_TOO_SMALL,
"NtAccessCheck should have failed with STATUS_BUFFER_TOO_SMALL, got %x\n", ntret);
ok(err == 0xdeadbeef,
"NtAccessCheck shouldn't set last error, got %d\n", err);
todo_wine ok(Access == 0x1abe11ed && ntAccessStatus == 0x1abe11ed,
"Access and/or AccessStatus were changed!\n");
todo_wine ok(ntPrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", ntPrivSetLen);
/* Key access mask - insufficient returnlength */
SetLastError(0xdeadbeef);
Access = ntAccessStatus = 0x1abe11ed;
ntPrivSetLen = sizeof(PRIVILEGE_SET)-1;
ntret = pNtAccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
PrivSet, &ntPrivSetLen, &Access, &ntAccessStatus);
err = GetLastError();
todo_wine ok(ntret == STATUS_BUFFER_TOO_SMALL,
"NtAccessCheck should have failed with STATUS_BUFFER_TOO_SMALL, got %x\n", ntret);
ok(err == 0xdeadbeef,
"NtAccessCheck shouldn't set last error, got %d\n", err);
todo_wine ok(Access == 0x1abe11ed && ntAccessStatus == 0x1abe11ed,
"Access and/or AccessStatus were changed!\n");
todo_wine ok(ntPrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", ntPrivSetLen);
}
else
win_skip("NtAccessCheck unavailable. Skipping.\n");
/* sd with NULL dacl */
Access = AccessStatus = 0x1abe11ed;
ret = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, NULL, FALSE);
ok(ret, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
PrivSet, &PrivSetLen, &Access, &AccessStatus);
ok(ret, "AccessCheck failed with error %d\n", GetLastError());
ok(AccessStatus && (Access == KEY_READ),
"AccessCheck failed to grant access with error %d\n",
GetLastError());
ret = AccessCheck(SecurityDescriptor, Token, MAXIMUM_ALLOWED, &Mapping,
PrivSet, &PrivSetLen, &Access, &AccessStatus);
ok(ret, "AccessCheck failed with error %d\n", GetLastError());
ok(AccessStatus && (Access == KEY_ALL_ACCESS),
"AccessCheck failed to grant access with error %d\n",
GetLastError());
/* sd with blank dacl */
ret = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
ok(ret, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
PrivSet, &PrivSetLen, &Access, &AccessStatus);
ok(ret, "AccessCheck failed with error %d\n", GetLastError());
err = GetLastError();
ok(!AccessStatus && err == ERROR_ACCESS_DENIED, "AccessCheck should have failed "
"with ERROR_ACCESS_DENIED, instead of %d\n", err);
ok(!Access, "Should have failed to grant any access, got 0x%08x\n", Access);
res = AddAccessAllowedAce(Acl, ACL_REVISION, KEY_READ, EveryoneSid);
ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
res = AddAccessDeniedAce(Acl, ACL_REVISION, KEY_SET_VALUE, AdminSid);
ok(res, "AddAccessDeniedAce failed with error %d\n", GetLastError());
/* sd with dacl */
Access = AccessStatus = 0x1abe11ed;
ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
PrivSet, &PrivSetLen, &Access, &AccessStatus);
ok(ret, "AccessCheck failed with error %d\n", GetLastError());
ok(AccessStatus && (Access == KEY_READ),
"AccessCheck failed to grant access with error %d\n",
GetLastError());
ret = AccessCheck(SecurityDescriptor, Token, MAXIMUM_ALLOWED, &Mapping,
PrivSet, &PrivSetLen, &Access, &AccessStatus);
ok(ret, "AccessCheck failed with error %d\n", GetLastError());
ok(AccessStatus,
"AccessCheck failed to grant any access with error %d\n",
GetLastError());
trace("AccessCheck with MAXIMUM_ALLOWED got Access 0x%08x\n", Access);
/* Null PrivSet with null PrivSetLen pointer */
SetLastError(0xdeadbeef);
Access = AccessStatus = 0x1abe11ed;
ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
NULL, NULL, &Access, &AccessStatus);
err = GetLastError();
ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have "
"failed with ERROR_NOACCESS, instead of %d\n", err);
ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
"Access and/or AccessStatus were changed!\n");
/* Null PrivSet with zero PrivSetLen */
SetLastError(0xdeadbeef);
Access = AccessStatus = 0x1abe11ed;
PrivSetLen = 0;
ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
0, &PrivSetLen, &Access, &AccessStatus);
err = GetLastError();
todo_wine
ok(!ret && err == ERROR_INSUFFICIENT_BUFFER, "AccessCheck should have "
"failed with ERROR_INSUFFICIENT_BUFFER, instead of %d\n", err);
todo_wine
ok(PrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", PrivSetLen);
ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
"Access and/or AccessStatus were changed!\n");
/* Null PrivSet with insufficient PrivSetLen */
SetLastError(0xdeadbeef);
Access = AccessStatus = 0x1abe11ed;
PrivSetLen = 1;
ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
0, &PrivSetLen, &Access, &AccessStatus);
err = GetLastError();
ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have "
"failed with ERROR_NOACCESS, instead of %d\n", err);
ok(PrivSetLen == 1, "PrivSetLen returns %d\n", PrivSetLen);
ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
"Access and/or AccessStatus were changed!\n");
/* Null PrivSet with insufficient PrivSetLen */
SetLastError(0xdeadbeef);
Access = AccessStatus = 0x1abe11ed;
PrivSetLen = sizeof(PRIVILEGE_SET) - 1;
ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
0, &PrivSetLen, &Access, &AccessStatus);
err = GetLastError();
ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have "
"failed with ERROR_NOACCESS, instead of %d\n", err);
ok(PrivSetLen == sizeof(PRIVILEGE_SET) - 1, "PrivSetLen returns %d\n", PrivSetLen);
ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
"Access and/or AccessStatus were changed!\n");
/* Null PrivSet with minimal sufficient PrivSetLen */
SetLastError(0xdeadbeef);
Access = AccessStatus = 0x1abe11ed;
PrivSetLen = sizeof(PRIVILEGE_SET);
ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
0, &PrivSetLen, &Access, &AccessStatus);
err = GetLastError();
ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have "
"failed with ERROR_NOACCESS, instead of %d\n", err);
ok(PrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", PrivSetLen);
ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
"Access and/or AccessStatus were changed!\n");
/* Valid PrivSet with zero PrivSetLen */
SetLastError(0xdeadbeef);
Access = AccessStatus = 0x1abe11ed;
PrivSetLen = 0;
ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
PrivSet, &PrivSetLen, &Access, &AccessStatus);
err = GetLastError();
todo_wine
ok(!ret && err == ERROR_INSUFFICIENT_BUFFER, "AccessCheck should have "
"failed with ERROR_INSUFFICIENT_BUFFER, instead of %d\n", err);
todo_wine
ok(PrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", PrivSetLen);
todo_wine
ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
"Access and/or AccessStatus were changed!\n");
/* Valid PrivSet with insufficient PrivSetLen */
SetLastError(0xdeadbeef);
Access = AccessStatus = 0x1abe11ed;
PrivSetLen = 1;
ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
PrivSet, &PrivSetLen, &Access, &AccessStatus);
err = GetLastError();
todo_wine
ok(!ret && err == ERROR_INSUFFICIENT_BUFFER, "AccessCheck should have "
"failed with ERROR_INSUFFICIENT_BUFFER, instead of %d\n", err);
todo_wine
ok(PrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", PrivSetLen);
todo_wine
ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
"Access and/or AccessStatus were changed!\n");
/* Valid PrivSet with insufficient PrivSetLen */
SetLastError(0xdeadbeef);
Access = AccessStatus = 0x1abe11ed;
PrivSetLen = sizeof(PRIVILEGE_SET) - 1;
ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
PrivSet, &PrivSetLen, &Access, &AccessStatus);
err = GetLastError();
todo_wine
ok(!ret && err == ERROR_INSUFFICIENT_BUFFER, "AccessCheck should have "
"failed with ERROR_INSUFFICIENT_BUFFER, instead of %d\n", err);
todo_wine
ok(PrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", PrivSetLen);
todo_wine
ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
"Access and/or AccessStatus were changed!\n");
/* Valid PrivSet with minimal sufficient PrivSetLen */
SetLastError(0xdeadbeef);
Access = AccessStatus = 0x1abe11ed;
PrivSetLen = sizeof(PRIVILEGE_SET);
memset(PrivSet, 0xcc, PrivSetLen);
ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
PrivSet, &PrivSetLen, &Access, &AccessStatus);
err = GetLastError();
ok(ret, "AccessCheck failed with error %d\n", GetLastError());
todo_wine
ok(PrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", PrivSetLen);
ok(AccessStatus && (Access == KEY_READ),
"AccessCheck failed to grant access with error %d\n", GetLastError());
ok(PrivSet->PrivilegeCount == 0, "PrivilegeCount returns %d, expects 0\n",
PrivSet->PrivilegeCount);
/* Valid PrivSet with sufficient PrivSetLen */
SetLastError(0xdeadbeef);
Access = AccessStatus = 0x1abe11ed;
PrivSetLen = sizeof(PRIVILEGE_SET) + 1;
memset(PrivSet, 0xcc, PrivSetLen);
ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
PrivSet, &PrivSetLen, &Access, &AccessStatus);
err = GetLastError();
ok(ret, "AccessCheck failed with error %d\n", GetLastError());
todo_wine
ok(PrivSetLen == sizeof(PRIVILEGE_SET) + 1, "PrivSetLen returns %d\n", PrivSetLen);
ok(AccessStatus && (Access == KEY_READ),
"AccessCheck failed to grant access with error %d\n", GetLastError());
ok(PrivSet->PrivilegeCount == 0, "PrivilegeCount returns %d, expects 0\n",
PrivSet->PrivilegeCount);
PrivSetLen = FIELD_OFFSET(PRIVILEGE_SET, Privilege[16]);
/* Null PrivSet with valid PrivSetLen */
SetLastError(0xdeadbeef);
Access = AccessStatus = 0x1abe11ed;
ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
0, &PrivSetLen, &Access, &AccessStatus);
err = GetLastError();
ok(!ret && err == ERROR_NOACCESS, "AccessCheck should have "
"failed with ERROR_NOACCESS, instead of %d\n", err);
ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
"Access and/or AccessStatus were changed!\n");
/* Access denied by SD */
SetLastError(0xdeadbeef);
Access = AccessStatus = 0x1abe11ed;
ret = AccessCheck(SecurityDescriptor, Token, KEY_WRITE, &Mapping,
PrivSet, &PrivSetLen, &Access, &AccessStatus);
ok(ret, "AccessCheck failed with error %d\n", GetLastError());
err = GetLastError();
ok(!AccessStatus && err == ERROR_ACCESS_DENIED, "AccessCheck should have failed "
"with ERROR_ACCESS_DENIED, instead of %d\n", err);
ok(!Access, "Should have failed to grant any access, got 0x%08x\n", Access);
SetLastError(0xdeadbeef);
PrivSet->PrivilegeCount = 16;
ret = AccessCheck(SecurityDescriptor, Token, ACCESS_SYSTEM_SECURITY, &Mapping,
PrivSet, &PrivSetLen, &Access, &AccessStatus);
ok(ret && !AccessStatus && GetLastError() == ERROR_PRIVILEGE_NOT_HELD,
"AccessCheck should have failed with ERROR_PRIVILEGE_NOT_HELD, instead of %d\n",
GetLastError());
ret = ImpersonateLoggedOnUser(Token);
ok(ret, "ImpersonateLoggedOnUser failed with error %d\n", GetLastError());
ret = pRtlAdjustPrivilege(SE_SECURITY_PRIVILEGE, TRUE, TRUE, &Enabled);
if (!ret)
{
/* Valid PrivSet with zero PrivSetLen */
SetLastError(0xdeadbeef);
Access = AccessStatus = 0x1abe11ed;
PrivSetLen = 0;
ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
PrivSet, &PrivSetLen, &Access, &AccessStatus);
err = GetLastError();
todo_wine
ok(!ret && err == ERROR_INSUFFICIENT_BUFFER, "AccessCheck should have "
"failed with ERROR_INSUFFICIENT_BUFFER, instead of %d\n", err);
todo_wine
ok(PrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", PrivSetLen);
todo_wine
ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
"Access and/or AccessStatus were changed!\n");
/* Valid PrivSet with insufficient PrivSetLen */
SetLastError(0xdeadbeef);
Access = AccessStatus = 0x1abe11ed;
PrivSetLen = sizeof(PRIVILEGE_SET) - 1;
ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
PrivSet, &PrivSetLen, &Access, &AccessStatus);
err = GetLastError();
todo_wine
ok(!ret && err == ERROR_INSUFFICIENT_BUFFER, "AccessCheck should have "
"failed with ERROR_INSUFFICIENT_BUFFER, instead of %d\n", err);
todo_wine
ok(PrivSetLen == sizeof(PRIVILEGE_SET), "PrivSetLen returns %d\n", PrivSetLen);
todo_wine
ok(Access == 0x1abe11ed && AccessStatus == 0x1abe11ed,
"Access and/or AccessStatus were changed!\n");
/* Valid PrivSet with minimal sufficient PrivSetLen */
SetLastError(0xdeadbeef);
Access = AccessStatus = 0x1abe11ed;
PrivSetLen = sizeof(PRIVILEGE_SET);
memset(PrivSet, 0xcc, PrivSetLen);
ret = AccessCheck(SecurityDescriptor, Token, ACCESS_SYSTEM_SECURITY, &Mapping,
PrivSet, &PrivSetLen, &Access, &AccessStatus);
ok(ret && AccessStatus && GetLastError() == 0xdeadbeef,
"AccessCheck should have succeeded, error %d\n",
GetLastError());
ok(Access == ACCESS_SYSTEM_SECURITY,
"Access should be equal to ACCESS_SYSTEM_SECURITY instead of 0x%08x\n",
Access);
ok(PrivSet->PrivilegeCount == 1, "PrivilegeCount returns %d, expects 1\n",
PrivSet->PrivilegeCount);
/* Valid PrivSet with large PrivSetLen */
SetLastError(0xdeadbeef);
Access = AccessStatus = 0x1abe11ed;
PrivSetLen = FIELD_OFFSET(PRIVILEGE_SET, Privilege[16]);
memset(PrivSet, 0xcc, PrivSetLen);
ret = AccessCheck(SecurityDescriptor, Token, ACCESS_SYSTEM_SECURITY, &Mapping,
PrivSet, &PrivSetLen, &Access, &AccessStatus);
ok(ret && AccessStatus && GetLastError() == 0xdeadbeef,
"AccessCheck should have succeeded, error %d\n",
GetLastError());
ok(Access == ACCESS_SYSTEM_SECURITY,
"Access should be equal to ACCESS_SYSTEM_SECURITY instead of 0x%08x\n",
Access);
ok(PrivSet->PrivilegeCount == 1, "PrivilegeCount returns %d, expects 1\n",
PrivSet->PrivilegeCount);
}
else
trace("Couldn't get SE_SECURITY_PRIVILEGE (0x%08x), skipping ACCESS_SYSTEM_SECURITY test\n",
ret);
ret = RevertToSelf();
ok(ret, "RevertToSelf failed with error %d\n", GetLastError());
/* test INHERIT_ONLY_ACE */
ret = InitializeAcl(Acl, 256, ACL_REVISION);
ok(ret, "InitializeAcl failed with error %d\n", GetLastError());
/* NT doesn't have AddAccessAllowedAceEx. Skipping this call/test doesn't influence
* the next ones.
*/
if (pAddAccessAllowedAceEx)
{
ret = pAddAccessAllowedAceEx(Acl, ACL_REVISION, INHERIT_ONLY_ACE, KEY_READ, EveryoneSid);
ok(ret, "AddAccessAllowedAceEx failed with error %d\n", GetLastError());
}
else
win_skip("AddAccessAllowedAceEx is not available\n");
ret = AccessCheck(SecurityDescriptor, Token, KEY_READ, &Mapping,
PrivSet, &PrivSetLen, &Access, &AccessStatus);
ok(ret, "AccessCheck failed with error %d\n", GetLastError());
err = GetLastError();
ok(!AccessStatus && err == ERROR_ACCESS_DENIED, "AccessCheck should have failed "
"with ERROR_ACCESS_DENIED, instead of %d\n", err);
ok(!Access, "Should have failed to grant any access, got 0x%08x\n", Access);
CloseHandle(Token);
res = DuplicateToken(ProcessToken, SecurityAnonymous, &Token);
ok(res, "DuplicateToken failed with error %d\n", GetLastError());
SetLastError(0xdeadbeef);
ret = AccessCheck(SecurityDescriptor, Token, MAXIMUM_ALLOWED, &Mapping,
PrivSet, &PrivSetLen, &Access, &AccessStatus);
err = GetLastError();
ok(!ret && err == ERROR_BAD_IMPERSONATION_LEVEL, "AccessCheck should have failed "
"with ERROR_BAD_IMPERSONATION_LEVEL, instead of %d\n", err);
CloseHandle(Token);
SetLastError(0xdeadbeef);
ret = AccessCheck(SecurityDescriptor, ProcessToken, KEY_READ, &Mapping,
PrivSet, &PrivSetLen, &Access, &AccessStatus);
err = GetLastError();
ok(!ret && err == ERROR_NO_IMPERSONATION_TOKEN, "AccessCheck should have failed "
"with ERROR_NO_IMPERSONATION_TOKEN, instead of %d\n", err);
CloseHandle(ProcessToken);
if (EveryoneSid)
FreeSid(EveryoneSid);
if (AdminSid)
FreeSid(AdminSid);
if (UsersSid)
FreeSid(UsersSid);
HeapFree(GetProcessHeap(), 0, Acl);
HeapFree(GetProcessHeap(), 0, SecurityDescriptor);
HeapFree(GetProcessHeap(), 0, PrivSet);
}
/* test GetTokenInformation for the various attributes */
static void test_token_attr(void)
{
HANDLE Token, ImpersonationToken;
DWORD Size, Size2;
TOKEN_PRIVILEGES *Privileges;
TOKEN_GROUPS *Groups;
TOKEN_USER *User;
TOKEN_DEFAULT_DACL *Dacl;
BOOL ret;
DWORD i, GLE;
LPSTR SidString;
SECURITY_IMPERSONATION_LEVEL ImpersonationLevel;
ACL *acl;
/* cygwin-like use case */
SetLastError(0xdeadbeef);
ret = OpenProcessToken(GetCurrentProcess(), MAXIMUM_ALLOWED, &Token);
if(!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
{
win_skip("OpenProcessToken is not implemented\n");
return;
}
ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
if (ret)
{
DWORD buf[256]; /* GetTokenInformation wants a dword-aligned buffer */
Size = sizeof(buf);
ret = GetTokenInformation(Token, TokenUser,(void*)buf, Size, &Size);
ok(ret, "GetTokenInformation failed with error %d\n", GetLastError());
Size = sizeof(ImpersonationLevel);
ret = GetTokenInformation(Token, TokenImpersonationLevel, &ImpersonationLevel, Size, &Size);
GLE = GetLastError();
ok(!ret && (GLE == ERROR_INVALID_PARAMETER), "GetTokenInformation(TokenImpersonationLevel) on primary token should have failed with ERROR_INVALID_PARAMETER instead of %d\n", GLE);
CloseHandle(Token);
}
SetLastError(0xdeadbeef);
ret = OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &Token);
ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
/* groups */
/* insufficient buffer length */
SetLastError(0xdeadbeef);
Size2 = 0;
ret = GetTokenInformation(Token, TokenGroups, NULL, 0, &Size2);
ok(Size2 > 1, "got %d\n", Size2);
ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"%d with error %d\n", ret, GetLastError());
Size2 -= 1;
Groups = HeapAlloc(GetProcessHeap(), 0, Size2);
memset(Groups, 0xcc, Size2);
Size = 0;
ret = GetTokenInformation(Token, TokenGroups, Groups, Size2, &Size);
ok(Size > 1, "got %d\n", Size);
ok((!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER) || broken(ret) /* wow64 */,
"%d with error %d\n", ret, GetLastError());
if(!ret)
ok(*((BYTE*)Groups) == 0xcc, "buffer altered\n");
HeapFree(GetProcessHeap(), 0, Groups);
SetLastError(0xdeadbeef);
ret = GetTokenInformation(Token, TokenGroups, NULL, 0, &Size);
ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"GetTokenInformation(TokenGroups) %s with error %d\n",
ret ? "succeeded" : "failed", GetLastError());
Groups = HeapAlloc(GetProcessHeap(), 0, Size);
SetLastError(0xdeadbeef);
ret = GetTokenInformation(Token, TokenGroups, Groups, Size, &Size);
ok(ret, "GetTokenInformation(TokenGroups) failed with error %d\n", GetLastError());
ok(GetLastError() == 0xdeadbeef,
"GetTokenInformation shouldn't have set last error to %d\n",
GetLastError());
trace("TokenGroups:\n");
for (i = 0; i < Groups->GroupCount; i++)
{
DWORD NameLength = 255;
CHAR Name[255];
DWORD DomainLength = 255;
CHAR Domain[255];
SID_NAME_USE SidNameUse;
Name[0] = '\0';
Domain[0] = '\0';
ret = LookupAccountSidA(NULL, Groups->Groups[i].Sid, Name, &NameLength, Domain, &DomainLength, &SidNameUse);
if (ret)
{
ConvertSidToStringSidA(Groups->Groups[i].Sid, &SidString);
trace("%s, %s\\%s use: %d attr: 0x%08x\n", SidString, Domain, Name, SidNameUse, Groups->Groups[i].Attributes);
LocalFree(SidString);
}
else trace("attr: 0x%08x LookupAccountSid failed with error %d\n", Groups->Groups[i].Attributes, GetLastError());
}
HeapFree(GetProcessHeap(), 0, Groups);
/* user */
ret = GetTokenInformation(Token, TokenUser, NULL, 0, &Size);
ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
"GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
User = HeapAlloc(GetProcessHeap(), 0, Size);
ret = GetTokenInformation(Token, TokenUser, User, Size, &Size);
ok(ret,
"GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
ConvertSidToStringSidA(User->User.Sid, &SidString);
trace("TokenUser: %s attr: 0x%08x\n", SidString, User->User.Attributes);
LocalFree(SidString);
HeapFree(GetProcessHeap(), 0, User);
/* logon */
ret = GetTokenInformation(Token, TokenLogonSid, NULL, 0, &Size);
if (!ret && (GetLastError() == ERROR_INVALID_PARAMETER))
todo_wine win_skip("TokenLogonSid not supported. Skipping tests\n");
else
{
ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
"GetTokenInformation(TokenLogonSid) failed with error %d\n", GetLastError());
Groups = HeapAlloc(GetProcessHeap(), 0, Size);
ret = GetTokenInformation(Token, TokenLogonSid, Groups, Size, &Size);
ok(ret,
"GetTokenInformation(TokenLogonSid) failed with error %d\n", GetLastError());
if (ret)
{
ok(Groups->GroupCount == 1, "got %d\n", Groups->GroupCount);
if(Groups->GroupCount == 1)
{
ConvertSidToStringSidA(Groups->Groups[0].Sid, &SidString);
trace("TokenLogon: %s\n", SidString);
LocalFree(SidString);
/* S-1-5-5-0-XXXXXX */
ret = IsWellKnownSid(Groups->Groups[0].Sid, WinLogonIdsSid);
ok(ret, "Unknown SID\n");
}
}
HeapFree(GetProcessHeap(), 0, Groups);
}
/* privileges */
ret = GetTokenInformation(Token, TokenPrivileges, NULL, 0, &Size);
ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
"GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
Privileges = HeapAlloc(GetProcessHeap(), 0, Size);
ret = GetTokenInformation(Token, TokenPrivileges, Privileges, Size, &Size);
ok(ret,
"GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
trace("TokenPrivileges:\n");
for (i = 0; i < Privileges->PrivilegeCount; i++)
{
CHAR Name[256];
DWORD NameLen = ARRAY_SIZE(Name);
LookupPrivilegeNameA(NULL, &Privileges->Privileges[i].Luid, Name, &NameLen);
trace("\t%s, 0x%x\n", Name, Privileges->Privileges[i].Attributes);
}
HeapFree(GetProcessHeap(), 0, Privileges);
ret = DuplicateToken(Token, SecurityAnonymous, &ImpersonationToken);
ok(ret, "DuplicateToken failed with error %d\n", GetLastError());
Size = sizeof(ImpersonationLevel);
ret = GetTokenInformation(ImpersonationToken, TokenImpersonationLevel, &ImpersonationLevel, Size, &Size);
ok(ret, "GetTokenInformation(TokenImpersonationLevel) failed with error %d\n", GetLastError());
ok(ImpersonationLevel == SecurityAnonymous, "ImpersonationLevel should have been SecurityAnonymous instead of %d\n", ImpersonationLevel);
CloseHandle(ImpersonationToken);
/* default dacl */
ret = GetTokenInformation(Token, TokenDefaultDacl, NULL, 0, &Size);
ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
"GetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
Dacl = HeapAlloc(GetProcessHeap(), 0, Size);
ret = GetTokenInformation(Token, TokenDefaultDacl, Dacl, Size, &Size);
ok(ret, "GetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
SetLastError(0xdeadbeef);
ret = SetTokenInformation(Token, TokenDefaultDacl, NULL, 0);
GLE = GetLastError();
ok(!ret, "SetTokenInformation(TokenDefaultDacl) succeeded\n");
ok(GLE == ERROR_BAD_LENGTH, "expected ERROR_BAD_LENGTH got %u\n", GLE);
SetLastError(0xdeadbeef);
ret = SetTokenInformation(Token, TokenDefaultDacl, NULL, Size);
GLE = GetLastError();
ok(!ret, "SetTokenInformation(TokenDefaultDacl) succeeded\n");
ok(GLE == ERROR_NOACCESS, "expected ERROR_NOACCESS got %u\n", GLE);
acl = Dacl->DefaultDacl;
Dacl->DefaultDacl = NULL;
ret = SetTokenInformation(Token, TokenDefaultDacl, Dacl, Size);
ok(ret, "SetTokenInformation(TokenDefaultDacl) succeeded\n");
Size2 = 0;
Dacl->DefaultDacl = (ACL *)0xdeadbeef;
ret = GetTokenInformation(Token, TokenDefaultDacl, Dacl, Size, &Size2);
ok(ret, "GetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
ok(Dacl->DefaultDacl == NULL, "expected NULL, got %p\n", Dacl->DefaultDacl);
ok(Size2 == sizeof(TOKEN_DEFAULT_DACL) || broken(Size2 == 2*sizeof(TOKEN_DEFAULT_DACL)), /* WoW64 */
"got %u expected sizeof(TOKEN_DEFAULT_DACL)\n", Size2);
Dacl->DefaultDacl = acl;
ret = SetTokenInformation(Token, TokenDefaultDacl, Dacl, Size);
ok(ret, "SetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
if (Size2 == sizeof(TOKEN_DEFAULT_DACL)) {
ret = GetTokenInformation(Token, TokenDefaultDacl, Dacl, Size, &Size2);
ok(ret, "GetTokenInformation(TokenDefaultDacl) failed with error %u\n", GetLastError());
} else
win_skip("TOKEN_DEFAULT_DACL size too small on WoW64\n");
HeapFree(GetProcessHeap(), 0, Dacl);
CloseHandle(Token);
}
static void test_GetTokenInformation(void)
{
DWORD is_app_container, size;
HANDLE token;
BOOL ret;
ret = OpenProcessToken(GetCurrentProcess(), MAXIMUM_ALLOWED, &token);
ok(ret, "OpenProcessToken failed: %u\n", GetLastError());
size = 0;
is_app_container = 0xdeadbeef;
ret = GetTokenInformation(token, TokenIsAppContainer, &is_app_container,
sizeof(is_app_container), &size);
ok(ret || broken(GetLastError() == ERROR_INVALID_PARAMETER ||
GetLastError() == ERROR_INVALID_FUNCTION), /* pre-win8 */
"GetTokenInformation failed: %u\n", GetLastError());
if(ret) {
ok(size == sizeof(is_app_container), "size = %u\n", size);
ok(!is_app_container, "is_app_container = %x\n", is_app_container);
}
CloseHandle(token);
}
typedef union _MAX_SID
{
SID sid;
char max[SECURITY_MAX_SID_SIZE];
} MAX_SID;
static void test_sid_str(PSID * sid)
{
char *str_sid;
BOOL ret = ConvertSidToStringSidA(sid, &str_sid);
ok(ret, "ConvertSidToStringSidA() failed: %d\n", GetLastError());
if (ret)
{
char account[MAX_PATH], domain[MAX_PATH];
SID_NAME_USE use;
DWORD acc_size = MAX_PATH;
DWORD dom_size = MAX_PATH;
ret = LookupAccountSidA (NULL, sid, account, &acc_size, domain, &dom_size, &use);
ok(ret || GetLastError() == ERROR_NONE_MAPPED,
"LookupAccountSid(%s) failed: %d\n", str_sid, GetLastError());
if (ret)
trace(" %s %s\\%s %d\n", str_sid, domain, account, use);
else if (GetLastError() == ERROR_NONE_MAPPED)
trace(" %s couldn't be mapped\n", str_sid);
LocalFree(str_sid);
}
}
static const struct well_known_sid_value
{
BOOL without_domain;
const char *sid_string;
} well_known_sid_values[] = {
/* 0 */ {TRUE, "S-1-0-0"}, {TRUE, "S-1-1-0"}, {TRUE, "S-1-2-0"}, {TRUE, "S-1-3-0"},
/* 4 */ {TRUE, "S-1-3-1"}, {TRUE, "S-1-3-2"}, {TRUE, "S-1-3-3"}, {TRUE, "S-1-5"},
/* 8 */ {FALSE, "S-1-5-1"}, {TRUE, "S-1-5-2"}, {TRUE, "S-1-5-3"}, {TRUE, "S-1-5-4"},
/* 12 */ {TRUE, "S-1-5-6"}, {TRUE, "S-1-5-7"}, {TRUE, "S-1-5-8"}, {TRUE, "S-1-5-9"},
/* 16 */ {TRUE, "S-1-5-10"}, {TRUE, "S-1-5-11"}, {TRUE, "S-1-5-12"}, {TRUE, "S-1-5-13"},
/* 20 */ {TRUE, "S-1-5-14"}, {FALSE, NULL}, {TRUE, "S-1-5-18"}, {TRUE, "S-1-5-19"},
/* 24 */ {TRUE, "S-1-5-20"}, {TRUE, "S-1-5-32"},
/* 26 */ {FALSE, "S-1-5-32-544"}, {TRUE, "S-1-5-32-545"}, {TRUE, "S-1-5-32-546"},
/* 29 */ {TRUE, "S-1-5-32-547"}, {TRUE, "S-1-5-32-548"}, {TRUE, "S-1-5-32-549"},
/* 32 */ {TRUE, "S-1-5-32-550"}, {TRUE, "S-1-5-32-551"}, {TRUE, "S-1-5-32-552"},
/* 35 */ {TRUE, "S-1-5-32-554"}, {TRUE, "S-1-5-32-555"}, {TRUE, "S-1-5-32-556"},
/* 38 */ {FALSE, "S-1-5-21-12-23-34-45-56-500"}, {FALSE, "S-1-5-21-12-23-34-45-56-501"},
/* 40 */ {FALSE, "S-1-5-21-12-23-34-45-56-502"}, {FALSE, "S-1-5-21-12-23-34-45-56-512"},
/* 42 */ {FALSE, "S-1-5-21-12-23-34-45-56-513"}, {FALSE, "S-1-5-21-12-23-34-45-56-514"},
/* 44 */ {FALSE, "S-1-5-21-12-23-34-45-56-515"}, {FALSE, "S-1-5-21-12-23-34-45-56-516"},
/* 46 */ {FALSE, "S-1-5-21-12-23-34-45-56-517"}, {FALSE, "S-1-5-21-12-23-34-45-56-518"},
/* 48 */ {FALSE, "S-1-5-21-12-23-34-45-56-519"}, {FALSE, "S-1-5-21-12-23-34-45-56-520"},
/* 50 */ {FALSE, "S-1-5-21-12-23-34-45-56-553"},
/* Added in Windows Server 2003 */
/* 51 */ {TRUE, "S-1-5-64-10"}, {TRUE, "S-1-5-64-21"}, {TRUE, "S-1-5-64-14"},
/* 54 */ {TRUE, "S-1-5-15"}, {TRUE, "S-1-5-1000"}, {FALSE, "S-1-5-32-557"},
/* 57 */ {TRUE, "S-1-5-32-558"}, {TRUE, "S-1-5-32-559"}, {TRUE, "S-1-5-32-560"},
/* 60 */ {TRUE, "S-1-5-32-561"}, {TRUE, "S-1-5-32-562"},
/* Added in Windows Vista: */
/* 62 */ {TRUE, "S-1-5-32-568"},
/* 63 */ {TRUE, "S-1-5-17"}, {FALSE, "S-1-5-32-569"}, {TRUE, "S-1-16-0"},
/* 66 */ {TRUE, "S-1-16-4096"}, {TRUE, "S-1-16-8192"}, {TRUE, "S-1-16-12288"},
/* 69 */ {TRUE, "S-1-16-16384"}, {TRUE, "S-1-5-33"}, {TRUE, "S-1-3-4"},
/* 72 */ {FALSE, "S-1-5-21-12-23-34-45-56-571"}, {FALSE, "S-1-5-21-12-23-34-45-56-572"},
/* 74 */ {TRUE, "S-1-5-22"}, {FALSE, "S-1-5-21-12-23-34-45-56-521"}, {TRUE, "S-1-5-32-573"},
/* 77 */ {FALSE, "S-1-5-21-12-23-34-45-56-498"}, {TRUE, "S-1-5-32-574"}, {TRUE, "S-1-16-8448"},
/* 80 */ {FALSE, NULL}, {TRUE, "S-1-2-1"}, {TRUE, "S-1-5-65-1"}, {FALSE, NULL},
/* 84 */ {TRUE, "S-1-15-2-1"},
};
static void test_CreateWellKnownSid(void)
{
SID_IDENTIFIER_AUTHORITY ident = { SECURITY_NT_AUTHORITY };
PSID domainsid, sid;
DWORD size, error;
BOOL ret;
unsigned int i;
if (!pCreateWellKnownSid)
{
win_skip("CreateWellKnownSid not available\n");
return;
}
size = 0;
SetLastError(0xdeadbeef);
ret = pCreateWellKnownSid(WinInteractiveSid, NULL, NULL, &size);
error = GetLastError();
ok(!ret, "CreateWellKnownSid succeeded\n");
ok(error == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %u\n", error);
ok(size, "expected size > 0\n");
SetLastError(0xdeadbeef);
ret = pCreateWellKnownSid(WinInteractiveSid, NULL, NULL, &size);
error = GetLastError();
ok(!ret, "CreateWellKnownSid succeeded\n");
ok(error == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %u\n", error);
sid = HeapAlloc(GetProcessHeap(), 0, size);
ret = pCreateWellKnownSid(WinInteractiveSid, NULL, sid, &size);
ok(ret, "CreateWellKnownSid failed %u\n", GetLastError());
HeapFree(GetProcessHeap(), 0, sid);
/* a domain sid usually have three subauthorities but we test that CreateWellKnownSid doesn't check it */
AllocateAndInitializeSid(&ident, 6, SECURITY_NT_NON_UNIQUE, 12, 23, 34, 45, 56, 0, 0, &domainsid);
for (i = 0; i < ARRAY_SIZE(well_known_sid_values); i++)
{
const struct well_known_sid_value *value = &well_known_sid_values[i];
char sid_buffer[SECURITY_MAX_SID_SIZE];
LPSTR str;
DWORD cb;
if (value->sid_string == NULL)
continue;
/* some SIDs aren't implemented by all Windows versions - detect it */
cb = sizeof(sid_buffer);
if (!pCreateWellKnownSid(i, NULL, sid_buffer, &cb))
{
skip("Well known SID %u not implemented\n", i);
continue;
}
cb = sizeof(sid_buffer);
ok(pCreateWellKnownSid(i, value->without_domain ? NULL : domainsid, sid_buffer, &cb), "Couldn't create well known sid %u\n", i);
expect_eq(GetSidLengthRequired(*GetSidSubAuthorityCount(sid_buffer)), cb, DWORD, "%d");
ok(IsValidSid(sid_buffer), "The sid is not valid\n");
ok(ConvertSidToStringSidA(sid_buffer, &str), "Couldn't convert SID to string\n");
ok(strcmp(str, value->sid_string) == 0, "%d: SID mismatch - expected %s, got %s\n", i,
value->sid_string, str);
LocalFree(str);
if (value->without_domain)
{
char buf2[SECURITY_MAX_SID_SIZE];
cb = sizeof(buf2);
ok(pCreateWellKnownSid(i, domainsid, buf2, &cb), "Couldn't create well known sid %u with optional domain\n", i);
expect_eq(GetSidLengthRequired(*GetSidSubAuthorityCount(sid_buffer)), cb, DWORD, "%d");
ok(memcmp(buf2, sid_buffer, cb) == 0, "SID create with domain is different than without (%u)\n", i);
}
}
FreeSid(domainsid);
}
static void test_LookupAccountSid(void)
{
SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
CHAR accountA[MAX_PATH], domainA[MAX_PATH], usernameA[MAX_PATH];
DWORD acc_sizeA, dom_sizeA, user_sizeA;
DWORD real_acc_sizeA, real_dom_sizeA;
WCHAR accountW[MAX_PATH], domainW[MAX_PATH];
DWORD acc_sizeW, dom_sizeW;
DWORD real_acc_sizeW, real_dom_sizeW;
PSID pUsersSid = NULL;
SID_NAME_USE use;
BOOL ret;
DWORD error, size, cbti = 0;
MAX_SID max_sid;
CHAR *str_sidA;
int i;
HANDLE hToken;
PTOKEN_USER ptiUser = NULL;
/* native windows crashes if account size, domain size, or name use is NULL */
ret = AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &pUsersSid);
ok(ret || (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED),
"AllocateAndInitializeSid failed with error %d\n", GetLastError());
/* not running on NT so give up */
if (!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
return;
real_acc_sizeA = MAX_PATH;
real_dom_sizeA = MAX_PATH;
ret = LookupAccountSidA(NULL, pUsersSid, accountA, &real_acc_sizeA, domainA, &real_dom_sizeA, &use);
ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
/* try NULL account */
acc_sizeA = MAX_PATH;
dom_sizeA = MAX_PATH;
ret = LookupAccountSidA(NULL, pUsersSid, NULL, &acc_sizeA, domainA, &dom_sizeA, &use);
ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
/* try NULL domain */
acc_sizeA = MAX_PATH;
dom_sizeA = MAX_PATH;
ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, NULL, &dom_sizeA, &use);
ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
/* try a small account buffer */
acc_sizeA = 1;
dom_sizeA = MAX_PATH;
accountA[0] = 0;
ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
ok(!ret, "LookupAccountSidA() Expected FALSE got TRUE\n");
ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"LookupAccountSidA() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
/* try a 0 sized account buffer */
acc_sizeA = 0;
dom_sizeA = MAX_PATH;
accountA[0] = 0;
LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
/* this can fail or succeed depending on OS version but the size will always be returned */
ok(acc_sizeA == real_acc_sizeA + 1,
"LookupAccountSidA() Expected acc_size = %u, got %u\n",
real_acc_sizeA + 1, acc_sizeA);
/* try a 0 sized account buffer */
acc_sizeA = 0;
dom_sizeA = MAX_PATH;
LookupAccountSidA(NULL, pUsersSid, NULL, &acc_sizeA, domainA, &dom_sizeA, &use);
/* this can fail or succeed depending on OS version but the size will always be returned */
ok(acc_sizeA == real_acc_sizeA + 1,
"LookupAccountSid() Expected acc_size = %u, got %u\n",
real_acc_sizeA + 1, acc_sizeA);
/* try a small domain buffer */
dom_sizeA = 1;
acc_sizeA = MAX_PATH;
accountA[0] = 0;
ret = LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
ok(!ret, "LookupAccountSidA() Expected FALSE got TRUE\n");
ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"LookupAccountSidA() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
/* try a 0 sized domain buffer */
dom_sizeA = 0;
acc_sizeA = MAX_PATH;
accountA[0] = 0;
LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
/* this can fail or succeed depending on OS version but the size will always be returned */
ok(dom_sizeA == real_dom_sizeA + 1,
"LookupAccountSidA() Expected dom_size = %u, got %u\n",
real_dom_sizeA + 1, dom_sizeA);
/* try a 0 sized domain buffer */
dom_sizeA = 0;
acc_sizeA = MAX_PATH;
LookupAccountSidA(NULL, pUsersSid, accountA, &acc_sizeA, NULL, &dom_sizeA, &use);
/* this can fail or succeed depending on OS version but the size will always be returned */
ok(dom_sizeA == real_dom_sizeA + 1,
"LookupAccountSidA() Expected dom_size = %u, got %u\n",
real_dom_sizeA + 1, dom_sizeA);
real_acc_sizeW = MAX_PATH;
real_dom_sizeW = MAX_PATH;
ret = LookupAccountSidW(NULL, pUsersSid, accountW, &real_acc_sizeW, domainW, &real_dom_sizeW, &use);
ok(ret, "LookupAccountSidW() Expected TRUE, got FALSE\n");
/* try an invalid system name */
real_acc_sizeA = MAX_PATH;
real_dom_sizeA = MAX_PATH;
ret = LookupAccountSidA("deepthought", pUsersSid, accountA, &real_acc_sizeA, domainA, &real_dom_sizeA, &use);
ok(!ret, "LookupAccountSidA() Expected FALSE got TRUE\n");
ok(GetLastError() == RPC_S_SERVER_UNAVAILABLE || GetLastError() == RPC_S_INVALID_NET_ADDR /* Vista */,
"LookupAccountSidA() Expected RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR, got %u\n", GetLastError());
/* native windows crashes if domainW or accountW is NULL */
/* try a small account buffer */
acc_sizeW = 1;
dom_sizeW = MAX_PATH;
accountW[0] = 0;
ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
ok(!ret, "LookupAccountSidW() Expected FALSE got TRUE\n");
ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"LookupAccountSidW() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
/* try a 0 sized account buffer */
acc_sizeW = 0;
dom_sizeW = MAX_PATH;
accountW[0] = 0;
LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
/* this can fail or succeed depending on OS version but the size will always be returned */
ok(acc_sizeW == real_acc_sizeW + 1,
"LookupAccountSidW() Expected acc_size = %u, got %u\n",
real_acc_sizeW + 1, acc_sizeW);
/* try a 0 sized account buffer */
acc_sizeW = 0;
dom_sizeW = MAX_PATH;
LookupAccountSidW(NULL, pUsersSid, NULL, &acc_sizeW, domainW, &dom_sizeW, &use);
/* this can fail or succeed depending on OS version but the size will always be returned */
ok(acc_sizeW == real_acc_sizeW + 1,
"LookupAccountSidW() Expected acc_size = %u, got %u\n",
real_acc_sizeW + 1, acc_sizeW);
/* try a small domain buffer */
dom_sizeW = 1;
acc_sizeW = MAX_PATH;
accountW[0] = 0;
ret = LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
ok(!ret, "LookupAccountSidW() Expected FALSE got TRUE\n");
ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"LookupAccountSidW() Expected ERROR_NOT_ENOUGH_MEMORY, got %u\n", GetLastError());
/* try a 0 sized domain buffer */
dom_sizeW = 0;
acc_sizeW = MAX_PATH;
accountW[0] = 0;
LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, domainW, &dom_sizeW, &use);
/* this can fail or succeed depending on OS version but the size will always be returned */
ok(dom_sizeW == real_dom_sizeW + 1,
"LookupAccountSidW() Expected dom_size = %u, got %u\n",
real_dom_sizeW + 1, dom_sizeW);
/* try a 0 sized domain buffer */
dom_sizeW = 0;
acc_sizeW = MAX_PATH;
LookupAccountSidW(NULL, pUsersSid, accountW, &acc_sizeW, NULL, &dom_sizeW, &use);
/* this can fail or succeed depending on OS version but the size will always be returned */
ok(dom_sizeW == real_dom_sizeW + 1,
"LookupAccountSidW() Expected dom_size = %u, got %u\n",
real_dom_sizeW + 1, dom_sizeW);
acc_sizeW = dom_sizeW = use = 0;
SetLastError(0xdeadbeef);
ret = LookupAccountSidW(NULL, pUsersSid, NULL, &acc_sizeW, NULL, &dom_sizeW, &use);
error = GetLastError();
ok(!ret, "LookupAccountSidW failed %u\n", GetLastError());
ok(error == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %u\n", error);
ok(acc_sizeW, "expected non-zero account size\n");
ok(dom_sizeW, "expected non-zero domain size\n");
ok(!use, "expected zero use %u\n", use);
FreeSid(pUsersSid);
/* Test LookupAccountSid with Sid retrieved from token information.
This assumes this process is running under the account of the current user.*/
ret = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY|TOKEN_DUPLICATE, &hToken);
ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
ret = GetTokenInformation(hToken, TokenUser, NULL, 0, &cbti);
ok(!ret, "GetTokenInformation failed with error %d\n", GetLastError());
ptiUser = HeapAlloc(GetProcessHeap(), 0, cbti);
if (GetTokenInformation(hToken, TokenUser, ptiUser, cbti, &cbti))
{
acc_sizeA = dom_sizeA = MAX_PATH;
ret = LookupAccountSidA(NULL, ptiUser->User.Sid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use);
ok(ret, "LookupAccountSidA() Expected TRUE, got FALSE\n");
user_sizeA = MAX_PATH;
ret = GetUserNameA(usernameA , &user_sizeA);
ok(ret, "GetUserNameA() Expected TRUE, got FALSE\n");
ok(lstrcmpA(usernameA, accountA) == 0, "LookupAccountSidA() Expected account name: %s got: %s\n", usernameA, accountA );
}
HeapFree(GetProcessHeap(), 0, ptiUser);
if (pCreateWellKnownSid)
{
trace("Well Known SIDs:\n");
for (i = 0; i <= 60; i++)
{
size = SECURITY_MAX_SID_SIZE;
if (pCreateWellKnownSid(i, NULL, &max_sid.sid, &size))
{
if (ConvertSidToStringSidA(&max_sid.sid, &str_sidA))
{
acc_sizeA = MAX_PATH;
dom_sizeA = MAX_PATH;
if (LookupAccountSidA(NULL, &max_sid.sid, accountA, &acc_sizeA, domainA, &dom_sizeA, &use))
trace(" %d: %s %s\\%s %d\n", i, str_sidA, domainA, accountA, use);
LocalFree(str_sidA);
}
}
else
{
if (GetLastError() != ERROR_INVALID_PARAMETER)
trace(" CreateWellKnownSid(%d) failed: %d\n", i, GetLastError());
else
trace(" %d: not supported\n", i);
}
}
pLsaQueryInformationPolicy = (void *)GetProcAddress( hmod, "LsaQueryInformationPolicy");
pLsaOpenPolicy = (void *)GetProcAddress( hmod, "LsaOpenPolicy");
pLsaFreeMemory = (void *)GetProcAddress( hmod, "LsaFreeMemory");
pLsaClose = (void *)GetProcAddress( hmod, "LsaClose");
if (pLsaQueryInformationPolicy && pLsaOpenPolicy && pLsaFreeMemory && pLsaClose)
{
NTSTATUS status;
LSA_HANDLE handle;
LSA_OBJECT_ATTRIBUTES object_attributes;
ZeroMemory(&object_attributes, sizeof(object_attributes));
object_attributes.Length = sizeof(object_attributes);
status = pLsaOpenPolicy( NULL, &object_attributes, POLICY_ALL_ACCESS, &handle);
ok(status == STATUS_SUCCESS || status == STATUS_ACCESS_DENIED,
"LsaOpenPolicy(POLICY_ALL_ACCESS) returned 0x%08x\n", status);
/* try a more restricted access mask if necessary */
if (status == STATUS_ACCESS_DENIED) {
trace("LsaOpenPolicy(POLICY_ALL_ACCESS) failed, trying POLICY_VIEW_LOCAL_INFORMATION\n");
status = pLsaOpenPolicy( NULL, &object_attributes, POLICY_VIEW_LOCAL_INFORMATION, &handle);
ok(status == STATUS_SUCCESS, "LsaOpenPolicy(POLICY_VIEW_LOCAL_INFORMATION) returned 0x%08x\n", status);
}
if (status == STATUS_SUCCESS)
{
PPOLICY_ACCOUNT_DOMAIN_INFO info;
status = pLsaQueryInformationPolicy(handle, PolicyAccountDomainInformation, (PVOID*)&info);
ok(status == STATUS_SUCCESS, "LsaQueryInformationPolicy() failed, returned 0x%08x\n", status);
if (status == STATUS_SUCCESS)
{
ok(info->DomainSid!=0, "LsaQueryInformationPolicy(PolicyAccountDomainInformation) missing SID\n");
if (info->DomainSid)
{
int count = *GetSidSubAuthorityCount(info->DomainSid);
CopySid(GetSidLengthRequired(count), &max_sid, info->DomainSid);
test_sid_str((PSID)&max_sid.sid);
max_sid.sid.SubAuthority[count] = DOMAIN_USER_RID_ADMIN;
max_sid.sid.SubAuthorityCount = count + 1;
test_sid_str((PSID)&max_sid.sid);
max_sid.sid.SubAuthority[count] = DOMAIN_USER_RID_GUEST;
test_sid_str((PSID)&max_sid.sid);
max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_ADMINS;
test_sid_str((PSID)&max_sid.sid);
max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_USERS;
test_sid_str((PSID)&max_sid.sid);
max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_GUESTS;
test_sid_str((PSID)&max_sid.sid);
max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_COMPUTERS;
test_sid_str((PSID)&max_sid.sid);
max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_CONTROLLERS;
test_sid_str((PSID)&max_sid.sid);
max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_CERT_ADMINS;
test_sid_str((PSID)&max_sid.sid);
max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_SCHEMA_ADMINS;
test_sid_str((PSID)&max_sid.sid);
max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_ENTERPRISE_ADMINS;
test_sid_str((PSID)&max_sid.sid);
max_sid.sid.SubAuthority[count] = DOMAIN_GROUP_RID_POLICY_ADMINS;
test_sid_str((PSID)&max_sid.sid);
max_sid.sid.SubAuthority[count] = DOMAIN_ALIAS_RID_RAS_SERVERS;
test_sid_str((PSID)&max_sid.sid);
max_sid.sid.SubAuthority[count] = 1000; /* first user account */
test_sid_str((PSID)&max_sid.sid);
}
pLsaFreeMemory((LPVOID)info);
}
status = pLsaClose(handle);
ok(status == STATUS_SUCCESS, "LsaClose() failed, returned 0x%08x\n", status);
}
}
}
}
static BOOL get_sid_info(PSID psid, LPSTR *user, LPSTR *dom)
{
static CHAR account[UNLEN + 1];
static CHAR domain[UNLEN + 1];
DWORD size, dom_size;
SID_NAME_USE use;
*user = account;
*dom = domain;
size = dom_size = UNLEN + 1;
account[0] = '\0';
domain[0] = '\0';
SetLastError(0xdeadbeef);
return LookupAccountSidA(NULL, psid, account, &size, domain, &dom_size, &use);
}
static void check_wellknown_name(const char* name, WELL_KNOWN_SID_TYPE result)
{
SID_IDENTIFIER_AUTHORITY ident = { SECURITY_NT_AUTHORITY };
PSID domainsid = NULL;
char wk_sid[SECURITY_MAX_SID_SIZE];
DWORD cb;
DWORD sid_size, domain_size;
SID_NAME_USE sid_use;
LPSTR domain, account, sid_domain, wk_domain, wk_account;
PSID psid;
BOOL ret ,ret2;
sid_size = 0;
domain_size = 0;
ret = LookupAccountNameA(NULL, name, NULL, &sid_size, NULL, &domain_size, &sid_use);
ok(!ret, " %s Should have failed to lookup account name\n", name);
psid = HeapAlloc(GetProcessHeap(),0,sid_size);
domain = HeapAlloc(GetProcessHeap(),0,domain_size);
ret = LookupAccountNameA(NULL, name, psid, &sid_size, domain, &domain_size, &sid_use);
if (!result)
{
ok(!ret, " %s Should have failed to lookup account name\n",name);
goto cleanup;
}
AllocateAndInitializeSid(&ident, 6, SECURITY_NT_NON_UNIQUE, 12, 23, 34, 45, 56, 0, 0, &domainsid);
cb = sizeof(wk_sid);
if (!pCreateWellKnownSid(result, domainsid, wk_sid, &cb))
{
win_skip("SID %i is not available on the system\n",result);
goto cleanup;
}
ret2 = get_sid_info(wk_sid, &wk_account, &wk_domain);
if (!ret2 && GetLastError() == ERROR_NONE_MAPPED)
{
win_skip("CreateWellKnownSid() succeeded but the account '%s' is not present (W2K)\n", name);
goto cleanup;
}
get_sid_info(psid, &account, &sid_domain);
ok(ret, "Failed to lookup account name %s\n",name);
ok(sid_size != 0, "sid_size was zero\n");
ok(EqualSid(psid,wk_sid),"%s Sid %s fails to match well known sid %s!\n",
name, debugstr_sid(psid), debugstr_sid(wk_sid));
ok(!lstrcmpA(account, wk_account), "Expected %s , got %s\n", account, wk_account);
ok(!lstrcmpA(domain, wk_domain), "Expected %s, got %s\n", wk_domain, domain);
ok(sid_use == SidTypeWellKnownGroup , "Expected Use (5), got %d\n", sid_use);
cleanup:
FreeSid(domainsid);
HeapFree(GetProcessHeap(),0,psid);
HeapFree(GetProcessHeap(),0,domain);
}
static void test_LookupAccountName(void)
{
DWORD sid_size, domain_size, user_size;
DWORD sid_save, domain_save;
CHAR user_name[UNLEN + 1];
CHAR computer_name[UNLEN + 1];
SID_NAME_USE sid_use;
LPSTR domain, account, sid_dom;
PSID psid;
BOOL ret;
/* native crashes if (assuming all other parameters correct):
* - peUse is NULL
* - Sid is NULL and cbSid is > 0
* - cbSid or cchReferencedDomainName are NULL
* - ReferencedDomainName is NULL and cchReferencedDomainName is the correct size
*/
user_size = UNLEN + 1;
SetLastError(0xdeadbeef);
ret = GetUserNameA(user_name, &user_size);
ok(ret, "Failed to get user name : %d\n", GetLastError());
/* get sizes */
sid_size = 0;
domain_size = 0;
sid_use = 0xcafebabe;
SetLastError(0xdeadbeef);
ret = LookupAccountNameA(NULL, user_name, NULL, &sid_size, NULL, &domain_size, &sid_use);
if(!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
{
win_skip("LookupAccountNameA is not implemented\n");
return;
}
ok(!ret, "Expected 0, got %d\n", ret);
ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
ok(sid_size != 0, "Expected non-zero sid size\n");
ok(domain_size != 0, "Expected non-zero domain size\n");
ok(sid_use == (SID_NAME_USE)0xcafebabe, "Expected 0xcafebabe, got %d\n", sid_use);
sid_save = sid_size;
domain_save = domain_size;
psid = HeapAlloc(GetProcessHeap(), 0, sid_size);
domain = HeapAlloc(GetProcessHeap(), 0, domain_size);
/* try valid account name */
ret = LookupAccountNameA(NULL, user_name, psid, &sid_size, domain, &domain_size, &sid_use);
get_sid_info(psid, &account, &sid_dom);
ok(ret, "Failed to lookup account name\n");
ok(sid_size == GetLengthSid(psid), "Expected %d, got %d\n", GetLengthSid(psid), sid_size);
ok(!lstrcmpA(account, user_name), "Expected %s, got %s\n", user_name, account);
ok(!lstrcmpiA(domain, sid_dom), "Expected %s, got %s\n", sid_dom, domain);
ok(domain_size == domain_save - 1, "Expected %d, got %d\n", domain_save - 1, domain_size);
ok(strlen(domain) == domain_size, "Expected %d, got %d\n", lstrlenA(domain), domain_size);
ok(sid_use == SidTypeUser, "Expected SidTypeUser (%d), got %d\n", SidTypeUser, sid_use);
domain_size = domain_save;
sid_size = sid_save;
if (PRIMARYLANGID(GetSystemDefaultLangID()) != LANG_ENGLISH)
{
skip("Non-English locale (test with hardcoded 'Everyone')\n");
}
else
{
ret = LookupAccountNameA(NULL, "Everyone", psid, &sid_size, domain, &domain_size, &sid_use);
get_sid_info(psid, &account, &sid_dom);
ok(ret, "Failed to lookup account name\n");
ok(sid_size != 0, "sid_size was zero\n");
ok(!lstrcmpA(account, "Everyone"), "Expected Everyone, got %s\n", account);
ok(!lstrcmpiA(domain, sid_dom), "Expected %s, got %s\n", sid_dom, domain);
ok(domain_size == 0, "Expected 0, got %d\n", domain_size);
ok(strlen(domain) == domain_size, "Expected %d, got %d\n", lstrlenA(domain), domain_size);
ok(sid_use == SidTypeWellKnownGroup, "Expected SidTypeWellKnownGroup (%d), got %d\n", SidTypeWellKnownGroup, sid_use);
domain_size = domain_save;
}
/* NULL Sid with zero sid size */
SetLastError(0xdeadbeef);
sid_size = 0;
ret = LookupAccountNameA(NULL, user_name, NULL, &sid_size, domain, &domain_size, &sid_use);
ok(!ret, "Expected 0, got %d\n", ret);
ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
ok(sid_size == sid_save, "Expected %d, got %d\n", sid_save, sid_size);
ok(domain_size == domain_save, "Expected %d, got %d\n", domain_save, domain_size);
/* try cchReferencedDomainName - 1 */
SetLastError(0xdeadbeef);
domain_size--;
ret = LookupAccountNameA(NULL, user_name, NULL, &sid_size, domain, &domain_size, &sid_use);
ok(!ret, "Expected 0, got %d\n", ret);
ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
ok(sid_size == sid_save, "Expected %d, got %d\n", sid_save, sid_size);
ok(domain_size == domain_save, "Expected %d, got %d\n", domain_save, domain_size);
/* NULL ReferencedDomainName with zero domain name size */
SetLastError(0xdeadbeef);
domain_size = 0;
ret = LookupAccountNameA(NULL, user_name, psid, &sid_size, NULL, &domain_size, &sid_use);
ok(!ret, "Expected 0, got %d\n", ret);
ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
ok(sid_size == sid_save, "Expected %d, got %d\n", sid_save, sid_size);
ok(domain_size == domain_save, "Expected %d, got %d\n", domain_save, domain_size);
HeapFree(GetProcessHeap(), 0, psid);
HeapFree(GetProcessHeap(), 0, domain);
/* get sizes for NULL account name */
sid_size = 0;
domain_size = 0;
sid_use = 0xcafebabe;
SetLastError(0xdeadbeef);
ret = LookupAccountNameA(NULL, NULL, NULL, &sid_size, NULL, &domain_size, &sid_use);
if (!ret && GetLastError() == ERROR_NONE_MAPPED)
win_skip("NULL account name doesn't work on NT4\n");
else
{
ok(!ret, "Expected 0, got %d\n", ret);
ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
ok(sid_size != 0, "Expected non-zero sid size\n");
ok(domain_size != 0, "Expected non-zero domain size\n");
ok(sid_use == (SID_NAME_USE)0xcafebabe, "Expected 0xcafebabe, got %d\n", sid_use);
psid = HeapAlloc(GetProcessHeap(), 0, sid_size);
domain = HeapAlloc(GetProcessHeap(), 0, domain_size);
/* try NULL account name */
ret = LookupAccountNameA(NULL, NULL, psid, &sid_size, domain, &domain_size, &sid_use);
get_sid_info(psid, &account, &sid_dom);
ok(ret, "Failed to lookup account name\n");
/* Using a fixed string will not work on different locales */
ok(!lstrcmpiA(account, domain),
"Got %s for account and %s for domain, these should be the same\n", account, domain);
ok(sid_use == SidTypeDomain, "Expected SidTypeDomain (%d), got %d\n", SidTypeDomain, sid_use);
HeapFree(GetProcessHeap(), 0, psid);
HeapFree(GetProcessHeap(), 0, domain);
}
/* try an invalid account name */
SetLastError(0xdeadbeef);
sid_size = 0;
domain_size = 0;
ret = LookupAccountNameA(NULL, "oogabooga", NULL, &sid_size, NULL, &domain_size, &sid_use);
ok(!ret, "Expected 0, got %d\n", ret);
ok(GetLastError() == ERROR_NONE_MAPPED ||
broken(GetLastError() == ERROR_TRUSTED_RELATIONSHIP_FAILURE),
"Expected ERROR_NONE_MAPPED, got %d\n", GetLastError());
ok(sid_size == 0, "Expected 0, got %d\n", sid_size);
ok(domain_size == 0, "Expected 0, got %d\n", domain_size);
/* try an invalid system name */
SetLastError(0xdeadbeef);
sid_size = 0;
domain_size = 0;
ret = LookupAccountNameA("deepthought", NULL, NULL, &sid_size, NULL, &domain_size, &sid_use);
ok(!ret, "Expected 0, got %d\n", ret);
ok(GetLastError() == RPC_S_SERVER_UNAVAILABLE || GetLastError() == RPC_S_INVALID_NET_ADDR /* Vista */,
"Expected RPC_S_SERVER_UNAVAILABLE or RPC_S_INVALID_NET_ADDR, got %d\n", GetLastError());
ok(sid_size == 0, "Expected 0, got %d\n", sid_size);
ok(domain_size == 0, "Expected 0, got %d\n", domain_size);
/* try with the computer name as the account name */
domain_size = sizeof(computer_name);
GetComputerNameA(computer_name, &domain_size);
sid_size = 0;
domain_size = 0;
ret = LookupAccountNameA(NULL, computer_name, NULL, &sid_size, NULL, &domain_size, &sid_use);
ok(!ret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER ||
GetLastError() == ERROR_NONE_MAPPED /* in a domain */ ||
broken(GetLastError() == ERROR_TRUSTED_DOMAIN_FAILURE) ||
broken(GetLastError() == ERROR_TRUSTED_RELATIONSHIP_FAILURE)),
"LookupAccountNameA failed: %d\n", GetLastError());
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
psid = HeapAlloc(GetProcessHeap(), 0, sid_size);
domain = HeapAlloc(GetProcessHeap(), 0, domain_size);
ret = LookupAccountNameA(NULL, computer_name, psid, &sid_size, domain, &domain_size, &sid_use);
ok(ret, "LookupAccountNameA failed: %d\n", GetLastError());
ok(sid_use == SidTypeDomain ||
(sid_use == SidTypeUser && ! strcmp(computer_name, user_name)), "expected SidTypeDomain for %s, got %d\n", computer_name, sid_use);
HeapFree(GetProcessHeap(), 0, domain);
HeapFree(GetProcessHeap(), 0, psid);
}
/* Well Known names */
if (!pCreateWellKnownSid)
{
win_skip("CreateWellKnownSid not available\n");
return;
}
if (PRIMARYLANGID(GetSystemDefaultLangID()) != LANG_ENGLISH)
{
skip("Non-English locale (skipping well known name creation tests)\n");
return;
}
check_wellknown_name("LocalService", WinLocalServiceSid);
check_wellknown_name("Local Service", WinLocalServiceSid);
/* 2 spaces */
check_wellknown_name("Local Service", 0);
check_wellknown_name("NetworkService", WinNetworkServiceSid);
check_wellknown_name("Network Service", WinNetworkServiceSid);
/* example of some names where the spaces are not optional */
check_wellknown_name("Terminal Server User", WinTerminalServerSid);
check_wellknown_name("TerminalServer User", 0);
check_wellknown_name("TerminalServerUser", 0);
check_wellknown_name("Terminal ServerUser", 0);
check_wellknown_name("enterprise domain controllers",WinEnterpriseControllersSid);
check_wellknown_name("enterprisedomain controllers", 0);
check_wellknown_name("enterprise domaincontrollers", 0);
check_wellknown_name("enterprisedomaincontrollers", 0);
/* case insensitivity */
check_wellknown_name("lOCAlServICE", WinLocalServiceSid);
/* fully qualified account names */
check_wellknown_name("NT AUTHORITY\\LocalService", WinLocalServiceSid);
check_wellknown_name("nt authority\\Network Service", WinNetworkServiceSid);
check_wellknown_name("nt authority test\\Network Service", 0);
check_wellknown_name("Dummy\\Network Service", 0);
check_wellknown_name("ntauthority\\Network Service", 0);
}
static void test_security_descriptor(void)
{
SECURITY_DESCRIPTOR sd, *sd_rel, *sd_rel2, *sd_abs;
char buf[8192];
DWORD size, size_dacl, size_sacl, size_owner, size_group;
BOOL isDefault, isPresent, ret;
PACL pacl, dacl, sacl;
PSID psid, owner, group;
SetLastError(0xdeadbeef);
ret = InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
if (ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
{
win_skip("InitializeSecurityDescriptor is not implemented\n");
return;
}
ok(GetSecurityDescriptorOwner(&sd, &psid, &isDefault), "GetSecurityDescriptorOwner failed\n");
expect_eq(psid, NULL, PSID, "%p");
expect_eq(isDefault, FALSE, BOOL, "%d");
sd.Control |= SE_DACL_PRESENT | SE_SACL_PRESENT;
SetLastError(0xdeadbeef);
size = 5;
expect_eq(MakeSelfRelativeSD(&sd, buf, &size), FALSE, BOOL, "%d");
expect_eq(GetLastError(), ERROR_INSUFFICIENT_BUFFER, DWORD, "%u");
ok(size > 5, "Size not increased\n");
if (size <= 8192)
{
expect_eq(MakeSelfRelativeSD(&sd, buf, &size), TRUE, BOOL, "%d");
ok(GetSecurityDescriptorOwner(&sd, &psid, &isDefault), "GetSecurityDescriptorOwner failed\n");
expect_eq(psid, NULL, PSID, "%p");
expect_eq(isDefault, FALSE, BOOL, "%d");
ok(GetSecurityDescriptorGroup(&sd, &psid, &isDefault), "GetSecurityDescriptorGroup failed\n");
expect_eq(psid, NULL, PSID, "%p");
expect_eq(isDefault, FALSE, BOOL, "%d");
ok(GetSecurityDescriptorDacl(&sd, &isPresent, &pacl, &isDefault), "GetSecurityDescriptorDacl failed\n");
expect_eq(isPresent, TRUE, BOOL, "%d");
expect_eq(psid, NULL, PSID, "%p");
expect_eq(isDefault, FALSE, BOOL, "%d");
ok(GetSecurityDescriptorSacl(&sd, &isPresent, &pacl, &isDefault), "GetSecurityDescriptorSacl failed\n");
expect_eq(isPresent, TRUE, BOOL, "%d");
expect_eq(psid, NULL, PSID, "%p");
expect_eq(isDefault, FALSE, BOOL, "%d");
}
ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
"O:SYG:S-1-5-21-93476-23408-4576D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)"
"(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)"
"(AU;NPSA;0x12019f;;;SU)", SDDL_REVISION_1, (void **)&sd_rel, NULL);
ok(ret, "got %u\n", GetLastError());
size = 0;
ret = MakeSelfRelativeSD(sd_rel, NULL, &size);
todo_wine ok(!ret && GetLastError() == ERROR_BAD_DESCRIPTOR_FORMAT, "got %u\n", GetLastError());
/* convert to absolute form */
size = size_dacl = size_sacl = size_owner = size_group = 0;
ret = MakeAbsoluteSD(sd_rel, NULL, &size, NULL, &size_dacl, NULL, &size_sacl, NULL, &size_owner, NULL,
&size_group);
ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "got %u\n", GetLastError());
sd_abs = HeapAlloc(GetProcessHeap(), 0, size + size_dacl + size_sacl + size_owner + size_group);
dacl = (PACL)(sd_abs + 1);
sacl = (PACL)((char *)dacl + size_dacl);
owner = (PSID)((char *)sacl + size_sacl);
group = (PSID)((char *)owner + size_owner);
ret = MakeAbsoluteSD(sd_rel, sd_abs, &size, dacl, &size_dacl, sacl, &size_sacl, owner, &size_owner,
group, &size_group);
ok(ret, "got %u\n", GetLastError());
size = 0;
ret = MakeSelfRelativeSD(sd_abs, NULL, &size);
ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "got %u\n", GetLastError());
ok(size == 184, "got %u\n", size);
size += 4;
sd_rel2 = HeapAlloc(GetProcessHeap(), 0, size);
ret = MakeSelfRelativeSD(sd_abs, sd_rel2, &size);
ok(ret, "got %u\n", GetLastError());
ok(size == 188, "got %u\n", size);
HeapFree(GetProcessHeap(), 0, sd_abs);
HeapFree(GetProcessHeap(), 0, sd_rel2);
LocalFree(sd_rel);
}
#define TEST_GRANTED_ACCESS(a,b) test_granted_access(a,b,0,__LINE__)
#define TEST_GRANTED_ACCESS2(a,b,c) test_granted_access(a,b,c,__LINE__)
static void test_granted_access(HANDLE handle, ACCESS_MASK access,
ACCESS_MASK alt, int line)
{
OBJECT_BASIC_INFORMATION obj_info;
NTSTATUS status;
if (!pNtQueryObject)
{
skip_(__FILE__, line)("Not NT platform - skipping tests\n");
return;
}
status = pNtQueryObject( handle, ObjectBasicInformation, &obj_info,
sizeof(obj_info), NULL );
ok_(__FILE__, line)(!status, "NtQueryObject with err: %08x\n", status);
if (alt)
ok_(__FILE__, line)(obj_info.GrantedAccess == access ||
obj_info.GrantedAccess == alt, "Granted access should be 0x%08x "
"or 0x%08x, instead of 0x%08x\n", access, alt, obj_info.GrantedAccess);
else
ok_(__FILE__, line)(obj_info.GrantedAccess == access, "Granted access should "
"be 0x%08x, instead of 0x%08x\n", access, obj_info.GrantedAccess);
}
#define CHECK_SET_SECURITY(o,i,e) \
do{ \
BOOL res_; \
DWORD err; \
SetLastError( 0xdeadbeef ); \
res_ = SetKernelObjectSecurity( o, i, SecurityDescriptor ); \
err = GetLastError(); \
if (e == ERROR_SUCCESS) \
ok(res_, "SetKernelObjectSecurity failed with %d\n", err); \
else \
ok(!res_ && err == e, "SetKernelObjectSecurity should have failed " \
"with %s, instead of %d\n", #e, err); \
}while(0)
static void test_process_security(void)
{
BOOL res;
PTOKEN_USER user;
PTOKEN_OWNER owner;
PTOKEN_PRIMARY_GROUP group;
PSID AdminSid = NULL, UsersSid = NULL, UserSid = NULL;
PACL Acl = NULL, ThreadAcl = NULL;
SECURITY_DESCRIPTOR *SecurityDescriptor = NULL, *ThreadSecurityDescriptor = NULL;
char buffer[MAX_PATH], account[MAX_PATH], domain[MAX_PATH];
PROCESS_INFORMATION info;
STARTUPINFOA startup;
SECURITY_ATTRIBUTES psa, tsa;
HANDLE token, event;
DWORD size, acc_size, dom_size, ret;
SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
PSID EveryoneSid = NULL;
SID_NAME_USE use;
Acl = HeapAlloc(GetProcessHeap(), 0, 256);
res = InitializeAcl(Acl, 256, ACL_REVISION);
if (!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
{
win_skip("ACLs not implemented - skipping tests\n");
HeapFree(GetProcessHeap(), 0, Acl);
return;
}
ok(res, "InitializeAcl failed with error %d\n", GetLastError());
res = AllocateAndInitializeSid( &SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &EveryoneSid);
ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
/* get owner from the token we might be running as a user not admin */
res = OpenProcessToken( GetCurrentProcess(), MAXIMUM_ALLOWED, &token );
ok(res, "OpenProcessToken failed with error %d\n", GetLastError());
if (!res)
{
HeapFree(GetProcessHeap(), 0, Acl);
return;
}
res = GetTokenInformation( token, TokenOwner, NULL, 0, &size );
ok(!res, "Expected failure, got %d\n", res);
ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
owner = HeapAlloc(GetProcessHeap(), 0, size);
res = GetTokenInformation( token, TokenOwner, owner, size, &size );
ok(res, "GetTokenInformation failed with error %d\n", GetLastError());
AdminSid = owner->Owner;
test_sid_str(AdminSid);
res = GetTokenInformation( token, TokenPrimaryGroup, NULL, 0, &size );
ok(!res, "Expected failure, got %d\n", res);
ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
group = HeapAlloc(GetProcessHeap(), 0, size);
res = GetTokenInformation( token, TokenPrimaryGroup, group, size, &size );
ok(res, "GetTokenInformation failed with error %d\n", GetLastError());
UsersSid = group->PrimaryGroup;
test_sid_str(UsersSid);
acc_size = sizeof(account);
dom_size = sizeof(domain);
ret = LookupAccountSidA( NULL, UsersSid, account, &acc_size, domain, &dom_size, &use );
ok(ret, "LookupAccountSid failed with %d\n", ret);
todo_wine ok(use == SidTypeGroup, "expect SidTypeGroup, got %d\n", use);
if (PRIMARYLANGID(GetSystemDefaultLangID()) != LANG_ENGLISH)
skip("Non-English locale (test with hardcoded 'None')\n");
else
todo_wine ok(!strcmp(account, "None"), "expect None, got %s\n", account);
res = GetTokenInformation( token, TokenUser, NULL, 0, &size );
ok(!res, "Expected failure, got %d\n", res);
ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
user = HeapAlloc(GetProcessHeap(), 0, size);
res = GetTokenInformation( token, TokenUser, user, size, &size );
ok(res, "GetTokenInformation failed with error %d\n", GetLastError());
UserSid = user->User.Sid;
test_sid_str(UserSid);
ok(EqualPrefixSid(UsersSid, UserSid), "TokenPrimaryGroup Sid and TokenUser Sid don't match.\n");
CloseHandle( token );
if (!res)
{
HeapFree(GetProcessHeap(), 0, group);
HeapFree(GetProcessHeap(), 0, owner);
HeapFree(GetProcessHeap(), 0, user);
HeapFree(GetProcessHeap(), 0, Acl);
return;
}
res = AddAccessDeniedAce(Acl, ACL_REVISION, PROCESS_VM_READ, AdminSid);
ok(res, "AddAccessDeniedAce failed with error %d\n", GetLastError());
res = AddAccessAllowedAce(Acl, ACL_REVISION, PROCESS_ALL_ACCESS, AdminSid);
ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
SecurityDescriptor = HeapAlloc(GetProcessHeap(), 0, SECURITY_DESCRIPTOR_MIN_LENGTH);
res = InitializeSecurityDescriptor(SecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
ok(res, "InitializeSecurityDescriptor failed with error %d\n", GetLastError());
event = CreateEventA( NULL, TRUE, TRUE, "test_event" );
ok(event != NULL, "CreateEvent %d\n", GetLastError());
SecurityDescriptor->Revision = 0;
CHECK_SET_SECURITY( event, OWNER_SECURITY_INFORMATION, ERROR_UNKNOWN_REVISION );
SecurityDescriptor->Revision = SECURITY_DESCRIPTOR_REVISION;
CHECK_SET_SECURITY( event, OWNER_SECURITY_INFORMATION, ERROR_INVALID_SECURITY_DESCR );
CHECK_SET_SECURITY( event, GROUP_SECURITY_INFORMATION, ERROR_INVALID_SECURITY_DESCR );
CHECK_SET_SECURITY( event, SACL_SECURITY_INFORMATION, ERROR_ACCESS_DENIED );
CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
/* NULL DACL is valid and means that everyone has access */
SecurityDescriptor->Control |= SE_DACL_PRESENT;
CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
/* Set owner and group and dacl */
res = SetSecurityDescriptorOwner(SecurityDescriptor, AdminSid, FALSE);
ok(res, "SetSecurityDescriptorOwner failed with error %d\n", GetLastError());
CHECK_SET_SECURITY( event, OWNER_SECURITY_INFORMATION, ERROR_SUCCESS );
test_owner_equal( event, AdminSid, __LINE__ );
res = SetSecurityDescriptorGroup(SecurityDescriptor, EveryoneSid, FALSE);
ok(res, "SetSecurityDescriptorGroup failed with error %d\n", GetLastError());
CHECK_SET_SECURITY( event, GROUP_SECURITY_INFORMATION, ERROR_SUCCESS );
test_group_equal( event, EveryoneSid, __LINE__ );
res = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
ok(res, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
/* setting a dacl should not change the owner or group */
test_owner_equal( event, AdminSid, __LINE__ );
test_group_equal( event, EveryoneSid, __LINE__ );
/* Test again with a different SID in case the previous SID also happens to
* be the one that is incorrectly replacing the group. */
res = SetSecurityDescriptorGroup(SecurityDescriptor, UsersSid, FALSE);
ok(res, "SetSecurityDescriptorGroup failed with error %d\n", GetLastError());
CHECK_SET_SECURITY( event, GROUP_SECURITY_INFORMATION, ERROR_SUCCESS );
test_group_equal( event, UsersSid, __LINE__ );
res = SetSecurityDescriptorDacl(SecurityDescriptor, TRUE, Acl, FALSE);
ok(res, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
CHECK_SET_SECURITY( event, DACL_SECURITY_INFORMATION, ERROR_SUCCESS );
test_group_equal( event, UsersSid, __LINE__ );
sprintf(buffer, "%s tests/security.c test", myARGV[0]);
memset(&startup, 0, sizeof(startup));
startup.cb = sizeof(startup);
startup.dwFlags = STARTF_USESHOWWINDOW;
startup.wShowWindow = SW_SHOWNORMAL;
psa.nLength = sizeof(psa);
psa.lpSecurityDescriptor = SecurityDescriptor;
psa.bInheritHandle = TRUE;
ThreadSecurityDescriptor = HeapAlloc( GetProcessHeap(), 0, SECURITY_DESCRIPTOR_MIN_LENGTH );
res = InitializeSecurityDescriptor( ThreadSecurityDescriptor, SECURITY_DESCRIPTOR_REVISION );
ok(res, "InitializeSecurityDescriptor failed with error %d\n", GetLastError());
ThreadAcl = HeapAlloc( GetProcessHeap(), 0, 256 );
res = InitializeAcl( ThreadAcl, 256, ACL_REVISION );
ok(res, "InitializeAcl failed with error %d\n", GetLastError());
res = AddAccessDeniedAce( ThreadAcl, ACL_REVISION, THREAD_SET_THREAD_TOKEN, AdminSid );
ok(res, "AddAccessDeniedAce failed with error %d\n", GetLastError() );
res = AddAccessAllowedAce( ThreadAcl, ACL_REVISION, THREAD_ALL_ACCESS, AdminSid );
ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
res = SetSecurityDescriptorOwner( ThreadSecurityDescriptor, AdminSid, FALSE );
ok(res, "SetSecurityDescriptorOwner failed with error %d\n", GetLastError());
res = SetSecurityDescriptorGroup( ThreadSecurityDescriptor, UsersSid, FALSE );
ok(res, "SetSecurityDescriptorGroup failed with error %d\n", GetLastError());
res = SetSecurityDescriptorDacl( ThreadSecurityDescriptor, TRUE, ThreadAcl, FALSE );
ok(res, "SetSecurityDescriptorDacl failed with error %d\n", GetLastError());
tsa.nLength = sizeof(tsa);
tsa.lpSecurityDescriptor = ThreadSecurityDescriptor;
tsa.bInheritHandle = TRUE;
/* Doesn't matter what ACL say we should get full access for ourselves */
res = CreateProcessA( NULL, buffer, &psa, &tsa, FALSE, 0, NULL, NULL, &startup, &info );
ok(res, "CreateProcess with err:%d\n", GetLastError());
TEST_GRANTED_ACCESS2( info.hProcess, PROCESS_ALL_ACCESS_NT4,
STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL );
TEST_GRANTED_ACCESS2( info.hThread, THREAD_ALL_ACCESS_NT4,
STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL );
winetest_wait_child_process( info.hProcess );
FreeSid(EveryoneSid);
CloseHandle( info.hProcess );
CloseHandle( info.hThread );
CloseHandle( event );
HeapFree(GetProcessHeap(), 0, group);
HeapFree(GetProcessHeap(), 0, owner);
HeapFree(GetProcessHeap(), 0, user);
HeapFree(GetProcessHeap(), 0, Acl);
HeapFree(GetProcessHeap(), 0, SecurityDescriptor);
HeapFree(GetProcessHeap(), 0, ThreadAcl);
HeapFree(GetProcessHeap(), 0, ThreadSecurityDescriptor);
}
static void test_process_security_child(void)
{
HANDLE handle, handle1;
BOOL ret;
DWORD err;
handle = OpenProcess( PROCESS_TERMINATE, FALSE, GetCurrentProcessId() );
ok(handle != NULL, "OpenProcess(PROCESS_TERMINATE) with err:%d\n", GetLastError());
TEST_GRANTED_ACCESS( handle, PROCESS_TERMINATE );
ret = DuplicateHandle( GetCurrentProcess(), handle, GetCurrentProcess(),
&handle1, 0, TRUE, DUPLICATE_SAME_ACCESS );
ok(ret, "duplicating handle err:%d\n", GetLastError());
TEST_GRANTED_ACCESS( handle1, PROCESS_TERMINATE );
CloseHandle( handle1 );
SetLastError( 0xdeadbeef );
ret = DuplicateHandle( GetCurrentProcess(), handle, GetCurrentProcess(),
&handle1, PROCESS_ALL_ACCESS, TRUE, 0 );
err = GetLastError();
ok(!ret && err == ERROR_ACCESS_DENIED, "duplicating handle should have failed "
"with STATUS_ACCESS_DENIED, instead of err:%d\n", err);
CloseHandle( handle );
/* These two should fail - they are denied by ACL */
handle = OpenProcess( PROCESS_VM_READ, FALSE, GetCurrentProcessId() );
ok(handle == NULL, "OpenProcess(PROCESS_VM_READ) should have failed\n");
handle = OpenProcess( PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId() );
ok(handle == NULL, "OpenProcess(PROCESS_ALL_ACCESS) should have failed\n");
/* Documented privilege elevation */
ret = DuplicateHandle( GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(),
&handle, 0, TRUE, DUPLICATE_SAME_ACCESS );
ok(ret, "duplicating handle err:%d\n", GetLastError());
TEST_GRANTED_ACCESS2( handle, PROCESS_ALL_ACCESS_NT4,
STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL );
CloseHandle( handle );
/* Same only explicitly asking for all access rights */
ret = DuplicateHandle( GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(),
&handle, PROCESS_ALL_ACCESS, TRUE, 0 );
ok(ret, "duplicating handle err:%d\n", GetLastError());
TEST_GRANTED_ACCESS2( handle, PROCESS_ALL_ACCESS_NT4,
PROCESS_ALL_ACCESS | PROCESS_QUERY_LIMITED_INFORMATION );
ret = DuplicateHandle( GetCurrentProcess(), handle, GetCurrentProcess(),
&handle1, PROCESS_VM_READ, TRUE, 0 );
ok(ret, "duplicating handle err:%d\n", GetLastError());
TEST_GRANTED_ACCESS( handle1, PROCESS_VM_READ );
CloseHandle( handle1 );
CloseHandle( handle );
/* Test thread security */
handle = OpenThread( THREAD_TERMINATE, FALSE, GetCurrentThreadId() );
ok(handle != NULL, "OpenThread(THREAD_TERMINATE) with err:%d\n", GetLastError());
TEST_GRANTED_ACCESS( handle, PROCESS_TERMINATE );
CloseHandle( handle );
handle = OpenThread( THREAD_SET_THREAD_TOKEN, FALSE, GetCurrentThreadId() );
ok(handle == NULL, "OpenThread(THREAD_SET_THREAD_TOKEN) should have failed\n");
}
static void test_impersonation_level(void)
{
HANDLE Token, ProcessToken;
HANDLE Token2;
DWORD Size;
TOKEN_PRIVILEGES *Privileges;
TOKEN_USER *User;
PRIVILEGE_SET *PrivilegeSet;
BOOL AccessGranted;
BOOL ret;
HKEY hkey;
DWORD error;
if( !pDuplicateTokenEx ) {
win_skip("DuplicateTokenEx is not available\n");
return;
}
SetLastError(0xdeadbeef);
ret = ImpersonateSelf(SecurityAnonymous);
if(!ret && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
{
win_skip("ImpersonateSelf is not implemented\n");
return;
}
ok(ret, "ImpersonateSelf(SecurityAnonymous) failed with error %d\n", GetLastError());
ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY_SOURCE | TOKEN_IMPERSONATE | TOKEN_ADJUST_DEFAULT, TRUE, &Token);
ok(!ret, "OpenThreadToken should have failed\n");
error = GetLastError();
ok(error == ERROR_CANT_OPEN_ANONYMOUS, "OpenThreadToken on anonymous token should have returned ERROR_CANT_OPEN_ANONYMOUS instead of %d\n", error);
/* can't perform access check when opening object against an anonymous impersonation token */
todo_wine {
error = RegOpenKeyExA(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
ok(error == ERROR_INVALID_HANDLE || error == ERROR_CANT_OPEN_ANONYMOUS || error == ERROR_BAD_IMPERSONATION_LEVEL,
"RegOpenKeyEx failed with %d\n", error);
}
RevertToSelf();
ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE, &ProcessToken);
ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
ret = pDuplicateTokenEx(ProcessToken,
TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE, NULL,
SecurityAnonymous, TokenImpersonation, &Token);
ok(ret, "DuplicateTokenEx failed with error %d\n", GetLastError());
/* can't increase the impersonation level */
ret = DuplicateToken(Token, SecurityIdentification, &Token2);
error = GetLastError();
ok(!ret && error == ERROR_BAD_IMPERSONATION_LEVEL,
"Duplicating a token and increasing the impersonation level should have failed with ERROR_BAD_IMPERSONATION_LEVEL instead of %d\n", error);
/* we can query anything from an anonymous token, including the user */
ret = GetTokenInformation(Token, TokenUser, NULL, 0, &Size);
error = GetLastError();
ok(!ret && error == ERROR_INSUFFICIENT_BUFFER, "GetTokenInformation(TokenUser) should have failed with ERROR_INSUFFICIENT_BUFFER instead of %d\n", error);
User = HeapAlloc(GetProcessHeap(), 0, Size);
ret = GetTokenInformation(Token, TokenUser, User, Size, &Size);
ok(ret, "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
HeapFree(GetProcessHeap(), 0, User);
/* PrivilegeCheck fails with SecurityAnonymous level */
ret = GetTokenInformation(Token, TokenPrivileges, NULL, 0, &Size);
error = GetLastError();
ok(!ret && error == ERROR_INSUFFICIENT_BUFFER, "GetTokenInformation(TokenPrivileges) should have failed with ERROR_INSUFFICIENT_BUFFER instead of %d\n", error);
Privileges = HeapAlloc(GetProcessHeap(), 0, Size);
ret = GetTokenInformation(Token, TokenPrivileges, Privileges, Size, &Size);
ok(ret, "GetTokenInformation(TokenPrivileges) failed with error %d\n", GetLastError());
PrivilegeSet = HeapAlloc(GetProcessHeap(), 0, FIELD_OFFSET(PRIVILEGE_SET, Privilege[Privileges->PrivilegeCount]));
PrivilegeSet->PrivilegeCount = Privileges->PrivilegeCount;
memcpy(PrivilegeSet->Privilege, Privileges->Privileges, PrivilegeSet->PrivilegeCount * sizeof(PrivilegeSet->Privilege[0]));
PrivilegeSet->Control = PRIVILEGE_SET_ALL_NECESSARY;
HeapFree(GetProcessHeap(), 0, Privileges);
ret = PrivilegeCheck(Token, PrivilegeSet, &AccessGranted);
error = GetLastError();
ok(!ret && error == ERROR_BAD_IMPERSONATION_LEVEL, "PrivilegeCheck for SecurityAnonymous token should have failed with ERROR_BAD_IMPERSONATION_LEVEL instead of %d\n", error);
CloseHandle(Token);
ret = ImpersonateSelf(SecurityIdentification);
ok(ret, "ImpersonateSelf(SecurityIdentification) failed with error %d\n", GetLastError());
ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY_SOURCE | TOKEN_IMPERSONATE | TOKEN_ADJUST_DEFAULT, TRUE, &Token);
ok(ret, "OpenThreadToken failed with error %d\n", GetLastError());
/* can't perform access check when opening object against an identification impersonation token */
error = RegOpenKeyExA(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
todo_wine {
ok(error == ERROR_INVALID_HANDLE || error == ERROR_BAD_IMPERSONATION_LEVEL || error == ERROR_ACCESS_DENIED,
"RegOpenKeyEx should have failed with ERROR_INVALID_HANDLE, ERROR_BAD_IMPERSONATION_LEVEL or ERROR_ACCESS_DENIED instead of %d\n", error);
}
ret = PrivilegeCheck(Token, PrivilegeSet, &AccessGranted);
ok(ret, "PrivilegeCheck for SecurityIdentification failed with error %d\n", GetLastError());
CloseHandle(Token);
RevertToSelf();
ret = ImpersonateSelf(SecurityImpersonation);
ok(ret, "ImpersonateSelf(SecurityImpersonation) failed with error %d\n", GetLastError());
ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY_SOURCE | TOKEN_IMPERSONATE | TOKEN_ADJUST_DEFAULT, TRUE, &Token);
ok(ret, "OpenThreadToken failed with error %d\n", GetLastError());
error = RegOpenKeyExA(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey);
ok(error == ERROR_SUCCESS, "RegOpenKeyEx should have succeeded instead of failing with %d\n", error);
RegCloseKey(hkey);
ret = PrivilegeCheck(Token, PrivilegeSet, &AccessGranted);
ok(ret, "PrivilegeCheck for SecurityImpersonation failed with error %d\n", GetLastError());
RevertToSelf();
CloseHandle(Token);
CloseHandle(ProcessToken);
HeapFree(GetProcessHeap(), 0, PrivilegeSet);
}
static void test_SetEntriesInAclW(void)
{
DWORD res;
PSID EveryoneSid = NULL, UsersSid = NULL;
PACL OldAcl = NULL, NewAcl;
SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
EXPLICIT_ACCESSW ExplicitAccess;
static const WCHAR wszEveryone[] = {'E','v','e','r','y','o','n','e',0};
static const WCHAR wszCurrentUser[] = { 'C','U','R','R','E','N','T','_','U','S','E','R','\0'};
if (!pSetEntriesInAclW)
{
win_skip("SetEntriesInAclW is not available\n");
return;
}
NewAcl = (PACL)0xdeadbeef;
res = pSetEntriesInAclW(0, NULL, NULL, &NewAcl);
if(res == ERROR_CALL_NOT_IMPLEMENTED)
{
win_skip("SetEntriesInAclW is not implemented\n");
return;
}
ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
ok(NewAcl == NULL ||
broken(NewAcl != NULL), /* NT4 */
"NewAcl=%p, expected NULL\n", NewAcl);
LocalFree(NewAcl);
OldAcl = HeapAlloc(GetProcessHeap(), 0, 256);
res = InitializeAcl(OldAcl, 256, ACL_REVISION);
if(!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
{
win_skip("ACLs not implemented - skipping tests\n");
HeapFree(GetProcessHeap(), 0, OldAcl);
return;
}
ok(res, "InitializeAcl failed with error %d\n", GetLastError());
res = AllocateAndInitializeSid( &SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &EveryoneSid);
ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &UsersSid);
ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
res = AddAccessAllowedAce(OldAcl, ACL_REVISION, KEY_READ, UsersSid);
ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
ExplicitAccess.grfAccessPermissions = KEY_WRITE;
ExplicitAccess.grfAccessMode = GRANT_ACCESS;
ExplicitAccess.grfInheritance = NO_INHERITANCE;
ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
ExplicitAccess.Trustee.ptstrName = EveryoneSid;
ExplicitAccess.Trustee.MultipleTrusteeOperation = 0xDEADBEEF;
ExplicitAccess.Trustee.pMultipleTrustee = (PVOID)0xDEADBEEF;
res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
ok(NewAcl != NULL, "returned acl was NULL\n");
LocalFree(NewAcl);
ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN;
ExplicitAccess.Trustee.pMultipleTrustee = NULL;
ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
ok(NewAcl != NULL, "returned acl was NULL\n");
LocalFree(NewAcl);
if (PRIMARYLANGID(GetSystemDefaultLangID()) != LANG_ENGLISH)
{
skip("Non-English locale (test with hardcoded 'Everyone')\n");
}
else
{
ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
ExplicitAccess.Trustee.ptstrName = (LPWSTR)wszEveryone;
res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
ok(NewAcl != NULL, "returned acl was NULL\n");
LocalFree(NewAcl);
ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_BAD_FORM;
res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
ok(res == ERROR_INVALID_PARAMETER ||
broken(res == ERROR_NOT_SUPPORTED), /* NT4 */
"SetEntriesInAclW failed: %u\n", res);
ok(NewAcl == NULL ||
broken(NewAcl != NULL), /* NT4 */
"returned acl wasn't NULL: %p\n", NewAcl);
ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
ExplicitAccess.Trustee.MultipleTrusteeOperation = TRUSTEE_IS_IMPERSONATE;
res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
ok(res == ERROR_INVALID_PARAMETER ||
broken(res == ERROR_NOT_SUPPORTED), /* NT4 */
"SetEntriesInAclW failed: %u\n", res);
ok(NewAcl == NULL ||
broken(NewAcl != NULL), /* NT4 */
"returned acl wasn't NULL: %p\n", NewAcl);
ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
ExplicitAccess.grfAccessMode = SET_ACCESS;
res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
ok(NewAcl != NULL, "returned acl was NULL\n");
LocalFree(NewAcl);
}
ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
ExplicitAccess.Trustee.ptstrName = (LPWSTR)wszCurrentUser;
res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
ok(NewAcl != NULL, "returned acl was NULL\n");
LocalFree(NewAcl);
ExplicitAccess.grfAccessMode = REVOKE_ACCESS;
ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
ExplicitAccess.Trustee.ptstrName = UsersSid;
res = pSetEntriesInAclW(1, &ExplicitAccess, OldAcl, &NewAcl);
ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
ok(NewAcl != NULL, "returned acl was NULL\n");
LocalFree(NewAcl);
FreeSid(UsersSid);
FreeSid(EveryoneSid);
HeapFree(GetProcessHeap(), 0, OldAcl);
}
static void test_SetEntriesInAclA(void)
{
DWORD res;
PSID EveryoneSid = NULL, UsersSid = NULL;
PACL OldAcl = NULL, NewAcl;
SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
EXPLICIT_ACCESSA ExplicitAccess;
static const CHAR szEveryone[] = {'E','v','e','r','y','o','n','e',0};
static const CHAR szCurrentUser[] = { 'C','U','R','R','E','N','T','_','U','S','E','R','\0'};
if (!pSetEntriesInAclA)
{
win_skip("SetEntriesInAclA is not available\n");
return;
}
NewAcl = (PACL)0xdeadbeef;
res = pSetEntriesInAclA(0, NULL, NULL, &NewAcl);
if(res == ERROR_CALL_NOT_IMPLEMENTED)
{
win_skip("SetEntriesInAclA is not implemented\n");
return;
}
ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
ok(NewAcl == NULL ||
broken(NewAcl != NULL), /* NT4 */
"NewAcl=%p, expected NULL\n", NewAcl);
LocalFree(NewAcl);
OldAcl = HeapAlloc(GetProcessHeap(), 0, 256);
res = InitializeAcl(OldAcl, 256, ACL_REVISION);
if(!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
{
win_skip("ACLs not implemented - skipping tests\n");
HeapFree(GetProcessHeap(), 0, OldAcl);
return;
}
ok(res, "InitializeAcl failed with error %d\n", GetLastError());
res = AllocateAndInitializeSid( &SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &EveryoneSid);
ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
res = AllocateAndInitializeSid( &SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &UsersSid);
ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
res = AddAccessAllowedAce(OldAcl, ACL_REVISION, KEY_READ, UsersSid);
ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
ExplicitAccess.grfAccessPermissions = KEY_WRITE;
ExplicitAccess.grfAccessMode = GRANT_ACCESS;
ExplicitAccess.grfInheritance = NO_INHERITANCE;
ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
ExplicitAccess.Trustee.ptstrName = EveryoneSid;
ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
ExplicitAccess.Trustee.pMultipleTrustee = NULL;
res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
ok(NewAcl != NULL, "returned acl was NULL\n");
LocalFree(NewAcl);
ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN;
ExplicitAccess.Trustee.pMultipleTrustee = NULL;
ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
ok(NewAcl != NULL, "returned acl was NULL\n");
LocalFree(NewAcl);
if (PRIMARYLANGID(GetSystemDefaultLangID()) != LANG_ENGLISH)
{
skip("Non-English locale (test with hardcoded 'Everyone')\n");
}
else
{
ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
ExplicitAccess.Trustee.ptstrName = (LPSTR)szEveryone;
res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
ok(NewAcl != NULL, "returned acl was NULL\n");
LocalFree(NewAcl);
ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_BAD_FORM;
res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
ok(res == ERROR_INVALID_PARAMETER ||
broken(res == ERROR_NOT_SUPPORTED), /* NT4 */
"SetEntriesInAclA failed: %u\n", res);
ok(NewAcl == NULL ||
broken(NewAcl != NULL), /* NT4 */
"returned acl wasn't NULL: %p\n", NewAcl);
ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
ExplicitAccess.Trustee.MultipleTrusteeOperation = TRUSTEE_IS_IMPERSONATE;
res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
ok(res == ERROR_INVALID_PARAMETER ||
broken(res == ERROR_NOT_SUPPORTED), /* NT4 */
"SetEntriesInAclA failed: %u\n", res);
ok(NewAcl == NULL ||
broken(NewAcl != NULL), /* NT4 */
"returned acl wasn't NULL: %p\n", NewAcl);
ExplicitAccess.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
ExplicitAccess.grfAccessMode = SET_ACCESS;
res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
ok(NewAcl != NULL, "returned acl was NULL\n");
LocalFree(NewAcl);
}
ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
ExplicitAccess.Trustee.ptstrName = (LPSTR)szCurrentUser;
res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
ok(NewAcl != NULL, "returned acl was NULL\n");
LocalFree(NewAcl);
ExplicitAccess.grfAccessMode = REVOKE_ACCESS;
ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID;
ExplicitAccess.Trustee.ptstrName = UsersSid;
res = pSetEntriesInAclA(1, &ExplicitAccess, OldAcl, &NewAcl);
ok(res == ERROR_SUCCESS, "SetEntriesInAclA failed: %u\n", res);
ok(NewAcl != NULL, "returned acl was NULL\n");
LocalFree(NewAcl);
FreeSid(UsersSid);
FreeSid(EveryoneSid);
HeapFree(GetProcessHeap(), 0, OldAcl);
}
/* helper function for test_CreateDirectoryA */
static void get_nt_pathW(const char *name, UNICODE_STRING *nameW)
{
UNICODE_STRING strW;
ANSI_STRING str;
NTSTATUS status;
BOOLEAN ret;
pRtlInitAnsiString(&str, name);
status = pRtlAnsiStringToUnicodeString(&strW, &str, TRUE);
ok(!status, "RtlAnsiStringToUnicodeString failed with %08x\n", status);
ret = pRtlDosPathNameToNtPathName_U(strW.Buffer, nameW, NULL, NULL);
ok(ret, "RtlDosPathNameToNtPathName_U failed\n");
pRtlFreeUnicodeString(&strW);
}
static void test_inherited_dacl(PACL dacl, PSID admin_sid, PSID user_sid, DWORD flags, DWORD mask,
BOOL todo_count, BOOL todo_sid, BOOL todo_flags, int line)
{
ACL_SIZE_INFORMATION acl_size;
ACCESS_ALLOWED_ACE *ace;
BOOL bret;
bret = pGetAclInformation(dacl, &acl_size, sizeof(acl_size), AclSizeInformation);
ok_(__FILE__, line)(bret, "GetAclInformation failed\n");
todo_wine_if (todo_count)
ok_(__FILE__, line)(acl_size.AceCount == 2,
"GetAclInformation returned unexpected entry count (%d != 2)\n",
acl_size.AceCount);
if (acl_size.AceCount > 0)
{
bret = pGetAce(dacl, 0, (VOID **)&ace);
ok_(__FILE__, line)(bret, "Failed to get Current User ACE\n");
bret = EqualSid(&ace->SidStart, user_sid);
todo_wine_if (todo_sid)
ok_(__FILE__, line)(bret, "Current User ACE (%s) != Current User SID (%s)\n", debugstr_sid(&ace->SidStart), debugstr_sid(user_sid));
todo_wine_if (todo_flags)
ok_(__FILE__, line)(((ACE_HEADER *)ace)->AceFlags == flags,
"Current User ACE has unexpected flags (0x%x != 0x%x)\n",
((ACE_HEADER *)ace)->AceFlags, flags);
ok_(__FILE__, line)(ace->Mask == mask,
"Current User ACE has unexpected mask (0x%x != 0x%x)\n",
ace->Mask, mask);
}
if (acl_size.AceCount > 1)
{
bret = pGetAce(dacl, 1, (VOID **)&ace);
ok_(__FILE__, line)(bret, "Failed to get Administators Group ACE\n");
bret = EqualSid(&ace->SidStart, admin_sid);
todo_wine_if (todo_sid)
ok_(__FILE__, line)(bret, "Administators Group ACE (%s) != Administators Group SID (%s)\n", debugstr_sid(&ace->SidStart), debugstr_sid(admin_sid));
todo_wine_if (todo_flags)
ok_(__FILE__, line)(((ACE_HEADER *)ace)->AceFlags == flags,
"Administators Group ACE has unexpected flags (0x%x != 0x%x)\n",
((ACE_HEADER *)ace)->AceFlags, flags);
ok_(__FILE__, line)(ace->Mask == mask,
"Administators Group ACE has unexpected mask (0x%x != 0x%x)\n",
ace->Mask, mask);
}
}
static void test_CreateDirectoryA(void)
{
char admin_ptr[sizeof(SID)+sizeof(ULONG)*SID_MAX_SUB_AUTHORITIES], *user;
DWORD sid_size = sizeof(admin_ptr), user_size;
PSID admin_sid = (PSID) admin_ptr, user_sid;
char sd[SECURITY_DESCRIPTOR_MIN_LENGTH];
PSECURITY_DESCRIPTOR pSD = &sd;
ACL_SIZE_INFORMATION acl_size;
UNICODE_STRING tmpfileW;
SECURITY_ATTRIBUTES sa;
OBJECT_ATTRIBUTES attr;
char tmpfile[MAX_PATH];
char tmpdir[MAX_PATH];
HANDLE token, hTemp;
IO_STATUS_BLOCK io;
struct _SID *owner;
BOOL bret = TRUE;
NTSTATUS status;
DWORD error;
PACL pDacl;
if (!pGetSecurityInfo || !pGetNamedSecurityInfoA || !pCreateWellKnownSid)
{
win_skip("Required functions are not available\n");
return;
}
if (!OpenThreadToken(GetCurrentThread(), TOKEN_READ, TRUE, &token))
{
if (GetLastError() != ERROR_NO_TOKEN) bret = FALSE;
else if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &token)) bret = FALSE;
}
if (!bret)
{
win_skip("Failed to get current user token\n");
return;
}
bret = GetTokenInformation(token, TokenUser, NULL, 0, &user_size);
ok(!bret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
"GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
user = HeapAlloc(GetProcessHeap(), 0, user_size);
bret = GetTokenInformation(token, TokenUser, user, user_size, &user_size);
ok(bret, "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
CloseHandle( token );
user_sid = ((TOKEN_USER *)user)->User.Sid;
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = pSD;
sa.bInheritHandle = TRUE;
InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION);
pCreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, admin_sid, &sid_size);
pDacl = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, 100);
bret = InitializeAcl(pDacl, 100, ACL_REVISION);
ok(bret, "Failed to initialize ACL.\n");
bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, OBJECT_INHERIT_ACE|CONTAINER_INHERIT_ACE,
GENERIC_ALL, user_sid);
ok(bret, "Failed to add Current User to ACL.\n");
bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, OBJECT_INHERIT_ACE|CONTAINER_INHERIT_ACE,
GENERIC_ALL, admin_sid);
ok(bret, "Failed to add Administrator Group to ACL.\n");
bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
ok(bret, "Failed to add ACL to security descriptor.\n");
GetTempPathA(MAX_PATH, tmpdir);
lstrcatA(tmpdir, "Please Remove Me");
bret = CreateDirectoryA(tmpdir, &sa);
ok(bret == TRUE, "CreateDirectoryA(%s) failed err=%d\n", tmpdir, GetLastError());
HeapFree(GetProcessHeap(), 0, pDacl);
SetLastError(0xdeadbeef);
error = pGetNamedSecurityInfoA(tmpdir, SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION, (PSID*)&owner,
NULL, &pDacl, NULL, &pSD);
if (error != ERROR_SUCCESS && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
{
win_skip("GetNamedSecurityInfoA is not implemented\n");
goto done;
}
ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
test_inherited_dacl(pDacl, admin_sid, user_sid, OBJECT_INHERIT_ACE|CONTAINER_INHERIT_ACE,
0x1f01ff, FALSE, TRUE, FALSE, __LINE__);
LocalFree(pSD);
/* Test inheritance of ACLs in CreateFile without security descriptor */
strcpy(tmpfile, tmpdir);
lstrcatA(tmpfile, "/tmpfile");
hTemp = CreateFileA(tmpfile, GENERIC_WRITE, FILE_SHARE_READ, NULL,
CREATE_NEW, FILE_FLAG_DELETE_ON_CLOSE, NULL);
ok(hTemp != INVALID_HANDLE_VALUE, "CreateFile error %u\n", GetLastError());
error = pGetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
(PSID *)&owner, NULL, &pDacl, NULL, &pSD);
ok(error == ERROR_SUCCESS, "Failed to get permissions on file\n");
test_inherited_dacl(pDacl, admin_sid, user_sid, INHERITED_ACE,
0x1f01ff, TRUE, TRUE, TRUE, __LINE__);
LocalFree(pSD);
CloseHandle(hTemp);
/* Test inheritance of ACLs in CreateFile with security descriptor -
* When a security descriptor is set, then inheritance doesn't take effect */
pSD = &sd;
InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION);
pDacl = HeapAlloc(GetProcessHeap(), 0, sizeof(ACL));
bret = InitializeAcl(pDacl, sizeof(ACL), ACL_REVISION);
ok(bret, "Failed to initialize ACL\n");
bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
ok(bret, "Failed to add ACL to security descriptor\n");
strcpy(tmpfile, tmpdir);
lstrcatA(tmpfile, "/tmpfile");
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = pSD;
sa.bInheritHandle = TRUE;
hTemp = CreateFileA(tmpfile, GENERIC_WRITE, FILE_SHARE_READ, &sa,
CREATE_NEW, FILE_FLAG_DELETE_ON_CLOSE, NULL);
ok(hTemp != INVALID_HANDLE_VALUE, "CreateFile error %u\n", GetLastError());
HeapFree(GetProcessHeap(), 0, pDacl);
error = pGetSecurityInfo(hTemp, SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
(PSID *)&owner, NULL, &pDacl, NULL, &pSD);
ok(error == ERROR_SUCCESS, "GetNamedSecurityInfo failed with error %d\n", error);
bret = pGetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
ok(bret, "GetAclInformation failed\n");
todo_wine
ok(acl_size.AceCount == 0, "GetAclInformation returned unexpected entry count (%d != 0).\n",
acl_size.AceCount);
LocalFree(pSD);
error = pGetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
(PSID *)&owner, NULL, &pDacl, NULL, &pSD);
todo_wine
ok(error == ERROR_SUCCESS, "GetNamedSecurityInfo failed with error %d\n", error);
if (error == ERROR_SUCCESS)
{
bret = pGetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
ok(bret, "GetAclInformation failed\n");
todo_wine
ok(acl_size.AceCount == 0, "GetAclInformation returned unexpected entry count (%d != 0).\n",
acl_size.AceCount);
LocalFree(pSD);
}
CloseHandle(hTemp);
/* Test inheritance of ACLs in NtCreateFile without security descriptor */
strcpy(tmpfile, tmpdir);
lstrcatA(tmpfile, "/tmpfile");
get_nt_pathW(tmpfile, &tmpfileW);
attr.Length = sizeof(attr);
attr.RootDirectory = 0;
attr.ObjectName = &tmpfileW;
attr.Attributes = OBJ_CASE_INSENSITIVE;
attr.SecurityDescriptor = NULL;
attr.SecurityQualityOfService = NULL;
status = pNtCreateFile(&hTemp, GENERIC_WRITE | DELETE, &attr, &io, NULL, 0,
FILE_SHARE_READ, FILE_CREATE, FILE_DELETE_ON_CLOSE, NULL, 0);
ok(!status, "NtCreateFile failed with %08x\n", status);
pRtlFreeUnicodeString(&tmpfileW);
error = pGetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
(PSID *)&owner, NULL, &pDacl, NULL, &pSD);
ok(error == ERROR_SUCCESS, "Failed to get permissions on file\n");
test_inherited_dacl(pDacl, admin_sid, user_sid, INHERITED_ACE,
0x1f01ff, TRUE, TRUE, TRUE, __LINE__);
LocalFree(pSD);
CloseHandle(hTemp);
/* Test inheritance of ACLs in NtCreateFile with security descriptor -
* When a security descriptor is set, then inheritance doesn't take effect */
pSD = &sd;
InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION);
pDacl = HeapAlloc(GetProcessHeap(), 0, sizeof(ACL));
bret = InitializeAcl(pDacl, sizeof(ACL), ACL_REVISION);
ok(bret, "Failed to initialize ACL\n");
bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
ok(bret, "Failed to add ACL to security descriptor\n");
strcpy(tmpfile, tmpdir);
lstrcatA(tmpfile, "/tmpfile");
get_nt_pathW(tmpfile, &tmpfileW);
attr.Length = sizeof(attr);
attr.RootDirectory = 0;
attr.ObjectName = &tmpfileW;
attr.Attributes = OBJ_CASE_INSENSITIVE;
attr.SecurityDescriptor = pSD;
attr.SecurityQualityOfService = NULL;
status = pNtCreateFile(&hTemp, GENERIC_WRITE | DELETE, &attr, &io, NULL, 0,
FILE_SHARE_READ, FILE_CREATE, FILE_DELETE_ON_CLOSE, NULL, 0);
ok(!status, "NtCreateFile failed with %08x\n", status);
pRtlFreeUnicodeString(&tmpfileW);
HeapFree(GetProcessHeap(), 0, pDacl);
error = pGetSecurityInfo(hTemp, SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
(PSID *)&owner, NULL, &pDacl, NULL, &pSD);
ok(error == ERROR_SUCCESS, "GetNamedSecurityInfo failed with error %d\n", error);
bret = pGetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
ok(bret, "GetAclInformation failed\n");
todo_wine
ok(acl_size.AceCount == 0, "GetAclInformation returned unexpected entry count (%d != 0).\n",
acl_size.AceCount);
LocalFree(pSD);
error = pGetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
(PSID *)&owner, NULL, &pDacl, NULL, &pSD);
todo_wine
ok(error == ERROR_SUCCESS, "GetNamedSecurityInfo failed with error %d\n", error);
if (error == ERROR_SUCCESS)
{
bret = pGetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
ok(bret, "GetAclInformation failed\n");
todo_wine
ok(acl_size.AceCount == 0, "GetAclInformation returned unexpected entry count (%d != 0).\n",
acl_size.AceCount);
LocalFree(pSD);
}
CloseHandle(hTemp);
done:
HeapFree(GetProcessHeap(), 0, user);
bret = RemoveDirectoryA(tmpdir);
ok(bret == TRUE, "RemoveDirectoryA should always succeed\n");
}
static void test_GetNamedSecurityInfoA(void)
{
char admin_ptr[sizeof(SID)+sizeof(ULONG)*SID_MAX_SUB_AUTHORITIES], *user;
char system_ptr[sizeof(SID)+sizeof(ULONG)*SID_MAX_SUB_AUTHORITIES];
char users_ptr[sizeof(SID)+sizeof(ULONG)*SID_MAX_SUB_AUTHORITIES];
SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
PSID admin_sid = (PSID) admin_ptr, users_sid = (PSID) users_ptr;
PSID system_sid = (PSID) system_ptr, user_sid, localsys_sid;
DWORD sid_size = sizeof(admin_ptr), user_size;
char invalid_path[] = "/an invalid file path";
int users_ace_id = -1, admins_ace_id = -1, i;
char software_key[] = "MACHINE\\Software";
char sd[SECURITY_DESCRIPTOR_MIN_LENGTH+sizeof(void*)];
SECURITY_DESCRIPTOR_CONTROL control;
ACL_SIZE_INFORMATION acl_size;
CHAR windows_dir[MAX_PATH];
PSECURITY_DESCRIPTOR pSD;
ACCESS_ALLOWED_ACE *ace;
BOOL bret = TRUE, isNT4;
char tmpfile[MAX_PATH];
DWORD error, revision;
BOOL owner_defaulted;
BOOL group_defaulted;
BOOL dacl_defaulted;
HANDLE token, hTemp, h;
PSID owner, group;
BOOL dacl_present;
PACL pDacl;
BYTE flags;
NTSTATUS status;
if (!pSetNamedSecurityInfoA || !pGetNamedSecurityInfoA || !pCreateWellKnownSid)
{
win_skip("Required functions are not available\n");
return;
}
if (!OpenThreadToken(GetCurrentThread(), TOKEN_READ, TRUE, &token))
{
if (GetLastError() != ERROR_NO_TOKEN) bret = FALSE;
else if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &token)) bret = FALSE;
}
if (!bret)
{
win_skip("Failed to get current user token\n");
return;
}
bret = GetTokenInformation(token, TokenUser, NULL, 0, &user_size);
ok(!bret && (GetLastError() == ERROR_INSUFFICIENT_BUFFER),
"GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
user = HeapAlloc(GetProcessHeap(), 0, user_size);
bret = GetTokenInformation(token, TokenUser, user, user_size, &user_size);
ok(bret, "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
CloseHandle( token );
user_sid = ((TOKEN_USER *)user)->User.Sid;
bret = GetWindowsDirectoryA(windows_dir, MAX_PATH);
ok(bret, "GetWindowsDirectory failed with error %d\n", GetLastError());
SetLastError(0xdeadbeef);
error = pGetNamedSecurityInfoA(windows_dir, SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION,
NULL, NULL, NULL, NULL, &pSD);
if (error != ERROR_SUCCESS && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
{
win_skip("GetNamedSecurityInfoA is not implemented\n");
HeapFree(GetProcessHeap(), 0, user);
return;
}
ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
bret = GetSecurityDescriptorControl(pSD, &control, &revision);
ok(bret, "GetSecurityDescriptorControl failed with error %d\n", GetLastError());
ok((control & (SE_SELF_RELATIVE|SE_DACL_PRESENT)) == (SE_SELF_RELATIVE|SE_DACL_PRESENT) ||
broken((control & (SE_SELF_RELATIVE|SE_DACL_PRESENT)) == SE_DACL_PRESENT), /* NT4 */
"control (0x%x) doesn't have (SE_SELF_RELATIVE|SE_DACL_PRESENT) flags set\n", control);
ok(revision == SECURITY_DESCRIPTOR_REVISION1, "revision was %d instead of 1\n", revision);
isNT4 = (control & (SE_SELF_RELATIVE|SE_DACL_PRESENT)) == SE_DACL_PRESENT;
bret = GetSecurityDescriptorOwner(pSD, &owner, &owner_defaulted);
ok(bret, "GetSecurityDescriptorOwner failed with error %d\n", GetLastError());
ok(owner != NULL, "owner should not be NULL\n");
bret = GetSecurityDescriptorGroup(pSD, &group, &group_defaulted);
ok(bret, "GetSecurityDescriptorGroup failed with error %d\n", GetLastError());
ok(group != NULL, "group should not be NULL\n");
LocalFree(pSD);
/* NULL descriptor tests */
if(isNT4)
{
win_skip("NT4 does not support GetNamedSecutityInfo with a NULL descriptor\n");
HeapFree(GetProcessHeap(), 0, user);
return;
}
error = pGetNamedSecurityInfoA(windows_dir, SE_FILE_OBJECT,DACL_SECURITY_INFORMATION,
NULL, NULL, NULL, NULL, NULL);
ok(error==ERROR_INVALID_PARAMETER, "GetNamedSecurityInfo failed with error %d\n", error);
pDacl = NULL;
error = pGetNamedSecurityInfoA(windows_dir, SE_FILE_OBJECT,DACL_SECURITY_INFORMATION,
NULL, NULL, &pDacl, NULL, &pSD);
ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
ok(pDacl != NULL, "DACL should not be NULL\n");
LocalFree(pSD);
error = pGetNamedSecurityInfoA(windows_dir, SE_FILE_OBJECT,OWNER_SECURITY_INFORMATION,
NULL, NULL, &pDacl, NULL, NULL);
ok(error==ERROR_INVALID_PARAMETER, "GetNamedSecurityInfo failed with error %d\n", error);
/* Test behavior of SetNamedSecurityInfo with an invalid path */
SetLastError(0xdeadbeef);
error = pSetNamedSecurityInfoA(invalid_path, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL,
NULL, NULL, NULL);
ok(error == ERROR_FILE_NOT_FOUND, "Unexpected error returned: 0x%x\n", error);
ok(GetLastError() == 0xdeadbeef, "Expected last error to remain unchanged.\n");
/* Create security descriptor information and test that it comes back the same */
pSD = &sd;
pDacl = HeapAlloc(GetProcessHeap(), 0, 100);
InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION);
pCreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, admin_sid, &sid_size);
bret = InitializeAcl(pDacl, 100, ACL_REVISION);
ok(bret, "Failed to initialize ACL.\n");
bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, user_sid);
ok(bret, "Failed to add Current User to ACL.\n");
bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, admin_sid);
ok(bret, "Failed to add Administrator Group to ACL.\n");
bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
ok(bret, "Failed to add ACL to security descriptor.\n");
GetTempFileNameA(".", "foo", 0, tmpfile);
hTemp = CreateFileA(tmpfile, WRITE_DAC|GENERIC_WRITE, FILE_SHARE_DELETE|FILE_SHARE_READ,
NULL, OPEN_EXISTING, FILE_FLAG_DELETE_ON_CLOSE, NULL);
SetLastError(0xdeadbeef);
error = pSetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL,
NULL, pDacl, NULL);
HeapFree(GetProcessHeap(), 0, pDacl);
if (error != ERROR_SUCCESS && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
{
win_skip("SetNamedSecurityInfoA is not implemented\n");
HeapFree(GetProcessHeap(), 0, user);
CloseHandle(hTemp);
return;
}
ok(!error, "SetNamedSecurityInfoA failed with error %d\n", error);
SetLastError(0xdeadbeef);
error = pGetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
NULL, NULL, &pDacl, NULL, &pSD);
if (error != ERROR_SUCCESS && (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED))
{
win_skip("GetNamedSecurityInfoA is not implemented\n");
HeapFree(GetProcessHeap(), 0, user);
CloseHandle(hTemp);
return;
}
ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
bret = pGetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
ok(bret, "GetAclInformation failed\n");
if (acl_size.AceCount > 0)
{
bret = pGetAce(pDacl, 0, (VOID **)&ace);
ok(bret, "Failed to get Current User ACE.\n");
bret = EqualSid(&ace->SidStart, user_sid);
todo_wine ok(bret, "Current User ACE (%s) != Current User SID (%s).\n",
debugstr_sid(&ace->SidStart), debugstr_sid(user_sid));
ok(((ACE_HEADER *)ace)->AceFlags == 0,
"Current User ACE has unexpected flags (0x%x != 0x0)\n", ((ACE_HEADER *)ace)->AceFlags);
ok(ace->Mask == 0x1f01ff, "Current User ACE has unexpected mask (0x%x != 0x1f01ff)\n",
ace->Mask);
}
if (acl_size.AceCount > 1)
{
bret = pGetAce(pDacl, 1, (VOID **)&ace);
ok(bret, "Failed to get Administators Group ACE.\n");
bret = EqualSid(&ace->SidStart, admin_sid);
todo_wine ok(bret || broken(!bret) /* win2k */,
"Administators Group ACE (%s) != Administators Group SID (%s).\n",
debugstr_sid(&ace->SidStart), debugstr_sid(admin_sid));
ok(((ACE_HEADER *)ace)->AceFlags == 0,
"Administators Group ACE has unexpected flags (0x%x != 0x0)\n", ((ACE_HEADER *)ace)->AceFlags);
ok(ace->Mask == 0x1f01ff || broken(ace->Mask == GENERIC_ALL) /* win2k */,
"Administators Group ACE has unexpected mask (0x%x != 0x1f01ff)\n", ace->Mask);
}
LocalFree(pSD);
/* show that setting empty DACL is not removing all file permissions */
pDacl = HeapAlloc(GetProcessHeap(), 0, sizeof(ACL));
bret = InitializeAcl(pDacl, sizeof(ACL), ACL_REVISION);
ok(bret, "Failed to initialize ACL.\n");
error = pSetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
NULL, NULL, pDacl, NULL);
ok(!error, "SetNamedSecurityInfoA failed with error %d\n", error);
HeapFree(GetProcessHeap(), 0, pDacl);
error = pGetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
NULL, NULL, &pDacl, NULL, &pSD);
ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
bret = pGetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
ok(bret, "GetAclInformation failed\n");
if (acl_size.AceCount > 0)
{
bret = pGetAce(pDacl, 0, (VOID **)&ace);
ok(bret, "Failed to get ACE.\n");
todo_wine ok(((ACE_HEADER *)ace)->AceFlags & INHERITED_ACE,
"ACE has unexpected flags: 0x%x\n", ((ACE_HEADER *)ace)->AceFlags);
}
LocalFree(pSD);
h = CreateFileA(tmpfile, GENERIC_READ, FILE_SHARE_DELETE|FILE_SHARE_WRITE|FILE_SHARE_READ,
NULL, OPEN_EXISTING, 0, NULL);
ok(h != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
CloseHandle(h);
/* test setting NULL DACL */
error = pSetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION, NULL, NULL, NULL, NULL);
ok(!error, "SetNamedSecurityInfoA failed with error %d\n", error);
error = pGetNamedSecurityInfoA(tmpfile, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
NULL, NULL, &pDacl, NULL, &pSD);
ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
todo_wine ok(!pDacl, "pDacl != NULL\n");
LocalFree(pSD);
h = CreateFileA(tmpfile, GENERIC_READ, FILE_SHARE_DELETE|FILE_SHARE_WRITE|FILE_SHARE_READ,
NULL, OPEN_EXISTING, 0, NULL);
ok(h != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
CloseHandle(h);
/* NtSetSecurityObject doesn't inherit DACL entries */
pSD = sd+sizeof(void*)-((ULONG_PTR)sd)%sizeof(void*);
InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION);
pDacl = HeapAlloc(GetProcessHeap(), 0, 100);
bret = InitializeAcl(pDacl, sizeof(ACL), ACL_REVISION);
ok(bret, "Failed to initialize ACL.\n");
bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
ok(bret, "Failed to add ACL to security descriptor.\n");
status = pNtSetSecurityObject(hTemp, DACL_SECURITY_INFORMATION, pSD);
ok(status == ERROR_SUCCESS, "NtSetSecurityObject returned %x\n", status);
h = CreateFileA(tmpfile, GENERIC_READ, FILE_SHARE_DELETE|FILE_SHARE_WRITE|FILE_SHARE_READ,
NULL, OPEN_EXISTING, 0, NULL);
ok(h == INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
CloseHandle(h);
pSetSecurityDescriptorControl(pSD, SE_DACL_AUTO_INHERIT_REQ, SE_DACL_AUTO_INHERIT_REQ);
status = pNtSetSecurityObject(hTemp, DACL_SECURITY_INFORMATION, pSD);
ok(status == ERROR_SUCCESS, "NtSetSecurityObject returned %x\n", status);
h = CreateFileA(tmpfile, GENERIC_READ, FILE_SHARE_DELETE|FILE_SHARE_WRITE|FILE_SHARE_READ,
NULL, OPEN_EXISTING, 0, NULL);
ok(h == INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
CloseHandle(h);
pSetSecurityDescriptorControl(pSD, SE_DACL_AUTO_INHERIT_REQ|SE_DACL_AUTO_INHERITED,
SE_DACL_AUTO_INHERIT_REQ|SE_DACL_AUTO_INHERITED);
status = pNtSetSecurityObject(hTemp, DACL_SECURITY_INFORMATION, pSD);
ok(status == ERROR_SUCCESS, "NtSetSecurityObject returned %x\n", status);
h = CreateFileA(tmpfile, GENERIC_READ, FILE_SHARE_DELETE|FILE_SHARE_WRITE|FILE_SHARE_READ,
NULL, OPEN_EXISTING, 0, NULL);
ok(h == INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
CloseHandle(h);
/* test if DACL is properly mapped to permission */
bret = InitializeAcl(pDacl, 100, ACL_REVISION);
ok(bret, "Failed to initialize ACL.\n");
bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, user_sid);
ok(bret, "Failed to add Current User to ACL.\n");
bret = pAddAccessDeniedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, user_sid);
ok(bret, "Failed to add Current User to ACL.\n");
bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
ok(bret, "Failed to add ACL to security descriptor.\n");
status = pNtSetSecurityObject(hTemp, DACL_SECURITY_INFORMATION, pSD);
ok(status == ERROR_SUCCESS, "NtSetSecurityObject returned %x\n", status);
h = CreateFileA(tmpfile, GENERIC_READ, FILE_SHARE_DELETE|FILE_SHARE_WRITE|FILE_SHARE_READ,
NULL, OPEN_EXISTING, 0, NULL);
ok(h != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
CloseHandle(h);
bret = InitializeAcl(pDacl, 100, ACL_REVISION);
ok(bret, "Failed to initialize ACL.\n");
bret = pAddAccessDeniedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, user_sid);
ok(bret, "Failed to add Current User to ACL.\n");
bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, user_sid);
ok(bret, "Failed to add Current User to ACL.\n");
bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
ok(bret, "Failed to add ACL to security descriptor.\n");
status = pNtSetSecurityObject(hTemp, DACL_SECURITY_INFORMATION, pSD);
ok(status == ERROR_SUCCESS, "NtSetSecurityObject returned %x\n", status);
h = CreateFileA(tmpfile, GENERIC_READ, FILE_SHARE_DELETE|FILE_SHARE_WRITE|FILE_SHARE_READ,
NULL, OPEN_EXISTING, 0, NULL);
ok(h == INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
HeapFree(GetProcessHeap(), 0, pDacl);
HeapFree(GetProcessHeap(), 0, user);
CloseHandle(hTemp);
/* Test querying the ownership of a built-in registry key */
sid_size = sizeof(system_ptr);
pCreateWellKnownSid(WinLocalSystemSid, NULL, system_sid, &sid_size);
error = pGetNamedSecurityInfoA(software_key, SE_REGISTRY_KEY,
OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION,
NULL, NULL, NULL, NULL, &pSD);
ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
bret = AllocateAndInitializeSid(&SIDAuthNT, 1, SECURITY_LOCAL_SYSTEM_RID, 0, 0, 0, 0, 0, 0, 0, &localsys_sid);
ok(bret, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
bret = GetSecurityDescriptorOwner(pSD, &owner, &owner_defaulted);
ok(bret, "GetSecurityDescriptorOwner failed with error %d\n", GetLastError());
ok(owner != NULL, "owner should not be NULL\n");
ok(EqualSid(owner, admin_sid) || EqualSid(owner, localsys_sid),
"MACHINE\\Software owner SID (%s) != Administrators SID (%s) or Local System Sid (%s).\n",
debugstr_sid(owner), debugstr_sid(admin_sid), debugstr_sid(localsys_sid));
bret = GetSecurityDescriptorGroup(pSD, &group, &group_defaulted);
ok(bret, "GetSecurityDescriptorGroup failed with error %d\n", GetLastError());
ok(group != NULL, "group should not be NULL\n");
ok(EqualSid(group, admin_sid) || broken(EqualSid(group, system_sid)) /* before Win7 */
|| broken(((SID*)group)->SubAuthority[0] == SECURITY_NT_NON_UNIQUE) /* Vista */,
"MACHINE\\Software group SID (%s) != Local System SID (%s or %s)\n",
debugstr_sid(group), debugstr_sid(admin_sid), debugstr_sid(system_sid));
LocalFree(pSD);
/* Test querying the DACL of a built-in registry key */
sid_size = sizeof(users_ptr);
pCreateWellKnownSid(WinBuiltinUsersSid, NULL, users_sid, &sid_size);
error = pGetNamedSecurityInfoA(software_key, SE_REGISTRY_KEY, DACL_SECURITY_INFORMATION,
NULL, NULL, NULL, NULL, &pSD);
ok(!error, "GetNamedSecurityInfo failed with error %d\n", error);
bret = GetSecurityDescriptorDacl(pSD, &dacl_present, &pDacl, &dacl_defaulted);
ok(bret, "GetSecurityDescriptorDacl failed with error %d\n", GetLastError());
ok(dacl_present, "DACL should be present\n");
ok(pDacl && IsValidAcl(pDacl), "GetSecurityDescriptorDacl returned invalid DACL.\n");
bret = pGetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
ok(bret, "GetAclInformation failed\n");
ok(acl_size.AceCount != 0, "GetAclInformation returned no ACLs\n");
for (i=0; i<acl_size.AceCount; i++)
{
bret = pGetAce(pDacl, i, (VOID **)&ace);
ok(bret, "Failed to get ACE %d.\n", i);
bret = EqualSid(&ace->SidStart, users_sid);
if (bret) users_ace_id = i;
bret = EqualSid(&ace->SidStart, admin_sid);
if (bret) admins_ace_id = i;
}
ok(users_ace_id != -1 || broken(users_ace_id == -1) /* win2k */,
"Builtin Users ACE not found.\n");
if (users_ace_id != -1)
{
bret = pGetAce(pDacl, users_ace_id, (VOID **)&ace);
ok(bret, "Failed to get Builtin Users ACE.\n");
flags = ((ACE_HEADER *)ace)->AceFlags;
ok(flags == (INHERIT_ONLY_ACE|CONTAINER_INHERIT_ACE)
|| broken(flags == (INHERIT_ONLY_ACE|CONTAINER_INHERIT_ACE|INHERITED_ACE)) /* w2k8 */
|| broken(flags == (CONTAINER_INHERIT_ACE|INHERITED_ACE)) /* win 10 wow64 */
|| broken(flags == CONTAINER_INHERIT_ACE), /* win 10 */
"Builtin Users ACE has unexpected flags (0x%x != 0x%x)\n", flags,
INHERIT_ONLY_ACE|CONTAINER_INHERIT_ACE);
ok(ace->Mask == GENERIC_READ
|| broken(ace->Mask == KEY_READ), /* win 10 */
"Builtin Users ACE has unexpected mask (0x%x != 0x%x)\n",
ace->Mask, GENERIC_READ);
}
ok(admins_ace_id != -1, "Builtin Admins ACE not found.\n");
if (admins_ace_id != -1)
{
bret = pGetAce(pDacl, admins_ace_id, (VOID **)&ace);
ok(bret, "Failed to get Builtin Admins ACE.\n");
flags = ((ACE_HEADER *)ace)->AceFlags;
ok(flags == 0x0
|| broken(flags == (INHERIT_ONLY_ACE|CONTAINER_INHERIT_ACE|INHERITED_ACE)) /* w2k8 */
|| broken(flags == (OBJECT_INHERIT_ACE|CONTAINER_INHERIT_ACE)) /* win7 */
|| broken(flags == (INHERIT_ONLY_ACE|CONTAINER_INHERIT_ACE)) /* win8+ */
|| broken(flags == (CONTAINER_INHERIT_ACE|INHERITED_ACE)) /* win 10 wow64 */
|| broken(flags == CONTAINER_INHERIT_ACE), /* win 10 */
"Builtin Admins ACE has unexpected flags (0x%x != 0x0)\n", flags);
ok(ace->Mask == KEY_ALL_ACCESS || broken(ace->Mask == GENERIC_ALL) /* w2k8 */,
"Builtin Admins ACE has unexpected mask (0x%x != 0x%x)\n", ace->Mask, KEY_ALL_ACCESS);
}
FreeSid(localsys_sid);
LocalFree(pSD);
}
static void test_ConvertStringSecurityDescriptor(void)
{
BOOL ret;
PSECURITY_DESCRIPTOR pSD;
static const WCHAR Blank[] = { 0 };
unsigned int i;
ULONG size;
ACL *acl;
static const struct
{
const char *sidstring;
DWORD revision;
BOOL ret;
DWORD GLE;
DWORD altGLE;
} cssd[] =
{
{ "D:(A;;GA;;;WD)", 0xdeadbeef, FALSE, ERROR_UNKNOWN_REVISION },
/* test ACE string type */
{ "D:(A;;GA;;;WD)", SDDL_REVISION_1, TRUE },
{ "D:(D;;GA;;;WD)", SDDL_REVISION_1, TRUE },
{ "ERROR:(D;;GA;;;WD)", SDDL_REVISION_1, FALSE, ERROR_INVALID_PARAMETER },
/* test ACE string with spaces */
{ " D:(D;;GA;;;WD)", SDDL_REVISION_1, TRUE },
{ "D: (D;;GA;;;WD)", SDDL_REVISION_1, TRUE },
{ "D:( D;;GA;;;WD)", SDDL_REVISION_1, TRUE },
{ "D:(D ;;GA;;;WD)", SDDL_REVISION_1, FALSE, RPC_S_INVALID_STRING_UUID, ERROR_INVALID_ACL }, /* Vista+ */
{ "D:(D; ;GA;;;WD)", SDDL_REVISION_1, TRUE },
{ "D:(D;; GA;;;WD)", SDDL_REVISION_1, TRUE },
{ "D:(D;;GA ;;;WD)", SDDL_REVISION_1, FALSE, ERROR_INVALID_ACL },
{ "D:(D;;GA; ;;WD)", SDDL_REVISION_1, TRUE },
{ "D:(D;;GA;; ;WD)", SDDL_REVISION_1, TRUE },
{ "D:(D;;GA;;; WD)", SDDL_REVISION_1, TRUE },
{ "D:(D;;GA;;;WD )", SDDL_REVISION_1, TRUE },
/* test ACE string access rights */
{ "D:(A;;GA;;;WD)", SDDL_REVISION_1, TRUE },
{ "D:(A;;GRGWGX;;;WD)", SDDL_REVISION_1, TRUE },
{ "D:(A;;RCSDWDWO;;;WD)", SDDL_REVISION_1, TRUE },
{ "D:(A;;RPWPCCDCLCSWLODTCR;;;WD)", SDDL_REVISION_1, TRUE },
{ "D:(A;;FAFRFWFX;;;WD)", SDDL_REVISION_1, TRUE },
{ "D:(A;;KAKRKWKX;;;WD)", SDDL_REVISION_1, TRUE },
{ "D:(A;;0xFFFFFFFF;;;WD)", SDDL_REVISION_1, TRUE },
{ "S:(AU;;0xFFFFFFFF;;;WD)", SDDL_REVISION_1, TRUE },
/* test ACE string access right error case */
{ "D:(A;;ROB;;;WD)", SDDL_REVISION_1, FALSE, ERROR_INVALID_ACL },
/* test behaviour with empty strings */
{ "", SDDL_REVISION_1, TRUE },
/* test ACE string SID */
{ "D:(D;;GA;;;S-1-0-0)", SDDL_REVISION_1, TRUE },
{ "D:(D;;GA;;;Nonexistent account)", SDDL_REVISION_1, FALSE, ERROR_INVALID_ACL, ERROR_INVALID_SID } /* W2K */
};
if (!pConvertStringSecurityDescriptorToSecurityDescriptorA)
{
win_skip("ConvertStringSecurityDescriptorToSecurityDescriptor is not available\n");
return;
}
for (i = 0; i < ARRAY_SIZE(cssd); i++)
{
DWORD GLE;
SetLastError(0xdeadbeef);
ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
cssd[i].sidstring, cssd[i].revision, &pSD, NULL);
GLE = GetLastError();
ok(ret == cssd[i].ret, "(%02u) Expected %s (%d)\n", i, cssd[i].ret ? "success" : "failure", GLE);
if (!cssd[i].ret)
ok(GLE == cssd[i].GLE ||
(cssd[i].altGLE && GLE == cssd[i].altGLE),
"(%02u) Unexpected last error %d\n", i, GLE);
if (ret)
LocalFree(pSD);
}
/* test behaviour with NULL parameters */
SetLastError(0xdeadbeef);
ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
NULL, 0xdeadbeef, &pSD, NULL);
todo_wine
ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
"ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
GetLastError());
SetLastError(0xdeadbeef);
ret = pConvertStringSecurityDescriptorToSecurityDescriptorW(
NULL, 0xdeadbeef, &pSD, NULL);
ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
"ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
GetLastError());
SetLastError(0xdeadbeef);
ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
"D:(A;;ROB;;;WD)", 0xdeadbeef, NULL, NULL);
ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
"ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
GetLastError());
SetLastError(0xdeadbeef);
ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
"D:(A;;ROB;;;WD)", SDDL_REVISION_1, NULL, NULL);
ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER,
"ConvertStringSecurityDescriptorToSecurityDescriptor should have failed with ERROR_INVALID_PARAMETER instead of %d\n",
GetLastError());
/* test behaviour with empty strings */
SetLastError(0xdeadbeef);
ret = pConvertStringSecurityDescriptorToSecurityDescriptorW(
Blank, SDDL_REVISION_1, &pSD, NULL);
ok(ret, "ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %d\n", GetLastError());
LocalFree(pSD);
SetLastError(0xdeadbeef);
ret = pConvertStringSecurityDescriptorToSecurityDescriptorA(
"D:P(A;;GRGW;;;BA)(A;;GRGW;;;S-1-5-21-0-0-0-1000)S:(ML;;NWNR;;;S-1-16-12288)", SDDL_REVISION_1, &pSD, NULL);
ok(ret || broken(!ret && GetLastError() == ERROR_INVALID_DATATYPE) /* win2k */,
"ConvertStringSecurityDescriptorToSecurityDescriptor failed with error %u\n", GetLastError());
if (ret) LocalFree(pSD);
/* empty DACL */
size = 0;
SetLastError(0xdeadbeef);
ret = pConvertStringSecurityDescriptorToSecurityDescriptorA("D:", SDDL_REVISION_1, &pSD, &size);
ok(ret, "unexpected error %u\n", GetLastError());
ok(size == sizeof(SECURITY_DESCRIPTOR_RELATIVE) + sizeof(ACL), "got %u\n", size);
acl = (ACL *)((char *)pSD + sizeof(SECURITY_DESCRIPTOR_RELATIVE));
ok(acl->AclRevision == ACL_REVISION, "got %u\n", acl->AclRevision);
ok(!acl->Sbz1, "got %u\n", acl->Sbz1);
ok(acl->AclSize == sizeof(*acl), "got %u\n", acl->AclSize);
ok(!acl->AceCount, "got %u\n", acl->AceCount);
ok(!acl->Sbz2, "got %u\n", acl->Sbz2);
LocalFree(pSD);
/* empty SACL */
size = 0;
SetLastError(0xdeadbeef);
ret = pConvertStringSecurityDescriptorToSecurityDescriptorA("S:", SDDL_REVISION_1, &pSD, &size);
ok(ret, "unexpected error %u\n", GetLastError());
ok(size == sizeof(SECURITY_DESCRIPTOR_RELATIVE) + sizeof(ACL), "got %u\n", size);
acl = (ACL *)((char *)pSD + sizeof(SECURITY_DESCRIPTOR_RELATIVE));
ok(!acl->Sbz1, "got %u\n", acl->Sbz1);
ok(acl->AclSize == sizeof(*acl), "got %u\n", acl->AclSize);
ok(!acl->AceCount, "got %u\n", acl->AceCount);
ok(!acl->Sbz2, "got %u\n", acl->Sbz2);
LocalFree(pSD);
}
static void test_ConvertSecurityDescriptorToString(void)
{
SECURITY_DESCRIPTOR desc;
SECURITY_INFORMATION sec_info = OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION|SACL_SECURITY_INFORMATION;
LPSTR string;
DWORD size;
PSID psid, psid2;
PACL pacl;
char sid_buf[256];
char acl_buf[8192];
ULONG len;
if (!pConvertSecurityDescriptorToStringSecurityDescriptorA)
{
win_skip("ConvertSecurityDescriptorToStringSecurityDescriptor is not available\n");
return;
}
if (!pCreateWellKnownSid)
{
win_skip("CreateWellKnownSid is not available\n");
return;
}
/* It seems Windows XP adds an extra character to the length of the string for each ACE in an ACL. We
* don't replicate this feature so we only test len >= strlen+1. */
#define CHECK_RESULT_AND_FREE(exp_str) \
ok(strcmp(string, (exp_str)) == 0, "String mismatch (expected \"%s\", got \"%s\")\n", (exp_str), string); \
ok(len >= (strlen(exp_str) + 1), "Length mismatch (expected %d, got %d)\n", lstrlenA(exp_str) + 1, len); \
LocalFree(string);
#define CHECK_ONE_OF_AND_FREE(exp_str1, exp_str2) \
ok(strcmp(string, (exp_str1)) == 0 || strcmp(string, (exp_str2)) == 0, "String mismatch (expected\n\"%s\" or\n\"%s\", got\n\"%s\")\n", (exp_str1), (exp_str2), string); \
ok(len >= (strlen(exp_str1) + 1) || len >= (strlen(exp_str2) + 1), "Length mismatch (expected %d or %d, got %d)\n", lstrlenA(exp_str1) + 1, lstrlenA(exp_str2) + 1, len); \
LocalFree(string);
InitializeSecurityDescriptor(&desc, SECURITY_DESCRIPTOR_REVISION);
ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
CHECK_RESULT_AND_FREE("");
size = 4096;
pCreateWellKnownSid(WinLocalSid, NULL, sid_buf, &size);
SetSecurityDescriptorOwner(&desc, sid_buf, FALSE);
ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
CHECK_RESULT_AND_FREE("O:S-1-2-0");
SetSecurityDescriptorOwner(&desc, sid_buf, TRUE);
ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
CHECK_RESULT_AND_FREE("O:S-1-2-0");
size = sizeof(sid_buf);
pCreateWellKnownSid(WinLocalSystemSid, NULL, sid_buf, &size);
SetSecurityDescriptorOwner(&desc, sid_buf, TRUE);
ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
CHECK_RESULT_AND_FREE("O:SY");
pConvertStringSidToSidA("S-1-5-21-93476-23408-4576", &psid);
SetSecurityDescriptorGroup(&desc, psid, TRUE);
ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576");
ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, GROUP_SECURITY_INFORMATION, &string, &len), "Conversion failed\n");
CHECK_RESULT_AND_FREE("G:S-1-5-21-93476-23408-4576");
pacl = (PACL)acl_buf;
InitializeAcl(pacl, sizeof(acl_buf), ACL_REVISION);
SetSecurityDescriptorDacl(&desc, TRUE, pacl, TRUE);
ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:");
SetSecurityDescriptorDacl(&desc, TRUE, pacl, FALSE);
ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:");
pConvertStringSidToSidA("S-1-5-6", &psid2);
pAddAccessAllowedAceEx(pacl, ACL_REVISION, NO_PROPAGATE_INHERIT_ACE, 0xf0000000, psid2);
ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:(A;NP;GAGXGWGR;;;SU)");
pAddAccessAllowedAceEx(pacl, ACL_REVISION, INHERIT_ONLY_ACE|INHERITED_ACE, 0x00000003, psid2);
ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)");
pAddAccessDeniedAceEx(pacl, ACL_REVISION, OBJECT_INHERIT_ACE|CONTAINER_INHERIT_ACE, 0xffffffff, psid);
ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)");
pacl = (PACL)acl_buf;
InitializeAcl(pacl, sizeof(acl_buf), ACL_REVISION);
SetSecurityDescriptorSacl(&desc, TRUE, pacl, FALSE);
ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
CHECK_RESULT_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:S:");
/* fails in win2k */
SetSecurityDescriptorDacl(&desc, TRUE, NULL, FALSE);
pAddAuditAccessAceEx(pacl, ACL_REVISION, VALID_INHERIT_FLAGS, KEY_READ|KEY_WRITE, psid2, TRUE, TRUE);
if (pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len))
{
CHECK_ONE_OF_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)", /* XP */
"O:SYG:S-1-5-21-93476-23408-4576D:NO_ACCESS_CONTROLS:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)" /* Vista */);
}
/* fails in win2k */
pAddAuditAccessAceEx(pacl, ACL_REVISION, NO_PROPAGATE_INHERIT_ACE, FILE_GENERIC_READ|FILE_GENERIC_WRITE, psid2, TRUE, FALSE);
if (pConvertSecurityDescriptorToStringSecurityDescriptorA(&desc, SDDL_REVISION_1, sec_info, &string, &len))
{
CHECK_ONE_OF_AND_FREE("O:SYG:S-1-5-21-93476-23408-4576D:S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)", /* XP */
"O:SYG:S-1-5-21-93476-23408-4576D:NO_ACCESS_CONTROLS:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)" /* Vista */);
}
LocalFree(psid2);
LocalFree(psid);
}
static void test_SetSecurityDescriptorControl (PSECURITY_DESCRIPTOR sec)
{
SECURITY_DESCRIPTOR_CONTROL ref;
SECURITY_DESCRIPTOR_CONTROL test;
SECURITY_DESCRIPTOR_CONTROL const mutable
= SE_DACL_AUTO_INHERIT_REQ | SE_SACL_AUTO_INHERIT_REQ
| SE_DACL_AUTO_INHERITED | SE_SACL_AUTO_INHERITED
| SE_DACL_PROTECTED | SE_SACL_PROTECTED
| 0x00000040 | 0x00000080 /* not defined in winnt.h */
;
SECURITY_DESCRIPTOR_CONTROL const immutable
= SE_OWNER_DEFAULTED | SE_GROUP_DEFAULTED
| SE_DACL_PRESENT | SE_DACL_DEFAULTED
| SE_SACL_PRESENT | SE_SACL_DEFAULTED
| SE_RM_CONTROL_VALID | SE_SELF_RELATIVE
;
int bit;
DWORD dwRevision;
LPCSTR fmt = "Expected error %s, got %u\n";
GetSecurityDescriptorControl (sec, &ref, &dwRevision);
/* The mutable bits are mutable regardless of the truth of
SE_DACL_PRESENT and/or SE_SACL_PRESENT */
/* Check call barfs if any bit-of-interest is immutable */
for (bit = 0; bit < 16; ++bit)
{
SECURITY_DESCRIPTOR_CONTROL const bitOfInterest = 1 << bit;
SECURITY_DESCRIPTOR_CONTROL setOrClear = ref & bitOfInterest;
SECURITY_DESCRIPTOR_CONTROL ctrl;
DWORD dwExpect = (bitOfInterest & immutable)
? ERROR_INVALID_PARAMETER : 0xbebecaca;
LPCSTR strExpect = (bitOfInterest & immutable)
? "ERROR_INVALID_PARAMETER" : "0xbebecaca";
ctrl = (bitOfInterest & mutable) ? ref + bitOfInterest : ref;
setOrClear ^= bitOfInterest;
SetLastError (0xbebecaca);
pSetSecurityDescriptorControl (sec, bitOfInterest, setOrClear);
ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
GetSecurityDescriptorControl(sec, &test, &dwRevision);
expect_eq(test, ctrl, int, "%x");
setOrClear ^= bitOfInterest;
SetLastError (0xbebecaca);
pSetSecurityDescriptorControl (sec, bitOfInterest, setOrClear);
ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
GetSecurityDescriptorControl (sec, &test, &dwRevision);
expect_eq(test, ref, int, "%x");
}
/* Check call barfs if any bit-to-set is immutable
even when not a bit-of-interest */
for (bit = 0; bit < 16; ++bit)
{
SECURITY_DESCRIPTOR_CONTROL const bitsOfInterest = mutable;
SECURITY_DESCRIPTOR_CONTROL setOrClear = ref & bitsOfInterest;
SECURITY_DESCRIPTOR_CONTROL ctrl;
DWORD dwExpect = ((1 << bit) & immutable)
? ERROR_INVALID_PARAMETER : 0xbebecaca;
LPCSTR strExpect = ((1 << bit) & immutable)
? "ERROR_INVALID_PARAMETER" : "0xbebecaca";
ctrl = ((1 << bit) & immutable) ? test : ref | mutable;
setOrClear ^= bitsOfInterest;
SetLastError (0xbebecaca);
pSetSecurityDescriptorControl (sec, bitsOfInterest, setOrClear | (1 << bit));
ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
GetSecurityDescriptorControl(sec, &test, &dwRevision);
expect_eq(test, ctrl, int, "%x");
ctrl = ((1 << bit) & immutable) ? test : ref | (1 << bit);
setOrClear ^= bitsOfInterest;
SetLastError (0xbebecaca);
pSetSecurityDescriptorControl (sec, bitsOfInterest, setOrClear | (1 << bit));
ok (GetLastError () == dwExpect, fmt, strExpect, GetLastError ());
GetSecurityDescriptorControl(sec, &test, &dwRevision);
expect_eq(test, ctrl, int, "%x");
}
}
static void test_PrivateObjectSecurity(void)
{
SECURITY_INFORMATION sec_info = OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION|SACL_SECURITY_INFORMATION;
SECURITY_DESCRIPTOR_CONTROL ctrl;
PSECURITY_DESCRIPTOR sec;
DWORD dwDescSize;
DWORD dwRevision;
DWORD retSize;
LPSTR string;
ULONG len;
PSECURITY_DESCRIPTOR buf;
BOOL ret;
if (!pConvertStringSecurityDescriptorToSecurityDescriptorA)
{
win_skip("ConvertStringSecurityDescriptorToSecurityDescriptor is not available\n");
return;
}
ok(pConvertStringSecurityDescriptorToSecurityDescriptorA(
"O:SY"
"G:S-1-5-21-93476-23408-4576"
"D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)"
"(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
"S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)",
SDDL_REVISION_1, &sec, &dwDescSize), "Creating descriptor failed\n");
test_SetSecurityDescriptorControl(sec);
LocalFree(sec);
ok(pConvertStringSecurityDescriptorToSecurityDescriptorA(
"O:SY"
"G:S-1-5-21-93476-23408-4576",
SDDL_REVISION_1, &sec, &dwDescSize), "Creating descriptor failed\n");
test_SetSecurityDescriptorControl(sec);
LocalFree(sec);
ok(pConvertStringSecurityDescriptorToSecurityDescriptorA(
"O:SY"
"G:S-1-5-21-93476-23408-4576"
"D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
"S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)", SDDL_REVISION_1, &sec, &dwDescSize), "Creating descriptor failed\n");
buf = HeapAlloc(GetProcessHeap(), 0, dwDescSize);
pSetSecurityDescriptorControl(sec, SE_DACL_PROTECTED, SE_DACL_PROTECTED);
GetSecurityDescriptorControl(sec, &ctrl, &dwRevision);
expect_eq(ctrl, 0x9014, int, "%x");
ret = GetPrivateObjectSecurity(sec, GROUP_SECURITY_INFORMATION, buf, dwDescSize, &retSize);
ok(ret, "GetPrivateObjectSecurity failed (err=%u)\n", GetLastError());
ok(retSize <= dwDescSize, "Buffer too small (%d vs %d)\n", retSize, dwDescSize);
ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(buf, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
CHECK_RESULT_AND_FREE("G:S-1-5-21-93476-23408-4576");
GetSecurityDescriptorControl(buf, &ctrl, &dwRevision);
expect_eq(ctrl, 0x8000, int, "%x");
ret = GetPrivateObjectSecurity(sec, GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION, buf, dwDescSize, &retSize);
ok(ret, "GetPrivateObjectSecurity failed (err=%u)\n", GetLastError());
ok(retSize <= dwDescSize, "Buffer too small (%d vs %d)\n", retSize, dwDescSize);
ret = pConvertSecurityDescriptorToStringSecurityDescriptorA(buf, SDDL_REVISION_1, sec_info, &string, &len);
ok(ret, "Conversion failed err=%u\n", GetLastError());
CHECK_ONE_OF_AND_FREE("G:S-1-5-21-93476-23408-4576D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)",
"G:S-1-5-21-93476-23408-4576D:P(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"); /* Win7 */
GetSecurityDescriptorControl(buf, &ctrl, &dwRevision);
expect_eq(ctrl & (~ SE_DACL_PROTECTED), 0x8004, int, "%x");
ret = GetPrivateObjectSecurity(sec, sec_info, buf, dwDescSize, &retSize);
ok(ret, "GetPrivateObjectSecurity failed (err=%u)\n", GetLastError());
ok(retSize == dwDescSize, "Buffer too small (%d vs %d)\n", retSize, dwDescSize);
ok(pConvertSecurityDescriptorToStringSecurityDescriptorA(buf, SDDL_REVISION_1, sec_info, &string, &len), "Conversion failed\n");
CHECK_ONE_OF_AND_FREE("O:SY"
"G:S-1-5-21-93476-23408-4576"
"D:(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
"S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)",
"O:SY"
"G:S-1-5-21-93476-23408-4576"
"D:P(A;NP;GAGXGWGR;;;SU)(A;IOID;CCDC;;;SU)(D;OICI;0xffffffff;;;S-1-5-21-93476-23408-4576)"
"S:(AU;OICINPIOIDSAFA;CCDCLCSWRPRC;;;SU)(AU;NPSA;0x12019f;;;SU)"); /* Win7 */
GetSecurityDescriptorControl(buf, &ctrl, &dwRevision);
expect_eq(ctrl & (~ SE_DACL_PROTECTED), 0x8014, int, "%x");
SetLastError(0xdeadbeef);
ok(GetPrivateObjectSecurity(sec, sec_info, buf, 5, &retSize) == FALSE, "GetPrivateObjectSecurity should have failed\n");
ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Expected error ERROR_INSUFFICIENT_BUFFER, got %u\n", GetLastError());
LocalFree(sec);
HeapFree(GetProcessHeap(), 0, buf);
}
#undef CHECK_RESULT_AND_FREE
#undef CHECK_ONE_OF_AND_FREE
static void test_acls(void)
{
char buffer[256];
PACL pAcl = (PACL)buffer;
BOOL ret;
SetLastError(0xdeadbeef);
ret = InitializeAcl(pAcl, sizeof(ACL) - 1, ACL_REVISION);
if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
{
win_skip("InitializeAcl is not implemented\n");
return;
}
ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "InitializeAcl with too small a buffer should have failed with ERROR_INSUFFICIENT_BUFFER instead of %d\n", GetLastError());
SetLastError(0xdeadbeef);
ret = InitializeAcl(pAcl, 0xffffffff, ACL_REVISION);
ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER, "InitializeAcl with too large a buffer should have failed with ERROR_INVALID_PARAMETER instead of %d\n", GetLastError());
SetLastError(0xdeadbeef);
ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION1);
ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER, "InitializeAcl(ACL_REVISION1) should have failed with ERROR_INVALID_PARAMETER instead of %d\n", GetLastError());
ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION2);
ok(ret, "InitializeAcl(ACL_REVISION2) failed with error %d\n", GetLastError());
ret = IsValidAcl(pAcl);
ok(ret, "IsValidAcl failed with error %d\n", GetLastError());
ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION3);
ok(ret, "InitializeAcl(ACL_REVISION3) failed with error %d\n", GetLastError());
ret = IsValidAcl(pAcl);
ok(ret, "IsValidAcl failed with error %d\n", GetLastError());
SetLastError(0xdeadbeef);
ret = InitializeAcl(pAcl, sizeof(buffer), ACL_REVISION4);
if (GetLastError() != ERROR_INVALID_PARAMETER)
{
ok(ret, "InitializeAcl(ACL_REVISION4) failed with error %d\n", GetLastError());
ret = IsValidAcl(pAcl);
ok(ret, "IsValidAcl failed with error %d\n", GetLastError());
}
else
win_skip("ACL_REVISION4 is not implemented on NT4\n");
SetLastError(0xdeadbeef);
ret = InitializeAcl(pAcl, sizeof(buffer), -1);
ok(!ret && GetLastError() == ERROR_INVALID_PARAMETER, "InitializeAcl(-1) failed with error %d\n", GetLastError());
}
static void test_GetSecurityInfo(void)
{
char domain_users_ptr[sizeof(TOKEN_USER) + sizeof(SID) + sizeof(DWORD)*SID_MAX_SUB_AUTHORITIES];
char b[sizeof(TOKEN_USER) + sizeof(SID) + sizeof(DWORD)*SID_MAX_SUB_AUTHORITIES];
char admin_ptr[sizeof(SID)+sizeof(ULONG)*SID_MAX_SUB_AUTHORITIES], dacl[100];
PSID domain_users_sid = (PSID) domain_users_ptr, domain_sid;
SID_IDENTIFIER_AUTHORITY sia = { SECURITY_NT_AUTHORITY };
int domain_users_ace_id = -1, admins_ace_id = -1, i;
DWORD sid_size = sizeof(admin_ptr), l = sizeof(b);
PSID admin_sid = (PSID) admin_ptr, user_sid;
char sd[SECURITY_DESCRIPTOR_MIN_LENGTH];
BOOL owner_defaulted, group_defaulted;
BOOL dacl_defaulted, dacl_present;
ACL_SIZE_INFORMATION acl_size;
PSECURITY_DESCRIPTOR pSD;
ACCESS_ALLOWED_ACE *ace;
HANDLE token, obj;
PSID owner, group;
BOOL bret = TRUE;
PACL pDacl;
BYTE flags;
DWORD ret;
if (!pGetSecurityInfo || !pSetSecurityInfo)
{
win_skip("[Get|Set]SecurityInfo is not available\n");
return;
}
if (!OpenThreadToken(GetCurrentThread(), TOKEN_READ, TRUE, &token))
{
if (GetLastError() != ERROR_NO_TOKEN) bret = FALSE;
else if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &token)) bret = FALSE;
}
if (!bret)
{
win_skip("Failed to get current user token\n");
return;
}
bret = GetTokenInformation(token, TokenUser, b, l, &l);
ok(bret, "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
CloseHandle( token );
user_sid = ((TOKEN_USER *)b)->User.Sid;
/* Create something. Files have lots of associated security info. */
obj = CreateFileA(myARGV[0], GENERIC_READ|WRITE_DAC, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (obj == INVALID_HANDLE_VALUE)
{
skip("Couldn't create an object for GetSecurityInfo test\n");
return;
}
ret = pGetSecurityInfo(obj, SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
&owner, &group, &pDacl, NULL, &pSD);
if (ret == ERROR_CALL_NOT_IMPLEMENTED)
{
win_skip("GetSecurityInfo is not implemented\n");
CloseHandle(obj);
return;
}
ok(ret == ERROR_SUCCESS, "GetSecurityInfo returned %d\n", ret);
ok(pSD != NULL, "GetSecurityInfo\n");
ok(owner != NULL, "GetSecurityInfo\n");
ok(group != NULL, "GetSecurityInfo\n");
if (pDacl != NULL)
ok(IsValidAcl(pDacl), "GetSecurityInfo\n");
else
win_skip("No ACL information returned\n");
LocalFree(pSD);
if (!pCreateWellKnownSid)
{
win_skip("NULL parameter test would crash on NT4\n");
CloseHandle(obj);
return;
}
/* If we don't ask for the security descriptor, Windows will still give us
the other stuff, leaving us no way to free it. */
ret = pGetSecurityInfo(obj, SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
&owner, &group, &pDacl, NULL, NULL);
ok(ret == ERROR_SUCCESS, "GetSecurityInfo returned %d\n", ret);
ok(owner != NULL, "GetSecurityInfo\n");
ok(group != NULL, "GetSecurityInfo\n");
if (pDacl != NULL)
ok(IsValidAcl(pDacl), "GetSecurityInfo\n");
else
win_skip("No ACL information returned\n");
/* Create security descriptor information and test that it comes back the same */
pSD = &sd;
pDacl = (PACL)&dacl;
InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION);
pCreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, admin_sid, &sid_size);
bret = InitializeAcl(pDacl, sizeof(dacl), ACL_REVISION);
ok(bret, "Failed to initialize ACL.\n");
bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, user_sid);
ok(bret, "Failed to add Current User to ACL.\n");
bret = pAddAccessAllowedAceEx(pDacl, ACL_REVISION, 0, GENERIC_ALL, admin_sid);
ok(bret, "Failed to add Administrator Group to ACL.\n");
bret = SetSecurityDescriptorDacl(pSD, TRUE, pDacl, FALSE);
ok(bret, "Failed to add ACL to security descriptor.\n");
ret = pSetSecurityInfo(obj, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
NULL, NULL, pDacl, NULL);
ok(ret == ERROR_SUCCESS, "SetSecurityInfo returned %d\n", ret);
ret = pGetSecurityInfo(obj, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
NULL, NULL, &pDacl, NULL, &pSD);
ok(ret == ERROR_SUCCESS, "GetSecurityInfo returned %d\n", ret);
ok(pDacl && IsValidAcl(pDacl), "GetSecurityInfo returned invalid DACL.\n");
bret = pGetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
ok(bret, "GetAclInformation failed\n");
if (acl_size.AceCount > 0)
{
bret = pGetAce(pDacl, 0, (VOID **)&ace);
ok(bret, "Failed to get Current User ACE.\n");
bret = EqualSid(&ace->SidStart, user_sid);
todo_wine ok(bret, "Current User ACE (%s) != Current User SID (%s).\n",
debugstr_sid(&ace->SidStart), debugstr_sid(user_sid));
ok(((ACE_HEADER *)ace)->AceFlags == 0,
"Current User ACE has unexpected flags (0x%x != 0x0)\n", ((ACE_HEADER *)ace)->AceFlags);
ok(ace->Mask == 0x1f01ff, "Current User ACE has unexpected mask (0x%x != 0x1f01ff)\n",
ace->Mask);
}
if (acl_size.AceCount > 1)
{
bret = pGetAce(pDacl, 1, (VOID **)&ace);
ok(bret, "Failed to get Administators Group ACE.\n");
bret = EqualSid(&ace->SidStart, admin_sid);
todo_wine ok(bret, "Administators Group ACE (%s) != Administators Group SID (%s).\n", debugstr_sid(&ace->SidStart), debugstr_sid(admin_sid));
ok(((ACE_HEADER *)ace)->AceFlags == 0,
"Administators Group ACE has unexpected flags (0x%x != 0x0)\n", ((ACE_HEADER *)ace)->AceFlags);
ok(ace->Mask == 0x1f01ff, "Administators Group ACE has unexpected mask (0x%x != 0x1f01ff)\n",
ace->Mask);
}
LocalFree(pSD);
CloseHandle(obj);
/* Obtain the "domain users" SID from the user SID */
if (!AllocateAndInitializeSid(&sia, 4, *GetSidSubAuthority(user_sid, 0),
*GetSidSubAuthority(user_sid, 1),
*GetSidSubAuthority(user_sid, 2),
*GetSidSubAuthority(user_sid, 3), 0, 0, 0, 0, &domain_sid))
{
win_skip("Failed to get current domain SID\n");
return;
}
sid_size = sizeof(domain_users_ptr);
pCreateWellKnownSid(WinAccountDomainUsersSid, domain_sid, domain_users_sid, &sid_size);
FreeSid(domain_sid);
/* Test querying the ownership of a process */
ret = pGetSecurityInfo(GetCurrentProcess(), SE_KERNEL_OBJECT,
OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION,
NULL, NULL, NULL, NULL, &pSD);
ok(!ret, "GetNamedSecurityInfo failed with error %d\n", ret);
bret = GetSecurityDescriptorOwner(pSD, &owner, &owner_defaulted);
ok(bret, "GetSecurityDescriptorOwner failed with error %d\n", GetLastError());
ok(owner != NULL, "owner should not be NULL\n");
ok(EqualSid(owner, admin_sid) || EqualSid(owner, user_sid),
"Process owner SID != Administrators SID.\n");
bret = GetSecurityDescriptorGroup(pSD, &group, &group_defaulted);
ok(bret, "GetSecurityDescriptorGroup failed with error %d\n", GetLastError());
ok(group != NULL, "group should not be NULL\n");
ok(EqualSid(group, domain_users_sid), "Process group SID != Domain Users SID.\n");
LocalFree(pSD);
/* Test querying the DACL of a process */
ret = pGetSecurityInfo(GetCurrentProcess(), SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION,
NULL, NULL, NULL, NULL, &pSD);
ok(!ret, "GetSecurityInfo failed with error %d\n", ret);
bret = GetSecurityDescriptorDacl(pSD, &dacl_present, &pDacl, &dacl_defaulted);
ok(bret, "GetSecurityDescriptorDacl failed with error %d\n", GetLastError());
ok(dacl_present, "DACL should be present\n");
ok(pDacl && IsValidAcl(pDacl), "GetSecurityDescriptorDacl returned invalid DACL.\n");
bret = pGetAclInformation(pDacl, &acl_size, sizeof(acl_size), AclSizeInformation);
ok(bret, "GetAclInformation failed\n");
ok(acl_size.AceCount != 0, "GetAclInformation returned no ACLs\n");
for (i=0; i<acl_size.AceCount; i++)
{
bret = pGetAce(pDacl, i, (VOID **)&ace);
ok(bret, "Failed to get ACE %d.\n", i);
bret = EqualSid(&ace->SidStart, domain_users_sid);
if (bret) domain_users_ace_id = i;
bret = EqualSid(&ace->SidStart, admin_sid);
if (bret) admins_ace_id = i;
}
ok(domain_users_ace_id != -1 || broken(domain_users_ace_id == -1) /* win2k */,
"Domain Users ACE not found.\n");
if (domain_users_ace_id != -1)
{
bret = pGetAce(pDacl, domain_users_ace_id, (VOID **)&ace);
ok(bret, "Failed to get Domain Users ACE.\n");
flags = ((ACE_HEADER *)ace)->AceFlags;
ok(flags == (INHERIT_ONLY_ACE|CONTAINER_INHERIT_ACE),
"Domain Users ACE has unexpected flags (0x%x != 0x%x)\n", flags,
INHERIT_ONLY_ACE|CONTAINER_INHERIT_ACE);
ok(ace->Mask == GENERIC_READ, "Domain Users ACE has unexpected mask (0x%x != 0x%x)\n",
ace->Mask, GENERIC_READ);
}
ok(admins_ace_id != -1 || broken(admins_ace_id == -1) /* xp */,
"Builtin Admins ACE not found.\n");
if (admins_ace_id != -1)
{
bret = pGetAce(pDacl, admins_ace_id, (VOID **)&ace);
ok(bret, "Failed to get Builtin Admins ACE.\n");
flags = ((ACE_HEADER *)ace)->AceFlags;
ok(flags == 0x0, "Builtin Admins ACE has unexpected flags (0x%x != 0x0)\n", flags);
ok(ace->Mask == PROCESS_ALL_ACCESS || broken(ace->Mask == 0x1f0fff) /* win2k */,
"Builtin Admins ACE has unexpected mask (0x%x != 0x%x)\n", ace->Mask, PROCESS_ALL_ACCESS);
}
LocalFree(pSD);
}
static void test_GetSidSubAuthority(void)
{
PSID psid = NULL;
if (!pGetSidSubAuthority || !pConvertStringSidToSidA || !pIsValidSid || !pGetSidSubAuthorityCount)
{
win_skip("Some functions not available\n");
return;
}
/* Note: on windows passing in an invalid index like -1, lets GetSidSubAuthority return 0x05000000 but
still GetLastError returns ERROR_SUCCESS then. We don't test these unlikely cornercases here for now */
ok(pConvertStringSidToSidA("S-1-5-21-93476-23408-4576",&psid),"ConvertStringSidToSidA failed\n");
ok(pIsValidSid(psid),"Sid is not valid\n");
SetLastError(0xbebecaca);
ok(*pGetSidSubAuthorityCount(psid) == 4,"GetSidSubAuthorityCount gave %d expected 4\n",*pGetSidSubAuthorityCount(psid));
ok(GetLastError() == 0,"GetLastError returned %d instead of 0\n",GetLastError());
SetLastError(0xbebecaca);
ok(*pGetSidSubAuthority(psid,0) == 21,"GetSidSubAuthority gave %d expected 21\n",*pGetSidSubAuthority(psid,0));
ok(GetLastError() == 0,"GetLastError returned %d instead of 0\n",GetLastError());
SetLastError(0xbebecaca);
ok(*pGetSidSubAuthority(psid,1) == 93476,"GetSidSubAuthority gave %d expected 93476\n",*pGetSidSubAuthority(psid,1));
ok(GetLastError() == 0,"GetLastError returned %d instead of 0\n",GetLastError());
SetLastError(0xbebecaca);
ok(pGetSidSubAuthority(psid,4) != NULL,"Expected out of bounds GetSidSubAuthority to return a non-NULL pointer\n");
ok(GetLastError() == 0,"GetLastError returned %d instead of 0\n",GetLastError());
LocalFree(psid);
}
static void test_CheckTokenMembership(void)
{
PTOKEN_GROUPS token_groups;
DWORD size;
HANDLE process_token, token;
BOOL is_member;
BOOL ret;
DWORD i;
if (!pCheckTokenMembership)
{
win_skip("CheckTokenMembership is not available\n");
return;
}
ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE|TOKEN_QUERY, &process_token);
ok(ret, "OpenProcessToken failed with error %d\n", GetLastError());
ret = DuplicateToken(process_token, SecurityImpersonation, &token);
ok(ret, "DuplicateToken failed with error %d\n", GetLastError());
/* groups */
ret = GetTokenInformation(token, TokenGroups, NULL, 0, &size);
ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"GetTokenInformation(TokenGroups) %s with error %d\n",
ret ? "succeeded" : "failed", GetLastError());
token_groups = HeapAlloc(GetProcessHeap(), 0, size);
ret = GetTokenInformation(token, TokenGroups, token_groups, size, &size);
ok(ret, "GetTokenInformation(TokenGroups) failed with error %d\n", GetLastError());
for (i = 0; i < token_groups->GroupCount; i++)
{
if (token_groups->Groups[i].Attributes & SE_GROUP_ENABLED)
break;
}
if (i == token_groups->GroupCount)
{
HeapFree(GetProcessHeap(), 0, token_groups);
CloseHandle(token);
skip("user not a member of any group\n");
return;
}
is_member = FALSE;
ret = pCheckTokenMembership(token, token_groups->Groups[i].Sid, &is_member);
ok(ret, "CheckTokenMembership failed with error %d\n", GetLastError());
ok(is_member, "CheckTokenMembership should have detected sid as member\n");
is_member = FALSE;
ret = pCheckTokenMembership(NULL, token_groups->Groups[i].Sid, &is_member);
ok(ret, "CheckTokenMembership failed with error %d\n", GetLastError());
ok(is_member, "CheckTokenMembership should have detected sid as member\n");
is_member = TRUE;
SetLastError(0xdeadbeef);
ret = pCheckTokenMembership(process_token, token_groups->Groups[i].Sid, &is_member);
ok(!ret && GetLastError() == ERROR_NO_IMPERSONATION_TOKEN,
"CheckTokenMembership with process token %s with error %d\n",
ret ? "succeeded" : "failed", GetLastError());
ok(!is_member, "CheckTokenMembership should have cleared is_member\n");
HeapFree(GetProcessHeap(), 0, token_groups);
CloseHandle(token);
CloseHandle(process_token);
}
static void test_EqualSid(void)
{
PSID sid1, sid2;
BOOL ret;
SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
SetLastError(0xdeadbeef);
ret = AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &sid1);
if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
{
win_skip("AllocateAndInitializeSid is not implemented\n");
return;
}
ok(ret, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
ok(GetLastError() == 0xdeadbeef,
"AllocateAndInitializeSid shouldn't have set last error to %d\n",
GetLastError());
ret = AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID,
0, 0, 0, 0, 0, 0, 0, &sid2);
ok(ret, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
SetLastError(0xdeadbeef);
ret = EqualSid(sid1, sid2);
ok(!ret, "World and domain admins sids shouldn't have been equal\n");
ok(GetLastError() == ERROR_SUCCESS ||
broken(GetLastError() == 0xdeadbeef), /* NT4 */
"EqualSid should have set last error to ERROR_SUCCESS instead of %d\n",
GetLastError());
SetLastError(0xdeadbeef);
sid2 = FreeSid(sid2);
ok(!sid2, "FreeSid should have returned NULL instead of %p\n", sid2);
ok(GetLastError() == 0xdeadbeef,
"FreeSid shouldn't have set last error to %d\n",
GetLastError());
ret = AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &sid2);
ok(ret, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
SetLastError(0xdeadbeef);
ret = EqualSid(sid1, sid2);
ok(ret, "Same sids should have been equal %s != %s\n",
debugstr_sid(sid1), debugstr_sid(sid2));
ok(GetLastError() == ERROR_SUCCESS ||
broken(GetLastError() == 0xdeadbeef), /* NT4 */
"EqualSid should have set last error to ERROR_SUCCESS instead of %d\n",
GetLastError());
((SID *)sid2)->Revision = 2;
SetLastError(0xdeadbeef);
ret = EqualSid(sid1, sid2);
ok(!ret, "EqualSid with invalid sid should have returned FALSE\n");
ok(GetLastError() == ERROR_SUCCESS ||
broken(GetLastError() == 0xdeadbeef), /* NT4 */
"EqualSid should have set last error to ERROR_SUCCESS instead of %d\n",
GetLastError());
((SID *)sid2)->Revision = SID_REVISION;
FreeSid(sid1);
FreeSid(sid2);
}
static void test_GetUserNameA(void)
{
char buffer[UNLEN + 1], filler[UNLEN + 1];
DWORD required_len, buffer_len;
BOOL ret;
/* Test crashes on Windows. */
if (0)
{
SetLastError(0xdeadbeef);
GetUserNameA(NULL, NULL);
}
SetLastError(0xdeadbeef);
required_len = 0;
ret = GetUserNameA(NULL, &required_len);
ok(ret == FALSE, "GetUserNameA returned %d\n", ret);
ok(required_len != 0, "Outputted buffer length was %u\n", required_len);
ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
SetLastError(0xdeadbeef);
required_len = 1;
ret = GetUserNameA(NULL, &required_len);
ok(ret == FALSE, "GetUserNameA returned %d\n", ret);
ok(required_len != 0 && required_len != 1, "Outputted buffer length was %u\n", required_len);
ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
/* Tests crashes on Windows. */
if (0)
{
SetLastError(0xdeadbeef);
required_len = UNLEN + 1;
GetUserNameA(NULL, &required_len);
SetLastError(0xdeadbeef);
GetUserNameA(buffer, NULL);
}
memset(filler, 'x', sizeof(filler));
/* Note that GetUserNameA on XP and newer outputs the number of bytes
* required for a Unicode string, which affects a test in the next block. */
SetLastError(0xdeadbeef);
memcpy(buffer, filler, sizeof(filler));
required_len = 0;
ret = GetUserNameA(buffer, &required_len);
ok(ret == FALSE, "GetUserNameA returned %d\n", ret);
ok(!memcmp(buffer, filler, sizeof(filler)), "Output buffer was altered\n");
ok(required_len != 0, "Outputted buffer length was %u\n", required_len);
ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
SetLastError(0xdeadbeef);
memcpy(buffer, filler, sizeof(filler));
buffer_len = required_len;
ret = GetUserNameA(buffer, &buffer_len);
ok(ret == TRUE, "GetUserNameA returned %d, last error %u\n", ret, GetLastError());
ok(memcmp(buffer, filler, sizeof(filler)) != 0, "Output buffer was untouched\n");
ok(buffer_len == required_len ||
broken(buffer_len == required_len / sizeof(WCHAR)), /* XP+ */
"Outputted buffer length was %u\n", buffer_len);
/* Use the reported buffer size from the last GetUserNameA call and pass
* a length that is one less than the required value. */
SetLastError(0xdeadbeef);
memcpy(buffer, filler, sizeof(filler));
buffer_len--;
ret = GetUserNameA(buffer, &buffer_len);
ok(ret == FALSE, "GetUserNameA returned %d\n", ret);
ok(!memcmp(buffer, filler, sizeof(filler)), "Output buffer was untouched\n");
ok(buffer_len == required_len, "Outputted buffer length was %u\n", buffer_len);
ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
}
static void test_GetUserNameW(void)
{
WCHAR buffer[UNLEN + 1], filler[UNLEN + 1];
DWORD required_len, buffer_len;
BOOL ret;
/* Test crashes on Windows. */
if (0)
{
SetLastError(0xdeadbeef);
GetUserNameW(NULL, NULL);
}
SetLastError(0xdeadbeef);
required_len = 0;
ret = GetUserNameW(NULL, &required_len);
ok(ret == FALSE, "GetUserNameW returned %d\n", ret);
ok(required_len != 0, "Outputted buffer length was %u\n", required_len);
ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
SetLastError(0xdeadbeef);
required_len = 1;
ret = GetUserNameW(NULL, &required_len);
ok(ret == FALSE, "GetUserNameW returned %d\n", ret);
ok(required_len != 0 && required_len != 1, "Outputted buffer length was %u\n", required_len);
ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
/* Tests crash on Windows. */
if (0)
{
SetLastError(0xdeadbeef);
required_len = UNLEN + 1;
GetUserNameW(NULL, &required_len);
SetLastError(0xdeadbeef);
GetUserNameW(buffer, NULL);
}
memset(filler, 'x', sizeof(filler));
SetLastError(0xdeadbeef);
memcpy(buffer, filler, sizeof(filler));
required_len = 0;
ret = GetUserNameW(buffer, &required_len);
ok(ret == FALSE, "GetUserNameW returned %d\n", ret);
ok(!memcmp(buffer, filler, sizeof(filler)), "Output buffer was altered\n");
ok(required_len != 0, "Outputted buffer length was %u\n", required_len);
ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
SetLastError(0xdeadbeef);
memcpy(buffer, filler, sizeof(filler));
buffer_len = required_len;
ret = GetUserNameW(buffer, &buffer_len);
ok(ret == TRUE, "GetUserNameW returned %d, last error %u\n", ret, GetLastError());
ok(memcmp(buffer, filler, sizeof(filler)) != 0, "Output buffer was untouched\n");
ok(buffer_len == required_len, "Outputted buffer length was %u\n", buffer_len);
/* GetUserNameW on XP and newer writes a truncated portion of the username string to the buffer. */
SetLastError(0xdeadbeef);
memcpy(buffer, filler, sizeof(filler));
buffer_len--;
ret = GetUserNameW(buffer, &buffer_len);
ok(ret == FALSE, "GetUserNameW returned %d\n", ret);
ok(!memcmp(buffer, filler, sizeof(filler)) ||
broken(memcmp(buffer, filler, sizeof(filler)) != 0), /* XP+ */
"Output buffer was altered\n");
ok(buffer_len == required_len, "Outputted buffer length was %u\n", buffer_len);
ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Last error was %u\n", GetLastError());
}
static void test_CreateRestrictedToken(void)
{
HANDLE process_token, token, r_token;
PTOKEN_GROUPS token_groups, groups2;
SID_AND_ATTRIBUTES sattr;
SECURITY_IMPERSONATION_LEVEL level;
TOKEN_TYPE type;
BOOL is_member;
DWORD size;
BOOL ret;
DWORD i, j;
if (!pCreateRestrictedToken)
{
win_skip("CreateRestrictedToken is not available\n");
return;
}
ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE|TOKEN_QUERY, &process_token);
ok(ret, "got error %d\n", GetLastError());
ret = DuplicateTokenEx(process_token, TOKEN_DUPLICATE|TOKEN_ADJUST_GROUPS|TOKEN_QUERY,
NULL, SecurityImpersonation, TokenImpersonation, &token);
ok(ret, "got error %d\n", GetLastError());
/* groups */
ret = GetTokenInformation(token, TokenGroups, NULL, 0, &size);
ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"got %d with error %d\n", ret, GetLastError());
token_groups = HeapAlloc(GetProcessHeap(), 0, size);
ret = GetTokenInformation(token, TokenGroups, token_groups, size, &size);
ok(ret, "got error %d\n", GetLastError());
for (i = 0; i < token_groups->GroupCount; i++)
{
if (token_groups->Groups[i].Attributes & SE_GROUP_ENABLED)
break;
}
if (i == token_groups->GroupCount)
{
HeapFree(GetProcessHeap(), 0, token_groups);
CloseHandle(token);
skip("User not a member of any group\n");
return;
}
is_member = FALSE;
ret = pCheckTokenMembership(token, token_groups->Groups[i].Sid, &is_member);
ok(ret, "got error %d\n", GetLastError());
ok(is_member, "not a member\n");
/* disable a SID in new token */
sattr.Sid = token_groups->Groups[i].Sid;
sattr.Attributes = 0;
r_token = NULL;
ret = pCreateRestrictedToken(token, 0, 1, &sattr, 0, NULL, 0, NULL, &r_token);
ok(ret, "got error %d\n", GetLastError());
if (ret)
{
/* check if a SID is enabled */
is_member = TRUE;
ret = pCheckTokenMembership(r_token, token_groups->Groups[i].Sid, &is_member);
ok(ret, "got error %d\n", GetLastError());
todo_wine ok(!is_member, "not a member\n");
ret = GetTokenInformation(r_token, TokenGroups, NULL, 0, &size);
ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "got %d with error %d\n",
ret, GetLastError());
groups2 = HeapAlloc(GetProcessHeap(), 0, size);
ret = GetTokenInformation(r_token, TokenGroups, groups2, size, &size);
ok(ret, "got error %d\n", GetLastError());
for (j = 0; j < groups2->GroupCount; j++)
{
if (EqualSid(groups2->Groups[j].Sid, token_groups->Groups[i].Sid))
break;
}
todo_wine ok(groups2->Groups[j].Attributes & SE_GROUP_USE_FOR_DENY_ONLY,
"got wrong attributes\n");
todo_wine ok((groups2->Groups[j].Attributes & SE_GROUP_ENABLED) == 0,
"got wrong attributes\n");
HeapFree(GetProcessHeap(), 0, groups2);
size = sizeof(type);
ret = GetTokenInformation(r_token, TokenType, &type, size, &size);
ok(ret, "got error %d\n", GetLastError());
ok(type == TokenImpersonation, "got type %u\n", type);
size = sizeof(level);
ret = GetTokenInformation(r_token, TokenImpersonationLevel, &level, size, &size);
ok(ret, "got error %d\n", GetLastError());
ok(level == SecurityImpersonation, "got level %u\n", type);
}
HeapFree(GetProcessHeap(), 0, token_groups);
CloseHandle(r_token);
CloseHandle(token);
CloseHandle(process_token);
}
static void validate_default_security_descriptor(SECURITY_DESCRIPTOR *sd)
{
BOOL ret, present, defaulted;
ACL *acl;
void *sid;
ret = IsValidSecurityDescriptor(sd);
ok(ret, "security descriptor is not valid\n");
present = -1;
defaulted = -1;
acl = (void *)0xdeadbeef;
SetLastError(0xdeadbeef);
ret = GetSecurityDescriptorDacl(sd, &present, &acl, &defaulted);
ok(ret, "GetSecurityDescriptorDacl error %d\n", GetLastError());
todo_wine
ok(present == 1, "acl is not present\n");
todo_wine
ok(acl != (void *)0xdeadbeef && acl != NULL, "acl pointer is not set\n");
ok(defaulted == 0, "defaulted is set to TRUE\n");
defaulted = -1;
sid = (void *)0xdeadbeef;
SetLastError(0xdeadbeef);
ret = GetSecurityDescriptorOwner(sd, &sid, &defaulted);
ok(ret, "GetSecurityDescriptorOwner error %d\n", GetLastError());
todo_wine
ok(sid != (void *)0xdeadbeef && sid != NULL, "sid pointer is not set\n");
ok(defaulted == 0, "defaulted is set to TRUE\n");
defaulted = -1;
sid = (void *)0xdeadbeef;
SetLastError(0xdeadbeef);
ret = GetSecurityDescriptorGroup(sd, &sid, &defaulted);
ok(ret, "GetSecurityDescriptorGroup error %d\n", GetLastError());
todo_wine
ok(sid != (void *)0xdeadbeef && sid != NULL, "sid pointer is not set\n");
ok(defaulted == 0, "defaulted is set to TRUE\n");
}
static void test_default_handle_security(HANDLE token, HANDLE handle, GENERIC_MAPPING *mapping)
{
DWORD ret, granted, priv_set_len;
BOOL status;
PRIVILEGE_SET priv_set;
SECURITY_DESCRIPTOR *sd;
sd = test_get_security_descriptor(handle, __LINE__);
validate_default_security_descriptor(sd);
priv_set_len = sizeof(priv_set);
granted = 0xdeadbeef;
status = 0xdeadbeef;
SetLastError(0xdeadbeef);
ret = AccessCheck(sd, token, MAXIMUM_ALLOWED, mapping, &priv_set, &priv_set_len, &granted, &status);
todo_wine {
ok(ret, "AccessCheck error %d\n", GetLastError());
ok(status == 1, "expected 1, got %d\n", status);
ok(granted == mapping->GenericAll, "expected all access %#x, got %#x\n", mapping->GenericAll, granted);
}
priv_set_len = sizeof(priv_set);
granted = 0xdeadbeef;
status = 0xdeadbeef;
SetLastError(0xdeadbeef);
ret = AccessCheck(sd, token, 0, mapping, &priv_set, &priv_set_len, &granted, &status);
todo_wine {
ok(ret, "AccessCheck error %d\n", GetLastError());
ok(status == 0 || broken(status == 1) /* NT4 */, "expected 0, got %d\n", status);
ok(granted == 0 || broken(granted == mapping->GenericRead) /* NT4 */, "expected 0, got %#x\n", granted);
}
priv_set_len = sizeof(priv_set);
granted = 0xdeadbeef;
status = 0xdeadbeef;
SetLastError(0xdeadbeef);
ret = AccessCheck(sd, token, ACCESS_SYSTEM_SECURITY, mapping, &priv_set, &priv_set_len, &granted, &status);
todo_wine {
ok(ret, "AccessCheck error %d\n", GetLastError());
ok(status == 0, "expected 0, got %d\n", status);
ok(granted == 0, "expected 0, got %#x\n", granted);
}
priv_set_len = sizeof(priv_set);
granted = 0xdeadbeef;
status = 0xdeadbeef;
SetLastError(0xdeadbeef);
ret = AccessCheck(sd, token, mapping->GenericRead, mapping, &priv_set, &priv_set_len, &granted, &status);
todo_wine {
ok(ret, "AccessCheck error %d\n", GetLastError());
ok(status == 1, "expected 1, got %d\n", status);
ok(granted == mapping->GenericRead, "expected read access %#x, got %#x\n", mapping->GenericRead, granted);
}
priv_set_len = sizeof(priv_set);
granted = 0xdeadbeef;
status = 0xdeadbeef;
SetLastError(0xdeadbeef);
ret = AccessCheck(sd, token, mapping->GenericWrite, mapping, &priv_set, &priv_set_len, &granted, &status);
todo_wine {
ok(ret, "AccessCheck error %d\n", GetLastError());
ok(status == 1, "expected 1, got %d\n", status);
ok(granted == mapping->GenericWrite, "expected write access %#x, got %#x\n", mapping->GenericWrite, granted);
}
priv_set_len = sizeof(priv_set);
granted = 0xdeadbeef;
status = 0xdeadbeef;
SetLastError(0xdeadbeef);
ret = AccessCheck(sd, token, mapping->GenericExecute, mapping, &priv_set, &priv_set_len, &granted, &status);
todo_wine {
ok(ret, "AccessCheck error %d\n", GetLastError());
ok(status == 1, "expected 1, got %d\n", status);
ok(granted == mapping->GenericExecute, "expected execute access %#x, got %#x\n", mapping->GenericExecute, granted);
}
HeapFree(GetProcessHeap(), 0, sd);
}
static ACCESS_MASK get_obj_access(HANDLE obj)
{
OBJECT_BASIC_INFORMATION info;
NTSTATUS status;
if (!pNtQueryObject) return 0;
status = pNtQueryObject(obj, ObjectBasicInformation, &info, sizeof(info), NULL);
ok(!status, "NtQueryObject error %#x\n", status);
return info.GrantedAccess;
}
static void test_mutex_security(HANDLE token)
{
DWORD ret, i, access;
HANDLE mutex, dup;
GENERIC_MAPPING mapping = { STANDARD_RIGHTS_READ | MUTANT_QUERY_STATE | SYNCHRONIZE,
STANDARD_RIGHTS_WRITE | MUTEX_MODIFY_STATE | SYNCHRONIZE,
STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE,
STANDARD_RIGHTS_ALL | MUTEX_ALL_ACCESS };
static const struct
{
int generic, mapped;
} map[] =
{
{ 0, 0 },
{ GENERIC_READ, STANDARD_RIGHTS_READ | MUTANT_QUERY_STATE },
{ GENERIC_WRITE, STANDARD_RIGHTS_WRITE },
{ GENERIC_EXECUTE, STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE },
{ GENERIC_ALL, STANDARD_RIGHTS_ALL | MUTANT_QUERY_STATE }
};
SetLastError(0xdeadbeef);
mutex = OpenMutexA(0, FALSE, "WineTestMutex");
ok(!mutex, "mutex should not exist\n");
ok(GetLastError() == ERROR_FILE_NOT_FOUND, "wrong error %u\n", GetLastError());
SetLastError(0xdeadbeef);
mutex = CreateMutexA(NULL, FALSE, "WineTestMutex");
ok(mutex != 0, "CreateMutex error %d\n", GetLastError());
access = get_obj_access(mutex);
ok(access == MUTANT_ALL_ACCESS, "expected MUTANT_ALL_ACCESS, got %#x\n", access);
for (i = 0; i < ARRAY_SIZE(map); i++)
{
SetLastError( 0xdeadbeef );
ret = DuplicateHandle(GetCurrentProcess(), mutex, GetCurrentProcess(), &dup,
map[i].generic, FALSE, 0);
ok(ret, "DuplicateHandle error %d\n", GetLastError());
access = get_obj_access(dup);
ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
CloseHandle(dup);
SetLastError(0xdeadbeef);
dup = OpenMutexA(0, FALSE, "WineTestMutex");
todo_wine
ok(!dup, "OpenMutex should fail\n");
todo_wine
ok(GetLastError() == ERROR_ACCESS_DENIED, "wrong error %u\n", GetLastError());
}
test_default_handle_security(token, mutex, &mapping);
CloseHandle (mutex);
}
static void test_event_security(HANDLE token)
{
DWORD ret, i, access;
HANDLE event, dup;
GENERIC_MAPPING mapping = { STANDARD_RIGHTS_READ | EVENT_QUERY_STATE | SYNCHRONIZE,
STANDARD_RIGHTS_WRITE | EVENT_MODIFY_STATE | SYNCHRONIZE,
STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE,
STANDARD_RIGHTS_ALL | EVENT_ALL_ACCESS };
static const struct
{
int generic, mapped;
} map[] =
{
{ 0, 0 },
{ GENERIC_READ, STANDARD_RIGHTS_READ | EVENT_QUERY_STATE },
{ GENERIC_WRITE, STANDARD_RIGHTS_WRITE | EVENT_MODIFY_STATE },
{ GENERIC_EXECUTE, STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE },
{ GENERIC_ALL, STANDARD_RIGHTS_ALL | EVENT_QUERY_STATE | EVENT_MODIFY_STATE }
};
SetLastError(0xdeadbeef);
event = OpenEventA(0, FALSE, "WineTestEvent");
ok(!event, "event should not exist\n");
ok(GetLastError() == ERROR_FILE_NOT_FOUND, "wrong error %u\n", GetLastError());
SetLastError(0xdeadbeef);
event = CreateEventA(NULL, FALSE, FALSE, "WineTestEvent");
ok(event != 0, "CreateEvent error %d\n", GetLastError());
access = get_obj_access(event);
ok(access == EVENT_ALL_ACCESS, "expected EVENT_ALL_ACCESS, got %#x\n", access);
for (i = 0; i < ARRAY_SIZE(map); i++)
{
SetLastError( 0xdeadbeef );
ret = DuplicateHandle(GetCurrentProcess(), event, GetCurrentProcess(), &dup,
map[i].generic, FALSE, 0);
ok(ret, "DuplicateHandle error %d\n", GetLastError());
access = get_obj_access(dup);
ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
CloseHandle(dup);
SetLastError(0xdeadbeef);
dup = OpenEventA(0, FALSE, "WineTestEvent");
todo_wine
ok(!dup, "OpenEvent should fail\n");
todo_wine
ok(GetLastError() == ERROR_ACCESS_DENIED, "wrong error %u\n", GetLastError());
}
test_default_handle_security(token, event, &mapping);
CloseHandle(event);
}
static void test_semaphore_security(HANDLE token)
{
DWORD ret, i, access;
HANDLE sem, dup;
GENERIC_MAPPING mapping = { STANDARD_RIGHTS_READ | SEMAPHORE_QUERY_STATE,
STANDARD_RIGHTS_WRITE | SEMAPHORE_MODIFY_STATE,
STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE,
STANDARD_RIGHTS_ALL | SEMAPHORE_ALL_ACCESS };
static const struct
{
int generic, mapped;
} map[] =
{
{ 0, 0 },
{ GENERIC_READ, STANDARD_RIGHTS_READ | SEMAPHORE_QUERY_STATE },
{ GENERIC_WRITE, STANDARD_RIGHTS_WRITE | SEMAPHORE_MODIFY_STATE },
{ GENERIC_EXECUTE, STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE },
{ GENERIC_ALL, STANDARD_RIGHTS_ALL | SEMAPHORE_QUERY_STATE | SEMAPHORE_MODIFY_STATE }
};
SetLastError(0xdeadbeef);
sem = OpenSemaphoreA(0, FALSE, "WineTestSemaphore");
ok(!sem, "semaphore should not exist\n");
ok(GetLastError() == ERROR_FILE_NOT_FOUND, "wrong error %u\n", GetLastError());
SetLastError(0xdeadbeef);
sem = CreateSemaphoreA(NULL, 0, 10, "WineTestSemaphore");
ok(sem != 0, "CreateSemaphore error %d\n", GetLastError());
access = get_obj_access(sem);
ok(access == SEMAPHORE_ALL_ACCESS, "expected SEMAPHORE_ALL_ACCESS, got %#x\n", access);
for (i = 0; i < ARRAY_SIZE(map); i++)
{
SetLastError( 0xdeadbeef );
ret = DuplicateHandle(GetCurrentProcess(), sem, GetCurrentProcess(), &dup,
map[i].generic, FALSE, 0);
ok(ret, "DuplicateHandle error %d\n", GetLastError());
access = get_obj_access(dup);
ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
CloseHandle(dup);
}
test_default_handle_security(token, sem, &mapping);
CloseHandle(sem);
}
#define WINE_TEST_PIPE "\\\\.\\pipe\\WineTestPipe"
static void test_named_pipe_security(HANDLE token)
{
DWORD ret, i, access;
HANDLE pipe, file, dup;
GENERIC_MAPPING mapping = { FILE_GENERIC_READ,
FILE_GENERIC_WRITE,
FILE_GENERIC_EXECUTE,
STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS };
static const struct
{
int generic, mapped;
} map[] =
{
{ 0, 0 },
{ GENERIC_READ, FILE_GENERIC_READ },
{ GENERIC_WRITE, FILE_GENERIC_WRITE },
{ GENERIC_EXECUTE, FILE_GENERIC_EXECUTE },
{ GENERIC_ALL, STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS }
};
static const struct
{
DWORD open_mode;
DWORD access;
} creation_access[] =
{
{ PIPE_ACCESS_INBOUND, FILE_GENERIC_READ },
{ PIPE_ACCESS_OUTBOUND, FILE_GENERIC_WRITE },
{ PIPE_ACCESS_DUPLEX, FILE_GENERIC_READ|FILE_GENERIC_WRITE },
{ PIPE_ACCESS_INBOUND|WRITE_DAC, FILE_GENERIC_READ|WRITE_DAC },
{ PIPE_ACCESS_INBOUND|WRITE_OWNER, FILE_GENERIC_READ|WRITE_OWNER }
/* ACCESS_SYSTEM_SECURITY is also valid, but will fail with ERROR_PRIVILEGE_NOT_HELD */
};
/* Test the different security access options for pipes */
for (i = 0; i < ARRAY_SIZE(creation_access); i++)
{
SetLastError(0xdeadbeef);
pipe = CreateNamedPipeA(WINE_TEST_PIPE, creation_access[i].open_mode,
PIPE_TYPE_BYTE | PIPE_NOWAIT, PIPE_UNLIMITED_INSTANCES, 0, 0,
NMPWAIT_USE_DEFAULT_WAIT, NULL);
ok(pipe != INVALID_HANDLE_VALUE, "CreateNamedPipe(0x%x) error %d\n",
creation_access[i].open_mode, GetLastError());
access = get_obj_access(pipe);
ok(access == creation_access[i].access,
"CreateNamedPipeA(0x%x) pipe expected access 0x%x (got 0x%x)\n",
creation_access[i].open_mode, creation_access[i].access, access);
CloseHandle(pipe);
}
SetLastError(0xdeadbeef);
pipe = CreateNamedPipeA(WINE_TEST_PIPE, PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE,
PIPE_TYPE_BYTE | PIPE_NOWAIT, PIPE_UNLIMITED_INSTANCES,
0, 0, NMPWAIT_USE_DEFAULT_WAIT, NULL);
ok(pipe != INVALID_HANDLE_VALUE, "CreateNamedPipe error %d\n", GetLastError());
test_default_handle_security(token, pipe, &mapping);
SetLastError(0xdeadbeef);
file = CreateFileA(WINE_TEST_PIPE, FILE_ALL_ACCESS, 0, NULL, OPEN_EXISTING, 0, 0);
ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
access = get_obj_access(file);
ok(access == FILE_ALL_ACCESS, "expected FILE_ALL_ACCESS, got %#x\n", access);
for (i = 0; i < ARRAY_SIZE(map); i++)
{
SetLastError( 0xdeadbeef );
ret = DuplicateHandle(GetCurrentProcess(), file, GetCurrentProcess(), &dup,
map[i].generic, FALSE, 0);
ok(ret, "DuplicateHandle error %d\n", GetLastError());
access = get_obj_access(dup);
ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
CloseHandle(dup);
}
CloseHandle(file);
CloseHandle(pipe);
SetLastError(0xdeadbeef);
file = CreateFileA("\\\\.\\pipe\\", FILE_ALL_ACCESS, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0);
ok(file != INVALID_HANDLE_VALUE || broken(file == INVALID_HANDLE_VALUE) /* before Vista */, "CreateFile error %d\n", GetLastError());
if (file != INVALID_HANDLE_VALUE)
{
access = get_obj_access(file);
ok(access == FILE_ALL_ACCESS, "expected FILE_ALL_ACCESS, got %#x\n", access);
for (i = 0; i < ARRAY_SIZE(map); i++)
{
SetLastError( 0xdeadbeef );
ret = DuplicateHandle(GetCurrentProcess(), file, GetCurrentProcess(), &dup,
map[i].generic, FALSE, 0);
ok(ret, "DuplicateHandle error %d\n", GetLastError());
access = get_obj_access(dup);
ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
CloseHandle(dup);
}
}
CloseHandle(file);
}
static void test_file_security(HANDLE token)
{
DWORD ret, i, access, bytes;
HANDLE file, dup;
static const struct
{
int generic, mapped;
} map[] =
{
{ 0, 0 },
{ GENERIC_READ, FILE_GENERIC_READ },
{ GENERIC_WRITE, FILE_GENERIC_WRITE },
{ GENERIC_EXECUTE, FILE_GENERIC_EXECUTE },
{ GENERIC_ALL, STANDARD_RIGHTS_ALL | FILE_ALL_ACCESS }
};
char temp_path[MAX_PATH];
char file_name[MAX_PATH];
char buf[16];
GetTempPathA(MAX_PATH, temp_path);
GetTempFileNameA(temp_path, "tmp", 0, file_name);
/* file */
SetLastError(0xdeadbeef);
file = CreateFileA(file_name, GENERIC_ALL, 0, NULL, CREATE_ALWAYS, 0, NULL);
ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
access = get_obj_access(file);
ok(access == FILE_ALL_ACCESS, "expected FILE_ALL_ACCESS, got %#x\n", access);
for (i = 0; i < ARRAY_SIZE(map); i++)
{
SetLastError( 0xdeadbeef );
ret = DuplicateHandle(GetCurrentProcess(), file, GetCurrentProcess(), &dup,
map[i].generic, FALSE, 0);
ok(ret, "DuplicateHandle error %d\n", GetLastError());
access = get_obj_access(dup);
ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
CloseHandle(dup);
}
CloseHandle(file);
SetLastError(0xdeadbeef);
file = CreateFileA(file_name, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
access = get_obj_access(file);
ok(access == (FILE_READ_ATTRIBUTES | SYNCHRONIZE), "expected FILE_READ_ATTRIBUTES | SYNCHRONIZE, got %#x\n", access);
bytes = 0xdeadbeef;
SetLastError(0xdeadbeef);
ret = ReadFile(file, buf, sizeof(buf), &bytes, NULL);
ok(!ret, "ReadFile should fail\n");
ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
ok(bytes == 0, "expected 0, got %u\n", bytes);
CloseHandle(file);
SetLastError(0xdeadbeef);
file = CreateFileA(file_name, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
access = get_obj_access(file);
ok(access == (FILE_GENERIC_WRITE | FILE_READ_ATTRIBUTES), "expected FILE_GENERIC_WRITE | FILE_READ_ATTRIBUTES, got %#x\n", access);
bytes = 0xdeadbeef;
SetLastError(0xdeadbeef);
ret = ReadFile(file, buf, sizeof(buf), &bytes, NULL);
ok(!ret, "ReadFile should fail\n");
ok(GetLastError() == ERROR_ACCESS_DENIED, "expected ERROR_ACCESS_DENIED, got %d\n", GetLastError());
ok(bytes == 0, "expected 0, got %u\n", bytes);
CloseHandle(file);
DeleteFileA(file_name);
/* directory */
SetLastError(0xdeadbeef);
file = CreateFileA(temp_path, GENERIC_ALL, 0, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
access = get_obj_access(file);
ok(access == FILE_ALL_ACCESS, "expected FILE_ALL_ACCESS, got %#x\n", access);
for (i = 0; i < ARRAY_SIZE(map); i++)
{
SetLastError( 0xdeadbeef );
ret = DuplicateHandle(GetCurrentProcess(), file, GetCurrentProcess(), &dup,
map[i].generic, FALSE, 0);
ok(ret, "DuplicateHandle error %d\n", GetLastError());
access = get_obj_access(dup);
ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
CloseHandle(dup);
}
CloseHandle(file);
SetLastError(0xdeadbeef);
file = CreateFileA(temp_path, 0, 0, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
access = get_obj_access(file);
ok(access == (FILE_READ_ATTRIBUTES | SYNCHRONIZE), "expected FILE_READ_ATTRIBUTES | SYNCHRONIZE, got %#x\n", access);
CloseHandle(file);
SetLastError(0xdeadbeef);
file = CreateFileA(temp_path, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
access = get_obj_access(file);
ok(access == (FILE_GENERIC_WRITE | FILE_READ_ATTRIBUTES), "expected FILE_GENERIC_WRITE | FILE_READ_ATTRIBUTES, got %#x\n", access);
CloseHandle(file);
}
static void test_filemap_security(void)
{
char temp_path[MAX_PATH];
char file_name[MAX_PATH];
DWORD ret, i, access;
HANDLE file, mapping, dup, created_mapping;
static const struct
{
int generic, mapped;
BOOL open_only;
} map[] =
{
{ 0, 0 },
{ GENERIC_READ, STANDARD_RIGHTS_READ | SECTION_QUERY | SECTION_MAP_READ },
{ GENERIC_WRITE, STANDARD_RIGHTS_WRITE | SECTION_MAP_WRITE },
{ GENERIC_EXECUTE, STANDARD_RIGHTS_EXECUTE | SECTION_MAP_EXECUTE },
{ GENERIC_ALL, STANDARD_RIGHTS_REQUIRED | SECTION_ALL_ACCESS },
{ SECTION_MAP_READ | SECTION_MAP_WRITE, SECTION_MAP_READ | SECTION_MAP_WRITE },
{ SECTION_MAP_WRITE, SECTION_MAP_WRITE },
{ SECTION_MAP_READ | SECTION_QUERY, SECTION_MAP_READ | SECTION_QUERY },
{ SECTION_QUERY, SECTION_MAP_READ, TRUE },
{ SECTION_QUERY | SECTION_MAP_READ, SECTION_QUERY | SECTION_MAP_READ }
};
static const struct
{
int prot, mapped;
} prot_map[] =
{
{ 0, 0 },
{ PAGE_NOACCESS, 0 },
{ PAGE_READONLY, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ },
{ PAGE_READWRITE, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ | SECTION_MAP_WRITE },
{ PAGE_WRITECOPY, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ },
{ PAGE_EXECUTE, 0 },
{ PAGE_EXECUTE_READ, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ | SECTION_MAP_EXECUTE },
{ PAGE_EXECUTE_READWRITE, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ | SECTION_MAP_WRITE | SECTION_MAP_EXECUTE },
{ PAGE_EXECUTE_WRITECOPY, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ | SECTION_MAP_EXECUTE }
};
GetTempPathA(MAX_PATH, temp_path);
GetTempFileNameA(temp_path, "tmp", 0, file_name);
SetLastError(0xdeadbeef);
file = CreateFileA(file_name, GENERIC_READ|GENERIC_WRITE|GENERIC_EXECUTE, 0, NULL, CREATE_ALWAYS, 0, 0);
ok(file != INVALID_HANDLE_VALUE, "CreateFile error %d\n", GetLastError());
SetFilePointer(file, 4096, NULL, FILE_BEGIN);
SetEndOfFile(file);
for (i = 0; i < ARRAY_SIZE(prot_map); i++)
{
if (map[i].open_only) continue;
SetLastError(0xdeadbeef);
mapping = CreateFileMappingW(file, NULL, prot_map[i].prot, 0, 4096, NULL);
if (prot_map[i].mapped)
{
if (!mapping)
{
/* NT4 and win2k don't support EXEC on file mappings */
if (prot_map[i].prot == PAGE_EXECUTE_READ || prot_map[i].prot == PAGE_EXECUTE_READWRITE || prot_map[i].prot == PAGE_EXECUTE_WRITECOPY)
{
win_skip("CreateFileMapping doesn't support PAGE_EXECUTE protection\n");
continue;
}
}
ok(mapping != 0, "CreateFileMapping(%04x) error %d\n", prot_map[i].prot, GetLastError());
}
else
{
ok(!mapping, "CreateFileMapping(%04x) should fail\n", prot_map[i].prot);
ok(GetLastError() == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
continue;
}
access = get_obj_access(mapping);
ok(access == prot_map[i].mapped, "%d: expected %#x, got %#x\n", i, prot_map[i].mapped, access);
CloseHandle(mapping);
}
SetLastError(0xdeadbeef);
mapping = CreateFileMappingW(file, NULL, PAGE_EXECUTE_READWRITE, 0, 4096, NULL);
if (!mapping)
{
/* NT4 and win2k don't support EXEC on file mappings */
win_skip("CreateFileMapping doesn't support PAGE_EXECUTE protection\n");
CloseHandle(file);
DeleteFileA(file_name);
return;
}
ok(mapping != 0, "CreateFileMapping error %d\n", GetLastError());
access = get_obj_access(mapping);
ok(access == (STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ | SECTION_MAP_WRITE | SECTION_MAP_EXECUTE),
"expected STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ | SECTION_MAP_WRITE | SECTION_MAP_EXECUTE, got %#x\n", access);
for (i = 0; i < ARRAY_SIZE(map); i++)
{
if (map[i].open_only) continue;
SetLastError( 0xdeadbeef );
ret = DuplicateHandle(GetCurrentProcess(), mapping, GetCurrentProcess(), &dup,
map[i].generic, FALSE, 0);
ok(ret, "DuplicateHandle error %d\n", GetLastError());
access = get_obj_access(dup);
ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
CloseHandle(dup);
}
CloseHandle(mapping);
CloseHandle(file);
DeleteFileA(file_name);
created_mapping = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 0x1000,
"Wine Test Open Mapping");
ok(created_mapping != NULL, "CreateFileMapping failed with error %u\n", GetLastError());
for (i = 0; i < ARRAY_SIZE(map); i++)
{
if (!map[i].generic) continue;
mapping = OpenFileMappingA(map[i].generic, FALSE, "Wine Test Open Mapping");
ok(mapping != NULL, "OpenFileMapping failed with error %d\n", GetLastError());
access = get_obj_access(mapping);
ok(access == map[i].mapped, "%d: unexpected access flags %#x, expected %#x\n",
i, access, map[i].mapped);
CloseHandle(mapping);
}
CloseHandle(created_mapping);
}
static void test_thread_security(void)
{
DWORD ret, i, access;
HANDLE thread, dup;
static const struct
{
int generic, mapped;
} map[] =
{
{ 0, 0 },
{ GENERIC_READ, STANDARD_RIGHTS_READ | THREAD_QUERY_INFORMATION | THREAD_GET_CONTEXT },
{ GENERIC_WRITE, STANDARD_RIGHTS_WRITE | THREAD_SET_INFORMATION | THREAD_SET_CONTEXT | THREAD_TERMINATE | THREAD_SUSPEND_RESUME | 0x4 },
{ GENERIC_EXECUTE, STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE },
{ GENERIC_ALL, THREAD_ALL_ACCESS_NT4 }
};
SetLastError(0xdeadbeef);
thread = CreateThread(NULL, 0, (void *)0xdeadbeef, NULL, CREATE_SUSPENDED, &ret);
ok(thread != 0, "CreateThread error %d\n", GetLastError());
access = get_obj_access(thread);
ok(access == THREAD_ALL_ACCESS_NT4 || access == THREAD_ALL_ACCESS_VISTA, "expected THREAD_ALL_ACCESS, got %#x\n", access);
for (i = 0; i < ARRAY_SIZE(map); i++)
{
SetLastError( 0xdeadbeef );
ret = DuplicateHandle(GetCurrentProcess(), thread, GetCurrentProcess(), &dup,
map[i].generic, FALSE, 0);
ok(ret, "DuplicateHandle error %d\n", GetLastError());
access = get_obj_access(dup);
switch (map[i].generic)
{
case GENERIC_READ:
case GENERIC_EXECUTE:
ok(access == map[i].mapped ||
access == (map[i].mapped | THREAD_QUERY_LIMITED_INFORMATION) /* Vista+ */ ||
access == (map[i].mapped | THREAD_QUERY_LIMITED_INFORMATION | THREAD_RESUME) /* win8 */,
"%d: expected %#x, got %#x\n", i, map[i].mapped, access);
break;
case GENERIC_WRITE:
todo_wine
ok(access == map[i].mapped ||
access == (map[i].mapped | THREAD_SET_LIMITED_INFORMATION) /* Vista+ */ ||
access == (map[i].mapped | THREAD_SET_LIMITED_INFORMATION | THREAD_RESUME) /* win8 */,
"%d: expected %#x, got %#x\n", i, map[i].mapped, access);
break;
case GENERIC_ALL:
ok(access == map[i].mapped || access == THREAD_ALL_ACCESS_VISTA,
"%d: expected %#x, got %#x\n", i, map[i].mapped, access);
break;
default:
ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
break;
}
CloseHandle(dup);
}
SetLastError( 0xdeadbeef );
ret = DuplicateHandle(GetCurrentProcess(), thread, GetCurrentProcess(), &dup,
THREAD_QUERY_INFORMATION, FALSE, 0);
ok(ret, "DuplicateHandle error %d\n", GetLastError());
access = get_obj_access(dup);
ok(access == (THREAD_QUERY_INFORMATION | THREAD_QUERY_LIMITED_INFORMATION) /* Vista+ */ ||
access == THREAD_QUERY_INFORMATION /* before Vista */,
"expected THREAD_QUERY_INFORMATION|THREAD_QUERY_LIMITED_INFORMATION, got %#x\n", access);
CloseHandle(dup);
TerminateThread(thread, 0);
CloseHandle(thread);
}
static void test_process_access(void)
{
DWORD ret, i, access;
HANDLE process, dup;
STARTUPINFOA sti;
PROCESS_INFORMATION pi;
char cmdline[] = "winver.exe";
static const struct
{
int generic, mapped;
} map[] =
{
{ 0, 0 },
{ GENERIC_READ, STANDARD_RIGHTS_READ | PROCESS_QUERY_INFORMATION | PROCESS_VM_READ },
{ GENERIC_WRITE, STANDARD_RIGHTS_WRITE | PROCESS_SET_QUOTA | PROCESS_SET_INFORMATION | PROCESS_SUSPEND_RESUME |
PROCESS_VM_WRITE | PROCESS_DUP_HANDLE | PROCESS_CREATE_PROCESS | PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION },
{ GENERIC_EXECUTE, STANDARD_RIGHTS_EXECUTE | SYNCHRONIZE },
{ GENERIC_ALL, PROCESS_ALL_ACCESS_NT4 }
};
memset(&sti, 0, sizeof(sti));
sti.cb = sizeof(sti);
SetLastError(0xdeadbeef);
ret = CreateProcessA(NULL, cmdline, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &sti, &pi);
ok(ret, "CreateProcess() error %d\n", GetLastError());
CloseHandle(pi.hThread);
process = pi.hProcess;
access = get_obj_access(process);
ok(access == PROCESS_ALL_ACCESS_NT4 || access == PROCESS_ALL_ACCESS_VISTA, "expected PROCESS_ALL_ACCESS, got %#x\n", access);
for (i = 0; i < ARRAY_SIZE(map); i++)
{
SetLastError( 0xdeadbeef );
ret = DuplicateHandle(GetCurrentProcess(), process, GetCurrentProcess(), &dup,
map[i].generic, FALSE, 0);
ok(ret, "DuplicateHandle error %d\n", GetLastError());
access = get_obj_access(dup);
switch (map[i].generic)
{
case GENERIC_READ:
ok(access == map[i].mapped || access == (map[i].mapped | PROCESS_QUERY_LIMITED_INFORMATION) /* Vista+ */,
"%d: expected %#x, got %#x\n", i, map[i].mapped, access);
break;
case GENERIC_WRITE:
ok(access == map[i].mapped ||
access == (map[i].mapped | PROCESS_TERMINATE) /* before Vista */ ||
access == (map[i].mapped | PROCESS_SET_LIMITED_INFORMATION) /* win8 */ ||
access == (map[i].mapped | PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SET_LIMITED_INFORMATION) /* Win10 Anniversary Update */,
"%d: expected %#x, got %#x\n", i, map[i].mapped, access);
break;
case GENERIC_EXECUTE:
ok(access == map[i].mapped || access == (map[i].mapped | PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_TERMINATE) /* Vista+ */,
"%d: expected %#x, got %#x\n", i, map[i].mapped, access);
break;
case GENERIC_ALL:
ok(access == map[i].mapped || access == PROCESS_ALL_ACCESS_VISTA,
"%d: expected %#x, got %#x\n", i, map[i].mapped, access);
break;
default:
ok(access == map[i].mapped, "%d: expected %#x, got %#x\n", i, map[i].mapped, access);
break;
}
CloseHandle(dup);
}
SetLastError( 0xdeadbeef );
ret = DuplicateHandle(GetCurrentProcess(), process, GetCurrentProcess(), &dup,
PROCESS_QUERY_INFORMATION, FALSE, 0);
ok(ret, "DuplicateHandle error %d\n", GetLastError());
access = get_obj_access(dup);
ok(access == (PROCESS_QUERY_INFORMATION | PROCESS_QUERY_LIMITED_INFORMATION) /* Vista+ */ ||
access == PROCESS_QUERY_INFORMATION /* before Vista */,
"expected PROCESS_QUERY_INFORMATION|PROCESS_QUERY_LIMITED_INFORMATION, got %#x\n", access);
CloseHandle(dup);
TerminateProcess(process, 0);
CloseHandle(process);
}
static BOOL validate_impersonation_token(HANDLE token, DWORD *token_type)
{
DWORD ret, needed;
TOKEN_TYPE type;
SECURITY_IMPERSONATION_LEVEL sil;
type = 0xdeadbeef;
needed = 0;
SetLastError(0xdeadbeef);
ret = GetTokenInformation(token, TokenType, &type, sizeof(type), &needed);
ok(ret, "GetTokenInformation error %d\n", GetLastError());
ok(needed == sizeof(type), "GetTokenInformation should return required buffer length\n");
ok(type == TokenPrimary || type == TokenImpersonation, "expected TokenPrimary or TokenImpersonation, got %d\n", type);
*token_type = type;
if (type != TokenImpersonation) return FALSE;
needed = 0;
SetLastError(0xdeadbeef);
ret = GetTokenInformation(token, TokenImpersonationLevel, &sil, sizeof(sil), &needed);
ok(ret, "GetTokenInformation error %d\n", GetLastError());
ok(needed == sizeof(sil), "GetTokenInformation should return required buffer length\n");
ok(sil == SecurityImpersonation, "expected SecurityImpersonation, got %d\n", sil);
needed = 0xdeadbeef;
SetLastError(0xdeadbeef);
ret = GetTokenInformation(token, TokenDefaultDacl, NULL, 0, &needed);
ok(!ret, "GetTokenInformation should fail\n");
ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
ok(needed != 0xdeadbeef, "GetTokenInformation should return required buffer length\n");
ok(needed > sizeof(TOKEN_DEFAULT_DACL), "GetTokenInformation returned empty default DACL\n");
needed = 0xdeadbeef;
SetLastError(0xdeadbeef);
ret = GetTokenInformation(token, TokenOwner, NULL, 0, &needed);
ok(!ret, "GetTokenInformation should fail\n");
ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
ok(needed != 0xdeadbeef, "GetTokenInformation should return required buffer length\n");
ok(needed > sizeof(TOKEN_OWNER), "GetTokenInformation returned empty token owner\n");
needed = 0xdeadbeef;
SetLastError(0xdeadbeef);
ret = GetTokenInformation(token, TokenPrimaryGroup, NULL, 0, &needed);
ok(!ret, "GetTokenInformation should fail\n");
ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
ok(needed != 0xdeadbeef, "GetTokenInformation should return required buffer length\n");
ok(needed > sizeof(TOKEN_PRIMARY_GROUP), "GetTokenInformation returned empty token primary group\n");
return TRUE;
}
static void test_kernel_objects_security(void)
{
HANDLE token, process_token;
DWORD ret, token_type;
ret = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE | TOKEN_QUERY, &process_token);
ok(ret, "OpenProcessToken error %d\n", GetLastError());
ret = validate_impersonation_token(process_token, &token_type);
ok(token_type == TokenPrimary, "expected TokenPrimary, got %d\n", token_type);
ok(!ret, "access token should not be an impersonation token\n");
ret = DuplicateToken(process_token, SecurityImpersonation, &token);
ok(ret, "DuplicateToken error %d\n", GetLastError());
ret = validate_impersonation_token(token, &token_type);
ok(ret, "access token should be a valid impersonation token\n");
ok(token_type == TokenImpersonation, "expected TokenImpersonation, got %d\n", token_type);
test_mutex_security(token);
test_event_security(token);
test_named_pipe_security(token);
test_semaphore_security(token);
test_file_security(token);
test_filemap_security();
test_thread_security();
test_process_access();
/* FIXME: test other kernel object types */
CloseHandle(process_token);
CloseHandle(token);
}
static void test_TokenIntegrityLevel(void)
{
TOKEN_MANDATORY_LABEL *tml;
BYTE buffer[64]; /* using max. 28 byte in win7 x64 */
HANDLE token;
DWORD size;
DWORD res;
static SID medium_level = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
{SECURITY_MANDATORY_HIGH_RID}};
static SID high_level = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
{SECURITY_MANDATORY_MEDIUM_RID}};
SetLastError(0xdeadbeef);
res = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token);
ok(res, "got %d with %d (expected TRUE)\n", res, GetLastError());
SetLastError(0xdeadbeef);
res = GetTokenInformation(token, TokenIntegrityLevel, buffer, sizeof(buffer), &size);
/* not supported before Vista */
if (!res && ((GetLastError() == ERROR_INVALID_PARAMETER) || GetLastError() == ERROR_INVALID_FUNCTION))
{
win_skip("TokenIntegrityLevel not supported\n");
CloseHandle(token);
return;
}
ok(res, "got %u with %u (expected TRUE)\n", res, GetLastError());
if (!res)
{
CloseHandle(token);
return;
}
tml = (TOKEN_MANDATORY_LABEL*) buffer;
ok(tml->Label.Attributes == (SE_GROUP_INTEGRITY | SE_GROUP_INTEGRITY_ENABLED),
"got 0x%x (expected 0x%x)\n", tml->Label.Attributes, (SE_GROUP_INTEGRITY | SE_GROUP_INTEGRITY_ENABLED));
ok(EqualSid(tml->Label.Sid, &medium_level) || EqualSid(tml->Label.Sid, &high_level),
"got %s (expected %s or %s)\n", debugstr_sid(tml->Label.Sid),
debugstr_sid(&medium_level), debugstr_sid(&high_level));
CloseHandle(token);
}
static void test_default_dacl_owner_sid(void)
{
HANDLE handle;
BOOL ret, defaulted, present, found;
DWORD size, index;
SECURITY_DESCRIPTOR *sd;
SECURITY_ATTRIBUTES sa;
PSID owner;
ACL *dacl;
ACCESS_ALLOWED_ACE *ace;
sd = HeapAlloc( GetProcessHeap(), 0, SECURITY_DESCRIPTOR_MIN_LENGTH );
ret = InitializeSecurityDescriptor( sd, SECURITY_DESCRIPTOR_REVISION );
ok( ret, "error %u\n", GetLastError() );
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = sd;
sa.bInheritHandle = FALSE;
handle = CreateEventA( &sa, TRUE, TRUE, "test_event" );
ok( handle != NULL, "error %u\n", GetLastError() );
size = 0;
ret = GetKernelObjectSecurity( handle, OWNER_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION, NULL, 0, &size );
ok( !ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER, "error %u\n", GetLastError() );
sd = HeapAlloc( GetProcessHeap(), 0, size );
ret = GetKernelObjectSecurity( handle, OWNER_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION, sd, size, &size );
ok( ret, "error %u\n", GetLastError() );
owner = (void *)0xdeadbeef;
defaulted = TRUE;
ret = GetSecurityDescriptorOwner( sd, &owner, &defaulted );
ok( ret, "error %u\n", GetLastError() );
ok( owner != (void *)0xdeadbeef, "owner not set\n" );
ok( !defaulted, "owner defaulted\n" );
dacl = (void *)0xdeadbeef;
present = FALSE;
defaulted = TRUE;
ret = GetSecurityDescriptorDacl( sd, &present, &dacl, &defaulted );
ok( ret, "error %u\n", GetLastError() );
ok( present, "dacl not present\n" );
ok( dacl != (void *)0xdeadbeef, "dacl not set\n" );
ok( !defaulted, "dacl defaulted\n" );
index = 0;
found = FALSE;
while (pGetAce( dacl, index++, (void **)&ace ))
{
if (EqualSid( &ace->SidStart, owner )) found = TRUE;
}
ok( found, "owner sid not found in dacl\n" );
HeapFree( GetProcessHeap(), 0, sa.lpSecurityDescriptor );
HeapFree( GetProcessHeap(), 0, sd );
CloseHandle( handle );
}
static void test_AdjustTokenPrivileges(void)
{
TOKEN_PRIVILEGES tp;
HANDLE token;
DWORD len;
LUID luid;
BOOL ret;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token))
return;
if (!LookupPrivilegeValueA(NULL, SE_BACKUP_NAME, &luid))
{
CloseHandle(token);
return;
}
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
len = 0xdeadbeef;
ret = AdjustTokenPrivileges(token, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), NULL, &len);
ok(ret, "got %d\n", ret);
ok(len == 0xdeadbeef, "got length %d\n", len);
/* revert */
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = 0;
ret = AdjustTokenPrivileges(token, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), NULL, NULL);
ok(ret, "got %d\n", ret);
CloseHandle(token);
}
static void test_AddAce(void)
{
static SID const sidWorld = { SID_REVISION, 1, { SECURITY_WORLD_SID_AUTHORITY} , { SECURITY_WORLD_RID } };
char acl_buf[1024], ace_buf[256];
ACCESS_ALLOWED_ACE *ace = (ACCESS_ALLOWED_ACE*)ace_buf;
PACL acl = (PACL)acl_buf;
BOOL ret;
memset(ace, 0, sizeof(ace_buf));
ace->Header.AceType = ACCESS_ALLOWED_ACE_TYPE;
ace->Header.AceSize = sizeof(ACCESS_ALLOWED_ACE)-sizeof(DWORD)+sizeof(SID);
memcpy(&ace->SidStart, &sidWorld, sizeof(sidWorld));
ret = InitializeAcl(acl, sizeof(acl_buf), ACL_REVISION2);
ok(ret, "InitializeAcl failed: %d\n", GetLastError());
ret = AddAce(acl, ACL_REVISION1, MAXDWORD, ace, ace->Header.AceSize);
ok(ret, "AddAce failed: %d\n", GetLastError());
ret = AddAce(acl, ACL_REVISION2, MAXDWORD, ace, ace->Header.AceSize);
ok(ret, "AddAce failed: %d\n", GetLastError());
ret = AddAce(acl, ACL_REVISION3, MAXDWORD, ace, ace->Header.AceSize);
ok(ret, "AddAce failed: %d\n", GetLastError());
ok(acl->AclRevision == ACL_REVISION3, "acl->AclRevision = %d\n", acl->AclRevision);
ret = AddAce(acl, ACL_REVISION4, MAXDWORD, ace, ace->Header.AceSize);
ok(ret, "AddAce failed: %d\n", GetLastError());
ok(acl->AclRevision == ACL_REVISION4, "acl->AclRevision = %d\n", acl->AclRevision);
ret = AddAce(acl, ACL_REVISION1, MAXDWORD, ace, ace->Header.AceSize);
ok(ret, "AddAce failed: %d\n", GetLastError());
ok(acl->AclRevision == ACL_REVISION4, "acl->AclRevision = %d\n", acl->AclRevision);
ret = AddAce(acl, ACL_REVISION2, MAXDWORD, ace, ace->Header.AceSize);
ok(ret, "AddAce failed: %d\n", GetLastError());
ret = AddAce(acl, MIN_ACL_REVISION-1, MAXDWORD, ace, ace->Header.AceSize);
ok(ret, "AddAce failed: %d\n", GetLastError());
/* next test succeededs but corrupts ACL */
ret = AddAce(acl, MAX_ACL_REVISION+1, MAXDWORD, ace, ace->Header.AceSize);
ok(ret, "AddAce failed: %d\n", GetLastError());
ok(acl->AclRevision == MAX_ACL_REVISION+1, "acl->AclRevision = %d\n", acl->AclRevision);
SetLastError(0xdeadbeef);
ret = AddAce(acl, ACL_REVISION1, MAXDWORD, ace, ace->Header.AceSize);
ok(!ret, "AddAce succeeded\n");
ok(GetLastError() == ERROR_INVALID_PARAMETER, "GetLastError() = %d\n", GetLastError());
}
static void test_AddMandatoryAce(void)
{
static SID low_level = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
{SECURITY_MANDATORY_LOW_RID}};
static SID medium_level = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
{SECURITY_MANDATORY_MEDIUM_RID}};
static SID_IDENTIFIER_AUTHORITY sia_world = {SECURITY_WORLD_SID_AUTHORITY};
char buffer_sd[SECURITY_DESCRIPTOR_MIN_LENGTH];
SECURITY_DESCRIPTOR *sd2, *sd = (SECURITY_DESCRIPTOR *)&buffer_sd;
BOOL defaulted, present, ret, found, found2;
ACL_SIZE_INFORMATION acl_size_info;
SYSTEM_MANDATORY_LABEL_ACE *ace;
char buffer_acl[256];
ACL *acl = (ACL *)&buffer_acl;
SECURITY_ATTRIBUTES sa;
DWORD index, size;
HANDLE handle;
SID *everyone;
ACL *sacl;
if (!pAddMandatoryAce)
{
win_skip("AddMandatoryAce not supported, skipping test\n");
return;
}
ret = InitializeSecurityDescriptor(sd, SECURITY_DESCRIPTOR_REVISION);
ok(ret, "InitializeSecurityDescriptor failed with error %u\n", GetLastError());
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = sd;
sa.bInheritHandle = FALSE;
handle = CreateEventA(&sa, TRUE, TRUE, "test_event");
ok(handle != NULL, "CreateEventA failed with error %u\n", GetLastError());
ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, NULL, 0, &size);
ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"Unexpected GetKernelObjectSecurity return value %u, error %u\n", ret, GetLastError());
sd2 = HeapAlloc(GetProcessHeap(), 0, size);
ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd2, size, &size);
ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
sacl = (void *)0xdeadbeef;
present = TRUE;
ret = GetSecurityDescriptorSacl(sd2, &present, &sacl, &defaulted);
ok(ret, "GetSecurityDescriptorSacl failed with error %u\n", GetLastError());
ok(!present, "SACL is present\n");
ok(sacl == (void *)0xdeadbeef, "SACL is set\n");
HeapFree(GetProcessHeap(), 0, sd2);
CloseHandle(handle);
memset(buffer_acl, 0, sizeof(buffer_acl));
ret = InitializeAcl(acl, 256, ACL_REVISION);
ok(ret, "InitializeAcl failed with %u\n", GetLastError());
SetLastError(0xdeadbeef);
ret = pAddMandatoryAce(acl, ACL_REVISION, 0, 0x1234, &low_level);
ok(!ret, "AddMandatoryAce succeeded\n");
ok(GetLastError() == ERROR_INVALID_PARAMETER,
"Expected ERROR_INVALID_PARAMETER got %u\n", GetLastError());
ret = pAddMandatoryAce(acl, ACL_REVISION, 0, SYSTEM_MANDATORY_LABEL_NO_WRITE_UP, &low_level);
ok(ret, "AddMandatoryAce failed with %u\n", GetLastError());
index = 0;
found = FALSE;
while (pGetAce(acl, index++, (void **)&ace))
{
if (ace->Header.AceType != SYSTEM_MANDATORY_LABEL_ACE_TYPE) continue;
ok(ace->Header.AceFlags == 0, "Expected flags 0, got %x\n", ace->Header.AceFlags);
ok(ace->Mask == SYSTEM_MANDATORY_LABEL_NO_WRITE_UP,
"Expected mask SYSTEM_MANDATORY_LABEL_NO_WRITE_UP, got %x\n", ace->Mask);
ok(EqualSid(&ace->SidStart, &low_level), "Expected low integrity level\n");
found = TRUE;
}
ok(found, "Could not find mandatory label ace\n");
ret = SetSecurityDescriptorSacl(sd, TRUE, acl, FALSE);
ok(ret, "SetSecurityDescriptorSacl failed with error %u\n", GetLastError());
handle = CreateEventA(&sa, TRUE, TRUE, "test_event");
ok(handle != NULL, "CreateEventA failed with error %u\n", GetLastError());
ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, NULL, 0, &size);
ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"Unexpected GetKernelObjectSecurity return value %u, error %u\n", ret, GetLastError());
sd2 = HeapAlloc(GetProcessHeap(), 0, size);
ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd2, size, &size);
ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
sacl = (void *)0xdeadbeef;
present = FALSE;
defaulted = TRUE;
ret = GetSecurityDescriptorSacl(sd2, &present, &sacl, &defaulted);
ok(ret, "GetSecurityDescriptorSacl failed with error %u\n", GetLastError());
ok(present, "SACL not present\n");
ok(sacl != (void *)0xdeadbeef, "SACL not set\n");
ok(!defaulted, "SACL defaulted\n");
ret = pGetAclInformation(sacl, &acl_size_info, sizeof(acl_size_info), AclSizeInformation);
ok(ret, "GetAclInformation failed with error %u\n", GetLastError());
ok(acl_size_info.AceCount == 1, "SACL contains an unexpected ACE count %u\n", acl_size_info.AceCount);
ret = pGetAce(sacl, 0, (void **)&ace);
ok(ret, "GetAce failed with error %u\n", GetLastError());
ok (ace->Header.AceType == SYSTEM_MANDATORY_LABEL_ACE_TYPE, "Unexpected ACE type %#x\n", ace->Header.AceType);
ok(!ace->Header.AceFlags, "Unexpected ACE flags %#x\n", ace->Header.AceFlags);
ok(ace->Mask == SYSTEM_MANDATORY_LABEL_NO_WRITE_UP, "Unexpected ACE mask %#x\n", ace->Mask);
ok(EqualSid(&ace->SidStart, &low_level), "Expected low integrity level\n");
HeapFree(GetProcessHeap(), 0, sd2);
ret = pAddMandatoryAce(acl, ACL_REVISION, 0, SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP, &medium_level);
ok(ret, "AddMandatoryAce failed with error %u\n", GetLastError());
ret = SetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd);
ok(ret, "SetKernelObjectSecurity failed with error %u\n", GetLastError());
ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, NULL, 0, &size);
ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"Unexpected GetKernelObjectSecurity return value %u, error %u\n", ret, GetLastError());
sd2 = HeapAlloc(GetProcessHeap(), 0, size);
ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd2, size, &size);
ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
sacl = (void *)0xdeadbeef;
present = FALSE;
defaulted = TRUE;
ret = GetSecurityDescriptorSacl(sd2, &present, &sacl, &defaulted);
ok(ret, "GetSecurityDescriptorSacl failed with error %u\n", GetLastError());
ok(present, "SACL not present\n");
ok(sacl != (void *)0xdeadbeef, "SACL not set\n");
ok(sacl->AceCount == 2, "Expected 2 ACEs, got %d\n", sacl->AceCount);
ok(!defaulted, "SACL defaulted\n");
index = 0;
found = found2 = FALSE;
while (pGetAce(sacl, index++, (void **)&ace))
{
if (ace->Header.AceType == SYSTEM_MANDATORY_LABEL_ACE_TYPE)
{
if (EqualSid(&ace->SidStart, &low_level))
{
found = TRUE;
ok(!ace->Header.AceFlags, "Expected 0 as flags, got %#x\n", ace->Header.AceFlags);
ok(ace->Mask == SYSTEM_MANDATORY_LABEL_NO_WRITE_UP,
"Expected SYSTEM_MANDATORY_LABEL_NO_WRITE_UP as mask, got %#x\n", ace->Mask);
}
if (EqualSid(&ace->SidStart, &medium_level))
{
found2 = TRUE;
ok(!ace->Header.AceFlags, "Expected 0 as flags, got %#x\n", ace->Header.AceFlags);
ok(ace->Mask == SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP,
"Expected SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP as mask, got %#x\n", ace->Mask);
}
}
}
ok(found, "Could not find low mandatory label\n");
ok(found2, "Could not find medium mandatory label\n");
HeapFree(GetProcessHeap(), 0, sd2);
ret = SetSecurityDescriptorSacl(sd, FALSE, NULL, FALSE);
ok(ret, "SetSecurityDescriptorSacl failed with error %u\n", GetLastError());
ret = SetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd);
ok(ret, "SetKernelObjectSecurity failed with error %u\n", GetLastError());
ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, NULL, 0, &size);
ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"Unexpected GetKernelObjectSecurity return value %d, error %u\n", ret, GetLastError());
sd2 = HeapAlloc(GetProcessHeap(), 0, size);
ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd2, size, &size);
ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
sacl = (void *)0xdeadbeef;
present = FALSE;
defaulted = TRUE;
ret = GetSecurityDescriptorSacl(sd2, &present, &sacl, &defaulted);
ok(ret, "GetSecurityDescriptorSacl failed with error %u\n", GetLastError());
ok(present, "SACL not present\n");
ok(sacl && sacl != (void *)0xdeadbeef, "SACL not set\n");
ok(!defaulted, "SACL defaulted\n");
ok(!sacl->AceCount, "SACL contains an unexpected ACE count %u\n", sacl->AceCount);
HeapFree(GetProcessHeap(), 0, sd2);
ret = InitializeAcl(acl, 256, ACL_REVISION);
ok(ret, "InitializeAcl failed with error %u\n", GetLastError());
ret = pAddMandatoryAce(acl, ACL_REVISION3, 0, SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP, &medium_level);
ok(ret, "AddMandatoryAce failed with error %u\n", GetLastError());
ret = SetSecurityDescriptorSacl(sd, TRUE, acl, FALSE);
ok(ret, "SetSecurityDescriptorSacl failed with error %u\n", GetLastError());
ret = SetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd);
ok(ret, "SetKernelObjectSecurity failed with error %u\n", GetLastError());
ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, NULL, 0, &size);
ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"Unexpected GetKernelObjectSecurity return value %d, error %u\n", ret, GetLastError());
sd2 = HeapAlloc(GetProcessHeap(), 0, size);
ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd2, size, &size);
ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
sacl = (void *)0xdeadbeef;
present = FALSE;
defaulted = TRUE;
ret = GetSecurityDescriptorSacl(sd2, &present, &sacl, &defaulted);
ok(ret, "GetSecurityDescriptorSacl failed with error %u\n", GetLastError());
ok(present, "SACL not present\n");
ok(sacl != (void *)0xdeadbeef, "SACL not set\n");
ok(sacl->AclRevision == ACL_REVISION3, "Expected revision 3, got %d\n", sacl->AclRevision);
ok(!defaulted, "SACL defaulted\n");
HeapFree(GetProcessHeap(), 0, sd2);
ret = InitializeAcl(acl, 256, ACL_REVISION);
ok(ret, "InitializeAcl failed with error %u\n", GetLastError());
ret = AllocateAndInitializeSid(&sia_world, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, (void **)&everyone);
ok(ret, "AllocateAndInitializeSid failed with error %u\n", GetLastError());
ret = AddAccessAllowedAce(acl, ACL_REVISION, KEY_READ, everyone);
ok(ret, "AddAccessAllowedAce failed with error %u\n", GetLastError());
ret = SetSecurityDescriptorSacl(sd, TRUE, acl, FALSE);
ok(ret, "SetSecurityDescriptorSacl failed with error %u\n", GetLastError());
ret = SetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd);
ok(ret, "SetKernelObjectSecurity failed with error %u\n", GetLastError());
ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, NULL, 0, &size);
ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"Unexpected GetKernelObjectSecurity return value %d, error %u\n", ret, GetLastError());
sd2 = HeapAlloc(GetProcessHeap(), 0, size);
ret = GetKernelObjectSecurity(handle, LABEL_SECURITY_INFORMATION, sd2, size, &size);
ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
sacl = (void *)0xdeadbeef;
present = FALSE;
defaulted = TRUE;
ret = GetSecurityDescriptorSacl(sd2, &present, &sacl, &defaulted);
ok(ret, "GetSecurityDescriptorSacl failed with error %u\n", GetLastError());
ok(present, "SACL not present\n");
ok(sacl && sacl != (void *)0xdeadbeef, "SACL not set\n");
ok(!defaulted, "SACL defaulted\n");
ok(!sacl->AceCount, "SACL contains an unexpected ACE count %u\n", sacl->AceCount);
FreeSid(everyone);
HeapFree(GetProcessHeap(), 0, sd2);
CloseHandle(handle);
}
static void test_system_security_access(void)
{
static const WCHAR testkeyW[] =
{'S','O','F','T','W','A','R','E','\\','W','i','n','e','\\','S','A','C','L','t','e','s','t',0};
LONG res;
HKEY hkey;
PSECURITY_DESCRIPTOR sd;
ACL *sacl;
DWORD err, len = 128;
TOKEN_PRIVILEGES priv, *priv_prev;
HANDLE token;
LUID luid;
BOOL ret;
if (!OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &token )) return;
if (!LookupPrivilegeValueA( NULL, SE_SECURITY_NAME, &luid ))
{
CloseHandle( token );
return;
}
/* ACCESS_SYSTEM_SECURITY requires special privilege */
res = RegCreateKeyExW( HKEY_LOCAL_MACHINE, testkeyW, 0, NULL, 0, KEY_READ|ACCESS_SYSTEM_SECURITY, NULL, &hkey, NULL );
if (res == ERROR_ACCESS_DENIED)
{
skip( "unprivileged user\n" );
CloseHandle( token );
return;
}
todo_wine ok( res == ERROR_PRIVILEGE_NOT_HELD, "got %d\n", res );
priv.PrivilegeCount = 1;
priv.Privileges[0].Luid = luid;
priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
priv_prev = HeapAlloc( GetProcessHeap(), 0, len );
ret = AdjustTokenPrivileges( token, FALSE, &priv, len, priv_prev, &len );
ok( ret, "got %u\n", GetLastError());
res = RegCreateKeyExW( HKEY_LOCAL_MACHINE, testkeyW, 0, NULL, 0, KEY_READ|ACCESS_SYSTEM_SECURITY, NULL, &hkey, NULL );
if (res == ERROR_PRIVILEGE_NOT_HELD)
{
win_skip( "privilege not held\n" );
HeapFree( GetProcessHeap(), 0, priv_prev );
CloseHandle( token );
return;
}
ok( !res, "got %d\n", res );
/* restore privileges */
ret = AdjustTokenPrivileges( token, FALSE, priv_prev, 0, NULL, NULL );
ok( ret, "got %u\n", GetLastError() );
HeapFree( GetProcessHeap(), 0, priv_prev );
/* privilege is checked on access */
err = GetSecurityInfo( hkey, SE_REGISTRY_KEY, SACL_SECURITY_INFORMATION, NULL, NULL, NULL, &sacl, &sd );
todo_wine ok( err == ERROR_PRIVILEGE_NOT_HELD || err == ERROR_ACCESS_DENIED, "got %u\n", err );
if (err == ERROR_SUCCESS)
LocalFree( sd );
priv.PrivilegeCount = 1;
priv.Privileges[0].Luid = luid;
priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
priv_prev = HeapAlloc( GetProcessHeap(), 0, len );
ret = AdjustTokenPrivileges( token, FALSE, &priv, len, priv_prev, &len );
ok( ret, "got %u\n", GetLastError());
err = GetSecurityInfo( hkey, SE_REGISTRY_KEY, SACL_SECURITY_INFORMATION, NULL, NULL, NULL, &sacl, &sd );
ok( err == ERROR_SUCCESS, "got %u\n", err );
RegCloseKey( hkey );
LocalFree( sd );
/* handle created without ACCESS_SYSTEM_SECURITY, privilege held */
res = RegCreateKeyExW( HKEY_LOCAL_MACHINE, testkeyW, 0, NULL, 0, KEY_READ, NULL, &hkey, NULL );
ok( res == ERROR_SUCCESS, "got %d\n", res );
sd = NULL;
err = GetSecurityInfo( hkey, SE_REGISTRY_KEY, SACL_SECURITY_INFORMATION, NULL, NULL, NULL, &sacl, &sd );
todo_wine ok( err == ERROR_SUCCESS, "got %u\n", err );
RegCloseKey( hkey );
LocalFree( sd );
/* restore privileges */
ret = AdjustTokenPrivileges( token, FALSE, priv_prev, 0, NULL, NULL );
ok( ret, "got %u\n", GetLastError() );
HeapFree( GetProcessHeap(), 0, priv_prev );
/* handle created without ACCESS_SYSTEM_SECURITY, privilege not held */
res = RegCreateKeyExW( HKEY_LOCAL_MACHINE, testkeyW, 0, NULL, 0, KEY_READ, NULL, &hkey, NULL );
ok( res == ERROR_SUCCESS, "got %d\n", res );
err = GetSecurityInfo( hkey, SE_REGISTRY_KEY, SACL_SECURITY_INFORMATION, NULL, NULL, NULL, &sacl, &sd );
ok( err == ERROR_PRIVILEGE_NOT_HELD || err == ERROR_ACCESS_DENIED, "got %u\n", err );
RegCloseKey( hkey );
res = RegDeleteKeyW( HKEY_LOCAL_MACHINE, testkeyW );
ok( !res, "got %d\n", res );
CloseHandle( token );
}
static void test_GetWindowsAccountDomainSid(void)
{
char *user, buffer1[SECURITY_MAX_SID_SIZE], buffer2[SECURITY_MAX_SID_SIZE];
SID_IDENTIFIER_AUTHORITY domain_ident = { SECURITY_NT_AUTHORITY };
PSID domain_sid = (PSID *)&buffer1;
PSID domain_sid2 = (PSID *)&buffer2;
DWORD sid_size;
PSID user_sid;
HANDLE token;
BOOL bret = TRUE;
int i;
if (!pGetWindowsAccountDomainSid)
{
win_skip("GetWindowsAccountDomainSid not available\n");
return;
}
if (!OpenThreadToken(GetCurrentThread(), TOKEN_READ, TRUE, &token))
{
if (GetLastError() != ERROR_NO_TOKEN) bret = FALSE;
else if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &token)) bret = FALSE;
}
if (!bret)
{
win_skip("Failed to get current user token\n");
return;
}
bret = GetTokenInformation(token, TokenUser, NULL, 0, &sid_size);
ok(!bret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
user = HeapAlloc(GetProcessHeap(), 0, sid_size);
bret = GetTokenInformation(token, TokenUser, user, sid_size, &sid_size);
ok(bret, "GetTokenInformation(TokenUser) failed with error %d\n", GetLastError());
CloseHandle(token);
user_sid = ((TOKEN_USER *)user)->User.Sid;
SetLastError(0xdeadbeef);
bret = pGetWindowsAccountDomainSid(0, 0, 0);
ok(!bret, "GetWindowsAccountDomainSid succeeded\n");
ok(GetLastError() == ERROR_INVALID_SID, "expected ERROR_INVALID_SID, got %d\n", GetLastError());
SetLastError(0xdeadbeef);
bret = pGetWindowsAccountDomainSid(user_sid, 0, 0);
ok(!bret, "GetWindowsAccountDomainSid succeeded\n");
ok(GetLastError() == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
sid_size = SECURITY_MAX_SID_SIZE;
SetLastError(0xdeadbeef);
bret = pGetWindowsAccountDomainSid(user_sid, 0, &sid_size);
ok(!bret, "GetWindowsAccountDomainSid succeeded\n");
ok(GetLastError() == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
ok(sid_size == GetSidLengthRequired(4), "expected size %d, got %d\n", GetSidLengthRequired(4), sid_size);
SetLastError(0xdeadbeef);
bret = pGetWindowsAccountDomainSid(user_sid, domain_sid, 0);
ok(!bret, "GetWindowsAccountDomainSid succeeded\n");
ok(GetLastError() == ERROR_INVALID_PARAMETER, "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
sid_size = 1;
SetLastError(0xdeadbeef);
bret = pGetWindowsAccountDomainSid(user_sid, domain_sid, &sid_size);
ok(!bret, "GetWindowsAccountDomainSid succeeded\n");
ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
ok(sid_size == GetSidLengthRequired(4), "expected size %d, got %d\n", GetSidLengthRequired(4), sid_size);
sid_size = SECURITY_MAX_SID_SIZE;
bret = pGetWindowsAccountDomainSid(user_sid, domain_sid, &sid_size);
ok(bret, "GetWindowsAccountDomainSid failed with error %d\n", GetLastError());
ok(sid_size == GetSidLengthRequired(4), "expected size %d, got %d\n", GetSidLengthRequired(4), sid_size);
InitializeSid(domain_sid2, &domain_ident, 4);
for (i = 0; i < 4; i++)
*GetSidSubAuthority(domain_sid2, i) = *GetSidSubAuthority(user_sid, i);
ok(EqualSid(domain_sid, domain_sid2), "unexpected domain sid %s != %s\n",
debugstr_sid(domain_sid), debugstr_sid(domain_sid2));
HeapFree(GetProcessHeap(), 0, user);
}
static void test_GetSidIdentifierAuthority(void)
{
char buffer[SECURITY_MAX_SID_SIZE];
PSID authority_sid = (PSID *)buffer;
PSID_IDENTIFIER_AUTHORITY id;
BOOL ret;
if (!pGetSidIdentifierAuthority)
{
win_skip("GetSidIdentifierAuthority not available\n");
return;
}
memset(buffer, 0xcc, sizeof(buffer));
ret = IsValidSid(authority_sid);
ok(!ret, "expected FALSE, got %u\n", ret);
SetLastError(0xdeadbeef);
id = GetSidIdentifierAuthority(authority_sid);
ok(id != NULL, "got NULL pointer as identifier authority\n");
ok(GetLastError() == ERROR_SUCCESS, "expected ERROR_SUCCESS, got %u\n", GetLastError());
SetLastError(0xdeadbeef);
id = GetSidIdentifierAuthority(NULL);
ok(id != NULL, "got NULL pointer as identifier authority\n");
ok(GetLastError() == ERROR_SUCCESS, "expected ERROR_SUCCESS, got %u\n", GetLastError());
}
static void test_pseudo_tokens(void)
{
TOKEN_STATISTICS statistics1, statistics2;
HANDLE token;
DWORD retlen;
BOOL ret;
ret = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token);
ok(ret, "OpenProcessToken failed with error %u\n", GetLastError());
memset(&statistics1, 0x11, sizeof(statistics1));
ret = GetTokenInformation(token, TokenStatistics, &statistics1, sizeof(statistics1), &retlen);
ok(ret, "GetTokenInformation failed with %u\n", GetLastError());
CloseHandle(token);
/* test GetCurrentProcessToken() */
SetLastError(0xdeadbeef);
memset(&statistics2, 0x22, sizeof(statistics2));
ret = GetTokenInformation(GetCurrentProcessToken(), TokenStatistics,
&statistics2, sizeof(statistics2), &retlen);
ok(ret || broken(GetLastError() == ERROR_INVALID_HANDLE),
"GetTokenInformation failed with %u\n", GetLastError());
if (ret)
ok(!memcmp(&statistics1, &statistics2, sizeof(statistics1)), "Token statistics do not match\n");
else
win_skip("CurrentProcessToken not supported, skipping test\n");
/* test GetCurrentThreadEffectiveToken() */
SetLastError(0xdeadbeef);
memset(&statistics2, 0x22, sizeof(statistics2));
ret = GetTokenInformation(GetCurrentThreadEffectiveToken(), TokenStatistics,
&statistics2, sizeof(statistics2), &retlen);
ok(ret || broken(GetLastError() == ERROR_INVALID_HANDLE),
"GetTokenInformation failed with %u\n", GetLastError());
if (ret)
ok(!memcmp(&statistics1, &statistics2, sizeof(statistics1)), "Token statistics do not match\n");
else
win_skip("CurrentThreadEffectiveToken not supported, skipping test\n");
SetLastError(0xdeadbeef);
ret = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &token);
ok(!ret, "OpenThreadToken should have failed\n");
ok(GetLastError() == ERROR_NO_TOKEN, "Expected ERROR_NO_TOKEN, got %u\n", GetLastError());
/* test GetCurrentThreadToken() */
SetLastError(0xdeadbeef);
ret = GetTokenInformation(GetCurrentThreadToken(), TokenStatistics,
&statistics2, sizeof(statistics2), &retlen);
todo_wine ok(GetLastError() == ERROR_NO_TOKEN || broken(GetLastError() == ERROR_INVALID_HANDLE),
"Expected ERROR_NO_TOKEN, got %u\n", GetLastError());
}
static void test_maximum_allowed(void)
{
HANDLE (WINAPI *pCreateEventExA)(SECURITY_ATTRIBUTES *, LPCSTR, DWORD, DWORD);
char buffer_sd[SECURITY_DESCRIPTOR_MIN_LENGTH], buffer_acl[256];
SECURITY_DESCRIPTOR *sd = (SECURITY_DESCRIPTOR *)&buffer_sd;
SECURITY_ATTRIBUTES sa;
ACL *acl = (ACL *)&buffer_acl;
HMODULE hkernel32 = GetModuleHandleA("kernel32.dll");
ACCESS_MASK mask;
HANDLE handle;
BOOL ret;
pCreateEventExA = (void *)GetProcAddress(hkernel32, "CreateEventExA");
if (!pCreateEventExA)
{
win_skip("CreateEventExA is not available\n");
return;
}
ret = InitializeSecurityDescriptor(sd, SECURITY_DESCRIPTOR_REVISION);
ok(ret, "InitializeSecurityDescriptor failed with %u\n", GetLastError());
memset(buffer_acl, 0, sizeof(buffer_acl));
ret = InitializeAcl(acl, 256, ACL_REVISION);
ok(ret, "InitializeAcl failed with %u\n", GetLastError());
ret = SetSecurityDescriptorDacl(sd, TRUE, acl, FALSE);
ok(ret, "SetSecurityDescriptorDacl failed with %u\n", GetLastError());
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = sd;
sa.bInheritHandle = FALSE;
handle = pCreateEventExA(&sa, NULL, 0, MAXIMUM_ALLOWED | 0x4);
ok(handle != NULL, "CreateEventExA failed with error %u\n", GetLastError());
mask = get_obj_access(handle);
ok(mask == EVENT_ALL_ACCESS, "Expected %x, got %x\n", EVENT_ALL_ACCESS, mask);
CloseHandle(handle);
}
static void test_token_label(void)
{
static SID medium_sid = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
{SECURITY_MANDATORY_MEDIUM_RID}};
static SID high_sid = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
{SECURITY_MANDATORY_HIGH_RID}};
SECURITY_DESCRIPTOR_CONTROL control;
SYSTEM_MANDATORY_LABEL_ACE *ace;
BOOL ret, present, defaulted;
SECURITY_DESCRIPTOR *sd;
ACL *sacl = NULL, *dacl;
DWORD size, revision;
HANDLE token;
char *str;
SID *sid;
ret = OpenProcessToken(GetCurrentProcess(), READ_CONTROL | WRITE_OWNER, &token);
ok(ret, "OpenProcessToken failed with error %u\n", GetLastError());
ret = GetKernelObjectSecurity(token, LABEL_SECURITY_INFORMATION, NULL, 0, &size);
ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"Unexpected GetKernelObjectSecurity return value %d, error %u\n", ret, GetLastError());
sd = HeapAlloc(GetProcessHeap(), 0, size);
ret = GetKernelObjectSecurity(token, LABEL_SECURITY_INFORMATION, sd, size, &size);
ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
ret = GetSecurityDescriptorControl(sd, &control, &revision);
ok(ret, "GetSecurityDescriptorControl failed with error %u\n", GetLastError());
todo_wine ok(control == (SE_SELF_RELATIVE | SE_SACL_AUTO_INHERITED | SE_SACL_PRESENT) ||
broken(control == SE_SELF_RELATIVE) /* WinXP, Win2003 */,
"Unexpected security descriptor control %#x\n", control);
ok(revision == 1, "Unexpected security descriptor revision %u\n", revision);
sid = (void *)0xdeadbeef;
defaulted = TRUE;
ret = GetSecurityDescriptorOwner(sd, (void **)&sid, &defaulted);
ok(ret, "GetSecurityDescriptorOwner failed with error %u\n", GetLastError());
ok(!sid, "Owner present\n");
ok(!defaulted, "Owner defaulted\n");
sid = (void *)0xdeadbeef;
defaulted = TRUE;
ret = GetSecurityDescriptorGroup(sd, (void **)&sid, &defaulted);
ok(ret, "GetSecurityDescriptorGroup failed with error %u\n", GetLastError());
ok(!sid, "Group present\n");
ok(!defaulted, "Group defaulted\n");
ret = GetSecurityDescriptorSacl(sd, &present, &sacl, &defaulted);
ok(ret, "GetSecurityDescriptorSacl failed with error %u\n", GetLastError());
ok(present || broken(!present) /* WinXP, Win2003 */, "No SACL in the security descriptor\n");
ok(sacl || broken(!sacl) /* WinXP, Win2003 */, "NULL SACL in the security descriptor\n");
if (present)
{
ok(!defaulted, "SACL defaulted\n");
ok(sacl->AceCount == 1, "SACL contains an unexpected ACE count %u\n", sacl->AceCount);
ret = pGetAce(sacl, 0, (void **)&ace);
ok(ret, "GetAce failed with error %u\n", GetLastError());
ok(ace->Header.AceType == SYSTEM_MANDATORY_LABEL_ACE_TYPE,
"Unexpected ACE type %#x\n", ace->Header.AceType);
ok(!ace->Header.AceFlags, "Unexpected ACE flags %#x\n", ace->Header.AceFlags);
ok(ace->Header.AceSize, "Unexpected ACE size %u\n", ace->Header.AceSize);
ok(ace->Mask == SYSTEM_MANDATORY_LABEL_NO_WRITE_UP, "Unexpected ACE mask %#x\n", ace->Mask);
sid = (SID *)&ace->SidStart;
ConvertSidToStringSidA(sid, &str);
ok(EqualSid(sid, &medium_sid) || EqualSid(sid, &high_sid), "Got unexpected SID %s\n", str);
LocalFree(str);
}
ret = GetSecurityDescriptorDacl(sd, &present, &dacl, &defaulted);
ok(ret, "GetSecurityDescriptorDacl failed with error %u\n", GetLastError());
todo_wine ok(!present, "DACL present\n");
HeapFree(GetProcessHeap(), 0, sd);
CloseHandle(token);
}
static void test_token_security_descriptor(void)
{
static SID low_level = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
{SECURITY_MANDATORY_LOW_RID}};
char buffer_sd[SECURITY_DESCRIPTOR_MIN_LENGTH];
SECURITY_DESCRIPTOR *sd = (SECURITY_DESCRIPTOR *)&buffer_sd, *sd2;
char buffer_acl[256], buffer[MAX_PATH];
ACL *acl = (ACL *)&buffer_acl, *acl2, *acl_child;
BOOL defaulted, present, ret, found;
HANDLE token, token2, token3;
EXPLICIT_ACCESSW exp_access;
PROCESS_INFORMATION info;
DWORD size, index, retd;
ACCESS_ALLOWED_ACE *ace;
SECURITY_ATTRIBUTES sa;
STARTUPINFOA startup;
PSID psid;
if (!pDuplicateTokenEx || !pConvertStringSidToSidA || !pAddAccessAllowedAceEx || !pGetAce
|| !pSetEntriesInAclW)
{
win_skip("Some functions not available\n");
return;
}
/* Test whether we can create tokens with security descriptors */
ret = OpenProcessToken(GetCurrentProcess(), MAXIMUM_ALLOWED, &token);
ok(ret, "OpenProcessToken failed with error %u\n", GetLastError());
ret = InitializeSecurityDescriptor(sd, SECURITY_DESCRIPTOR_REVISION);
ok(ret, "InitializeSecurityDescriptor failed with error %u\n", GetLastError());
memset(buffer_acl, 0, sizeof(buffer_acl));
ret = InitializeAcl(acl, 256, ACL_REVISION);
ok(ret, "InitializeAcl failed with error %u\n", GetLastError());
ret = pConvertStringSidToSidA("S-1-5-6", &psid);
ok(ret, "ConvertStringSidToSidA failed with error %u\n", GetLastError());
ret = pAddAccessAllowedAceEx(acl, ACL_REVISION, NO_PROPAGATE_INHERIT_ACE, GENERIC_ALL, psid);
ok(ret, "AddAccessAllowedAceEx failed with error %u\n", GetLastError());
ret = SetSecurityDescriptorDacl(sd, TRUE, acl, FALSE);
ok(ret, "SetSecurityDescriptorDacl failed with error %u\n", GetLastError());
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = sd;
sa.bInheritHandle = FALSE;
ret = pDuplicateTokenEx(token, MAXIMUM_ALLOWED, &sa, SecurityImpersonation, TokenImpersonation, &token2);
ok(ret, "DuplicateTokenEx failed with error %u\n", GetLastError());
ret = GetKernelObjectSecurity(token2, DACL_SECURITY_INFORMATION, NULL, 0, &size);
ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"Unexpected GetKernelObjectSecurity return value %d, error %u\n", ret, GetLastError());
sd2 = HeapAlloc(GetProcessHeap(), 0, size);
ret = GetKernelObjectSecurity(token2, DACL_SECURITY_INFORMATION, sd2, size, &size);
ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
acl2 = (void *)0xdeadbeef;
present = FALSE;
defaulted = TRUE;
ret = GetSecurityDescriptorDacl(sd2, &present, &acl2, &defaulted);
ok(ret, "GetSecurityDescriptorDacl failed with error %u\n", GetLastError());
ok(present, "acl2 not present\n");
ok(acl2 != (void *)0xdeadbeef, "acl2 not set\n");
ok(acl2->AceCount == 1, "Expected 1 ACE, got %d\n", acl2->AceCount);
ok(!defaulted, "acl2 defaulted\n");
ret = pGetAce(acl2, 0, (void **)&ace);
ok(ret, "GetAce failed with error %u\n", GetLastError());
ok(ace->Header.AceType == ACCESS_ALLOWED_ACE_TYPE, "Unexpected ACE type %#x\n", ace->Header.AceType);
ok(EqualSid(&ace->SidStart, psid), "Expected access allowed ACE\n");
ok(ace->Header.AceFlags == NO_PROPAGATE_INHERIT_ACE,
"Expected NO_PROPAGATE_INHERIT_ACE as flags, got %x\n", ace->Header.AceFlags);
HeapFree(GetProcessHeap(), 0, sd2);
/* Duplicate token without security attributes.
* Tokens do not inherit the security descriptor in DuplicateToken. */
ret = pDuplicateTokenEx(token2, MAXIMUM_ALLOWED, NULL, SecurityImpersonation, TokenImpersonation, &token3);
ok(ret, "DuplicateTokenEx failed with error %u\n", GetLastError());
ret = GetKernelObjectSecurity(token3, DACL_SECURITY_INFORMATION, NULL, 0, &size);
ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"Unexpected GetKernelObjectSecurity return value %d, error %u\n", ret, GetLastError());
sd2 = HeapAlloc(GetProcessHeap(), 0, size);
ret = GetKernelObjectSecurity(token3, DACL_SECURITY_INFORMATION, sd2, size, &size);
ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
acl2 = (void *)0xdeadbeef;
present = FALSE;
defaulted = TRUE;
ret = GetSecurityDescriptorDacl(sd2, &present, &acl2, &defaulted);
ok(ret, "GetSecurityDescriptorDacl failed with error %u\n", GetLastError());
todo_wine
ok(present, "DACL not present\n");
if (present)
{
ok(acl2 != (void *)0xdeadbeef, "DACL not set\n");
ok(!defaulted, "DACL defaulted\n");
index = 0;
found = FALSE;
while (pGetAce(acl2, index++, (void **)&ace))
{
if (ace->Header.AceType == ACCESS_ALLOWED_ACE_TYPE && EqualSid(&ace->SidStart, psid))
found = TRUE;
}
ok(!found, "Access allowed ACE was inherited\n");
}
HeapFree(GetProcessHeap(), 0, sd2);
/* When creating a child process, the process does inherit the token of
* the parent but not the DACL of the token */
ret = GetKernelObjectSecurity(token, DACL_SECURITY_INFORMATION, NULL, 0, &size);
ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"Unexpected GetKernelObjectSecurity return value %d, error %u\n", ret, GetLastError());
sd2 = HeapAlloc(GetProcessHeap(), 0, size);
ret = GetKernelObjectSecurity(token, DACL_SECURITY_INFORMATION, sd2, size, &size);
ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
acl2 = (void *)0xdeadbeef;
present = FALSE;
defaulted = TRUE;
ret = GetSecurityDescriptorDacl(sd2, &present, &acl2, &defaulted);
ok(ret, "GetSecurityDescriptorDacl failed with error %u\n", GetLastError());
ok(present, "DACL not present\n");
ok(acl2 != (void *)0xdeadbeef, "DACL not set\n");
ok(!defaulted, "DACL defaulted\n");
exp_access.grfAccessPermissions = GENERIC_ALL;
exp_access.grfAccessMode = GRANT_ACCESS;
exp_access.grfInheritance = NO_PROPAGATE_INHERIT_ACE;
exp_access.Trustee.pMultipleTrustee = NULL;
exp_access.Trustee.TrusteeForm = TRUSTEE_IS_SID;
exp_access.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
exp_access.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
exp_access.Trustee.ptstrName = (void*)psid;
retd = pSetEntriesInAclW(1, &exp_access, acl2, &acl_child);
ok(retd == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", retd);
memset(sd, 0, sizeof(buffer_sd));
ret = InitializeSecurityDescriptor(sd, SECURITY_DESCRIPTOR_REVISION);
ok(ret, "InitializeSecurityDescriptor failed with error %u\n", GetLastError());
ret = SetSecurityDescriptorDacl(sd, TRUE, acl_child, FALSE);
ok(ret, "SetSecurityDescriptorDacl failed with error %u\n", GetLastError());
ret = SetKernelObjectSecurity(token, DACL_SECURITY_INFORMATION, sd);
ok(ret, "SetKernelObjectSecurity failed with error %u\n", GetLastError());
/* The security label is also not inherited */
if (pAddMandatoryAce)
{
ret = InitializeAcl(acl, 256, ACL_REVISION);
ok(ret, "InitializeAcl failed with error %u\n", GetLastError());
ret = pAddMandatoryAce(acl, ACL_REVISION, 0, SYSTEM_MANDATORY_LABEL_NO_WRITE_UP, &low_level);
ok(ret, "AddMandatoryAce failed with error %u\n", GetLastError());
memset(sd, 0, sizeof(buffer_sd));
ret = InitializeSecurityDescriptor(sd, SECURITY_DESCRIPTOR_REVISION);
ok(ret, "InitializeSecurityDescriptor failed with error %u\n", GetLastError());
ret = SetSecurityDescriptorSacl(sd, TRUE, acl, FALSE);
ok(ret, "SetSecurityDescriptorSacl failed with error %u\n", GetLastError());
ret = SetKernelObjectSecurity(token, LABEL_SECURITY_INFORMATION, sd);
ok(ret, "SetKernelObjectSecurity failed with error %u\n", GetLastError());
}
else
win_skip("SYSTEM_MANDATORY_LABEL not supported\n");
/* Start child process with our modified token */
memset(&startup, 0, sizeof(startup));
startup.cb = sizeof(startup);
startup.dwFlags = STARTF_USESHOWWINDOW;
startup.wShowWindow = SW_SHOWNORMAL;
sprintf(buffer, "%s tests/security.c test_token_sd", myARGV[0]);
ret = CreateProcessA(NULL, buffer, NULL, NULL, FALSE, 0, NULL, NULL, &startup, &info);
ok(ret, "CreateProcess failed with error %u\n", GetLastError());
winetest_wait_child_process(info.hProcess);
CloseHandle(info.hProcess);
CloseHandle(info.hThread);
LocalFree(acl_child);
HeapFree(GetProcessHeap(), 0, sd2);
LocalFree(psid);
CloseHandle(token3);
CloseHandle(token2);
CloseHandle(token);
}
static void test_child_token_sd(void)
{
static SID low_level = {SID_REVISION, 1, {SECURITY_MANDATORY_LABEL_AUTHORITY},
{SECURITY_MANDATORY_LOW_RID}};
SYSTEM_MANDATORY_LABEL_ACE *ace_label;
BOOL ret, present, defaulted;
ACCESS_ALLOWED_ACE *acc_ace;
SECURITY_DESCRIPTOR *sd;
DWORD size, i;
HANDLE token;
PSID psid;
ACL *acl;
ret = pConvertStringSidToSidA("S-1-5-6", &psid);
ok(ret, "ConvertStringSidToSidA failed with error %u\n", GetLastError());
ret = OpenProcessToken(GetCurrentProcess(), MAXIMUM_ALLOWED, &token);
ok(ret, "OpenProcessToken failed with error %u\n", GetLastError());
ret = GetKernelObjectSecurity(token, DACL_SECURITY_INFORMATION, NULL, 0, &size);
ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"Unexpected GetKernelObjectSecurity return value %d, error %u\n", ret, GetLastError());
sd = HeapAlloc(GetProcessHeap(), 0, size);
ret = GetKernelObjectSecurity(token, DACL_SECURITY_INFORMATION, sd, size, &size);
ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
acl = NULL;
present = FALSE;
defaulted = TRUE;
ret = GetSecurityDescriptorDacl(sd, &present, &acl, &defaulted);
ok(ret, "GetSecurityDescriptorDacl failed with error %u\n", GetLastError());
ok(present, "DACL not present\n");
ok(acl && acl != (void *)0xdeadbeef, "Got invalid DACL\n");
ok(!defaulted, "DACL defaulted\n");
ok(acl->AceCount, "Expected at least one ACE\n");
for (i = 0; i < acl->AceCount; i++)
{
ok(pGetAce(acl, i, (void **)&acc_ace), "GetAce failed with error %u\n", GetLastError());
ok(acc_ace->Header.AceType != ACCESS_ALLOWED_ACE_TYPE || !EqualSid(&acc_ace->SidStart, psid),
"ACE inherited from the parent\n");
}
LocalFree(psid);
HeapFree(GetProcessHeap(), 0, sd);
if (!pAddMandatoryAce)
{
win_skip("SYSTEM_MANDATORY_LABEL not supported\n");
return;
}
ret = GetKernelObjectSecurity(token, LABEL_SECURITY_INFORMATION, NULL, 0, &size);
ok(!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER,
"Unexpected GetKernelObjectSecurity return value %d, error %u\n", ret, GetLastError());
sd = HeapAlloc(GetProcessHeap(), 0, size);
ret = GetKernelObjectSecurity(token, LABEL_SECURITY_INFORMATION, sd, size, &size);
ok(ret, "GetKernelObjectSecurity failed with error %u\n", GetLastError());
acl = NULL;
present = FALSE;
defaulted = TRUE;
ret = GetSecurityDescriptorSacl(sd, &present, &acl, &defaulted);
ok(ret, "GetSecurityDescriptorSacl failed with error %u\n", GetLastError());
ok(present, "SACL not present\n");
ok(acl && acl != (void *)0xdeadbeef, "Got invalid SACL\n");
ok(!defaulted, "SACL defaulted\n");
ok(acl->AceCount == 1, "Expected exactly one ACE\n");
ret = pGetAce(acl, 0, (void **)&ace_label);
ok(ret, "GetAce failed with error %u\n", GetLastError());
ok(ace_label->Header.AceType == SYSTEM_MANDATORY_LABEL_ACE_TYPE,
"Unexpected ACE type %#x\n", ace_label->Header.AceType);
ok(!EqualSid(&ace_label->SidStart, &low_level),
"Low integrity level should not have been inherited\n");
HeapFree(GetProcessHeap(), 0, sd);
}
static void test_GetExplicitEntriesFromAclW(void)
{
static const WCHAR wszCurrentUser[] = { 'C','U','R','R','E','N','T','_','U','S','E','R','\0'};
SID_IDENTIFIER_AUTHORITY SIDAuthWorld = { SECURITY_WORLD_SID_AUTHORITY };
SID_IDENTIFIER_AUTHORITY SIDAuthNT = { SECURITY_NT_AUTHORITY };
PSID everyone_sid = NULL, users_sid = NULL;
EXPLICIT_ACCESSW access;
EXPLICIT_ACCESSW *access2;
PACL new_acl, old_acl = NULL;
ULONG count;
DWORD res;
if (!pGetExplicitEntriesFromAclW)
{
win_skip("GetExplicitEntriesFromAclW is not available\n");
return;
}
if (!pSetEntriesInAclW)
{
win_skip("SetEntriesInAclW is not available\n");
return;
}
old_acl = HeapAlloc(GetProcessHeap(), 0, 256);
res = InitializeAcl(old_acl, 256, ACL_REVISION);
if(!res && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
{
win_skip("ACLs not implemented - skipping tests\n");
HeapFree(GetProcessHeap(), 0, old_acl);
return;
}
ok(res, "InitializeAcl failed with error %d\n", GetLastError());
res = AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &everyone_sid);
ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
res = AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_USERS, 0, 0, 0, 0, 0, 0, &users_sid);
ok(res, "AllocateAndInitializeSid failed with error %d\n", GetLastError());
res = AddAccessAllowedAce(old_acl, ACL_REVISION, KEY_READ, users_sid);
ok(res, "AddAccessAllowedAce failed with error %d\n", GetLastError());
access2 = NULL;
res = pGetExplicitEntriesFromAclW(old_acl, &count, &access2);
ok(res == ERROR_SUCCESS, "GetExplicitEntriesFromAclW failed with error %d\n", GetLastError());
ok(count == 1, "Expected count == 1, got %d\n", count);
ok(access2[0].grfAccessMode == GRANT_ACCESS, "Expected GRANT_ACCESS, got %d\n", access2[0].grfAccessMode);
ok(access2[0].grfAccessPermissions == KEY_READ, "Expected KEY_READ, got %d\n", access2[0].grfAccessPermissions);
ok(access2[0].Trustee.TrusteeForm == TRUSTEE_IS_SID, "Expected SID trustee, got %d\n", access2[0].Trustee.TrusteeForm);
ok(access2[0].grfInheritance == NO_INHERITANCE, "Expected NO_INHERITANCE, got %x\n", access2[0].grfInheritance);
ok(EqualSid(access2[0].Trustee.ptstrName, users_sid), "Expected equal SIDs\n");
LocalFree(access2);
access.Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE;
access.Trustee.pMultipleTrustee = NULL;
access.grfAccessPermissions = KEY_WRITE;
access.grfAccessMode = GRANT_ACCESS;
access.grfInheritance = NO_INHERITANCE;
access.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
access.Trustee.TrusteeForm = TRUSTEE_IS_SID;
access.Trustee.ptstrName = everyone_sid;
res = pSetEntriesInAclW(1, &access, old_acl, &new_acl);
ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
ok(new_acl != NULL, "returned acl was NULL\n");
access2 = NULL;
res = pGetExplicitEntriesFromAclW(new_acl, &count, &access2);
ok(res == ERROR_SUCCESS, "GetExplicitEntriesFromAclW failed with error %d\n", GetLastError());
ok(count == 2, "Expected count == 2, got %d\n", count);
ok(access2[0].grfAccessMode == GRANT_ACCESS, "Expected GRANT_ACCESS, got %d\n", access2[0].grfAccessMode);
ok(access2[0].grfAccessPermissions == KEY_WRITE, "Expected KEY_WRITE, got %d\n", access2[0].grfAccessPermissions);
ok(access2[0].Trustee.TrusteeType == TRUSTEE_IS_UNKNOWN,
"Expected TRUSTEE_IS_UNKNOWN trustee type, got %d\n", access2[0].Trustee.TrusteeType);
ok(access2[0].Trustee.TrusteeForm == TRUSTEE_IS_SID, "Expected SID trustee, got %d\n", access2[0].Trustee.TrusteeForm);
ok(access2[0].grfInheritance == NO_INHERITANCE, "Expected NO_INHERITANCE, got %x\n", access2[0].grfInheritance);
ok(EqualSid(access2[0].Trustee.ptstrName, everyone_sid), "Expected equal SIDs\n");
LocalFree(access2);
LocalFree(new_acl);
access.Trustee.TrusteeType = TRUSTEE_IS_UNKNOWN;
res = pSetEntriesInAclW(1, &access, old_acl, &new_acl);
ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
ok(new_acl != NULL, "returned acl was NULL\n");
access2 = NULL;
res = pGetExplicitEntriesFromAclW(new_acl, &count, &access2);
ok(res == ERROR_SUCCESS, "GetExplicitEntriesFromAclW failed with error %d\n", GetLastError());
ok(count == 2, "Expected count == 2, got %d\n", count);
ok(access2[0].grfAccessMode == GRANT_ACCESS, "Expected GRANT_ACCESS, got %d\n", access2[0].grfAccessMode);
ok(access2[0].grfAccessPermissions == KEY_WRITE, "Expected KEY_WRITE, got %d\n", access2[0].grfAccessPermissions);
ok(access2[0].Trustee.TrusteeType == TRUSTEE_IS_UNKNOWN,
"Expected TRUSTEE_IS_UNKNOWN trustee type, got %d\n", access2[0].Trustee.TrusteeType);
ok(access2[0].Trustee.TrusteeForm == TRUSTEE_IS_SID, "Expected SID trustee, got %d\n", access2[0].Trustee.TrusteeForm);
ok(access2[0].grfInheritance == NO_INHERITANCE, "Expected NO_INHERITANCE, got %x\n", access2[0].grfInheritance);
ok(EqualSid(access2[0].Trustee.ptstrName, everyone_sid), "Expected equal SIDs\n");
LocalFree(access2);
LocalFree(new_acl);
access.Trustee.TrusteeForm = TRUSTEE_IS_NAME;
access.Trustee.ptstrName = (LPWSTR)wszCurrentUser;
res = pSetEntriesInAclW(1, &access, old_acl, &new_acl);
ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
ok(new_acl != NULL, "returned acl was NULL\n");
access2 = NULL;
res = pGetExplicitEntriesFromAclW(new_acl, &count, &access2);
ok(res == ERROR_SUCCESS, "GetExplicitEntriesFromAclW failed with error %d\n", GetLastError());
ok(count == 2, "Expected count == 2, got %d\n", count);
ok(access2[0].grfAccessMode == GRANT_ACCESS, "Expected GRANT_ACCESS, got %d\n", access2[0].grfAccessMode);
ok(access2[0].grfAccessPermissions == KEY_WRITE, "Expected KEY_WRITE, got %d\n", access2[0].grfAccessPermissions);
ok(access2[0].Trustee.TrusteeType == TRUSTEE_IS_UNKNOWN,
"Expected TRUSTEE_IS_UNKNOWN trustee type, got %d\n", access2[0].Trustee.TrusteeType);
ok(access2[0].Trustee.TrusteeForm == TRUSTEE_IS_SID, "Expected SID trustee, got %d\n", access2[0].Trustee.TrusteeForm);
ok(access2[0].grfInheritance == NO_INHERITANCE, "Expected NO_INHERITANCE, got %x\n", access2[0].grfInheritance);
LocalFree(access2);
LocalFree(new_acl);
access.grfAccessMode = REVOKE_ACCESS;
access.Trustee.TrusteeForm = TRUSTEE_IS_SID;
access.Trustee.ptstrName = users_sid;
res = pSetEntriesInAclW(1, &access, old_acl, &new_acl);
ok(res == ERROR_SUCCESS, "SetEntriesInAclW failed: %u\n", res);
ok(new_acl != NULL, "returned acl was NULL\n");
access2 = (void *)0xdeadbeef;
res = pGetExplicitEntriesFromAclW(new_acl, &count, &access2);
ok(res == ERROR_SUCCESS, "GetExplicitEntriesFromAclW failed with error %d\n", GetLastError());
ok(count == 0, "Expected count == 0, got %d\n", count);
ok(access2 == NULL, "access2 was not NULL\n");
LocalFree(new_acl);
FreeSid(users_sid);
FreeSid(everyone_sid);
HeapFree(GetProcessHeap(), 0, old_acl);
}
static void test_BuildSecurityDescriptorW(void)
{
SECURITY_DESCRIPTOR old_sd, *new_sd, *rel_sd;
ULONG new_sd_size;
DWORD buf_size;
char buf[1024];
BOOL success;
DWORD ret;
InitializeSecurityDescriptor(&old_sd, SECURITY_DESCRIPTOR_REVISION);
buf_size = sizeof(buf);
rel_sd = (SECURITY_DESCRIPTOR *)buf;
success = MakeSelfRelativeSD(&old_sd, rel_sd, &buf_size);
ok(success, "MakeSelfRelativeSD failed with %u\n", GetLastError());
new_sd = NULL;
new_sd_size = 0;
ret = BuildSecurityDescriptorW(NULL, NULL, 0, NULL, 0, NULL, NULL, &new_sd_size, (void **)&new_sd);
ok(ret == ERROR_SUCCESS, "BuildSecurityDescriptor failed with %u\n", ret);
ok(new_sd != NULL, "expected new_sd != NULL\n");
LocalFree(new_sd);
new_sd = (void *)0xdeadbeef;
ret = BuildSecurityDescriptorW(NULL, NULL, 0, NULL, 0, NULL, &old_sd, &new_sd_size, (void **)&new_sd);
ok(ret == ERROR_INVALID_SECURITY_DESCR, "expected ERROR_INVALID_SECURITY_DESCR, got %u\n", ret);
ok(new_sd == (void *)0xdeadbeef, "expected new_sd == 0xdeadbeef, got %p\n", new_sd);
new_sd = NULL;
new_sd_size = 0;
ret = BuildSecurityDescriptorW(NULL, NULL, 0, NULL, 0, NULL, rel_sd, &new_sd_size, (void **)&new_sd);
ok(ret == ERROR_SUCCESS, "BuildSecurityDescriptor failed with %u\n", ret);
ok(new_sd != NULL, "expected new_sd != NULL\n");
LocalFree(new_sd);
}
START_TEST(security)
{
init();
if (!hmod) return;
if (myARGC >= 3)
{
if (!strcmp(myARGV[2], "test_token_sd"))
test_child_token_sd();
else
test_process_security_child();
return;
}
test_kernel_objects_security();
test_sid();
test_trustee();
test_luid();
test_CreateWellKnownSid();
test_FileSecurity();
test_AccessCheck();
test_token_attr();
test_GetTokenInformation();
test_LookupAccountSid();
test_LookupAccountName();
test_security_descriptor();
test_process_security();
test_impersonation_level();
test_SetEntriesInAclW();
test_SetEntriesInAclA();
test_CreateDirectoryA();
test_GetNamedSecurityInfoA();
test_ConvertStringSecurityDescriptor();
test_ConvertSecurityDescriptorToString();
test_PrivateObjectSecurity();
test_acls();
test_GetWindowsAccountDomainSid();
test_GetSecurityInfo();
test_GetSidSubAuthority();
test_CheckTokenMembership();
test_EqualSid();
test_GetUserNameA();
test_GetUserNameW();
test_CreateRestrictedToken();
test_TokenIntegrityLevel();
test_default_dacl_owner_sid();
test_AdjustTokenPrivileges();
test_AddAce();
test_AddMandatoryAce();
test_system_security_access();
test_GetSidIdentifierAuthority();
test_pseudo_tokens();
test_maximum_allowed();
test_token_label();
test_GetExplicitEntriesFromAclW();
test_BuildSecurityDescriptorW();
/* Must be the last test, modifies process token */
test_token_security_descriptor();
}
|
147857.c | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
/*=====================================================================
**
** Source: GetStdHandle.c (test 2)
**
** Purpose: Smoke Tests the PAL implementation of the GetStdHandle function.
**
**
**===================================================================*/
#include <palsuite.h>
int __cdecl main(int argc, char *argv[])
{
HANDLE hFile = NULL;
if (0 != PAL_Initialize(argc,argv))
{
return FAIL;
}
/*
* attempt to get an invalid handle
*/
hFile = GetStdHandle(-2);
if (hFile != INVALID_HANDLE_VALUE)
{
Fail("GetStdHandle: ERROR -> A request for the STD_INPUT_HANDLE "
"returned an invalid handle.\n");
}
/*
* test the STD_INPUT_HANDLE handle
*/
hFile = GetStdHandle(STD_INPUT_HANDLE);
if (hFile == INVALID_HANDLE_VALUE)
{
Fail("GetStdHandle: ERROR -> A request for the STD_INPUT_HANDLE "
"returned an invalid handle.\n");
}
/*
* test the STD_OUTPUT_HANDLE handle
*/
hFile = GetStdHandle(STD_OUTPUT_HANDLE);
if (hFile == INVALID_HANDLE_VALUE)
{
Fail("GetStdHandle: ERROR -> A request for the STD_OUTPUT_HANDLE "
"returned an invalid handle.\n");
}
/* test the STD_ERROR_HANDLE handle */
hFile = GetStdHandle(STD_ERROR_HANDLE);
if (hFile == INVALID_HANDLE_VALUE)
{
Fail("GetStdHandle: ERROR -> A request for the STD_ERROR_HANDLE "
"returned an invalid handle.\n");
}
/* check to see if we can CloseHandle works on the STD_ERROR_HANDLE */
if (!CloseHandle(hFile))
{
Fail("GetStdHandle: ERROR -> CloseHandle failed. GetLastError "
"returned %u.\n",
GetLastError());
}
PAL_Terminate();
return PASS;
}
|
711361.c | int i = 0;
int r = 0;
int m;
void mult() {
r = r + m;
i++;
}
void main() {
int n = __VERIFIER_nondet_int();//n = rand(), m = rand(), r;
m = __VERIFIER_nondet_int();
__VERIFIER_assume(n > 0);
while(i < n) {
mult();
}
assert(i == n);
assert(r == n * m);
}
|
825385.c | /* LibTomCrypt, modular cryptographic library -- Tom St Denis
*
* LibTomCrypt is a library that provides various cryptographic
* algorithms in a highly modular and flexible manner.
*
* The library is free for all purposes without any express
* guarantee it works.
*/
#include "tomcrypt.h"
/**
@file dsa_verify_key.c
DSA implementation, verify a key, Tom St Denis
*/
#ifdef LTC_MDSA
/**
Validate a DSA key
Yeah, this function should've been called dsa_validate_key()
in the first place and for compat-reasons we keep it
as it was (for now).
@param key The key to validate
@param stat [out] Result of test, 1==valid, 0==invalid
@return CRYPT_OK if successful
*/
int dsa_verify_key(dsa_key *key, int *stat)
{
int err;
err = dsa_int_validate_primes(key, stat);
if (err != CRYPT_OK || *stat == 0) return err;
err = dsa_int_validate_pqg(key, stat);
if (err != CRYPT_OK || *stat == 0) return err;
return dsa_int_validate_xy(key, stat);
}
/**
Non-complex part (no primality testing) of the validation
of DSA params (p, q, g)
@param key The key to validate
@param stat [out] Result of test, 1==valid, 0==invalid
@return CRYPT_OK if successful
*/
int dsa_int_validate_pqg(dsa_key *key, int *stat)
{
void *tmp1, *tmp2;
int err;
LTC_ARGCHK(key != NULL);
LTC_ARGCHK(stat != NULL);
*stat = 0;
/* check q-order */
if ( key->qord >= LTC_MDSA_MAX_GROUP || key->qord <= 15 ||
(unsigned long)key->qord >= mp_unsigned_bin_size(key->p) ||
(mp_unsigned_bin_size(key->p) - key->qord) >= LTC_MDSA_DELTA ) {
return CRYPT_OK;
}
/* FIPS 186-4 chapter 4.1: 1 < g < p */
if (mp_cmp_d(key->g, 1) != LTC_MP_GT || mp_cmp(key->g, key->p) != LTC_MP_LT) {
return CRYPT_OK;
}
if ((err = mp_init_multi(&tmp1, &tmp2, NULL)) != CRYPT_OK) { return err; }
/* FIPS 186-4 chapter 4.1: q is a divisor of (p - 1) */
if ((err = mp_sub_d(key->p, 1, tmp1)) != CRYPT_OK) { goto error; }
if ((err = mp_div(tmp1, key->q, tmp1, tmp2)) != CRYPT_OK) { goto error; }
if (mp_iszero(tmp2) != LTC_MP_YES) {
err = CRYPT_OK;
goto error;
}
/* FIPS 186-4 chapter 4.1: g is a generator of a subgroup of order q in
* the multiplicative group of GF(p) - so we make sure that g^q mod p = 1
*/
if ((err = mp_exptmod(key->g, key->q, key->p, tmp1)) != CRYPT_OK) { goto error; }
if (mp_cmp_d(tmp1, 1) != LTC_MP_EQ) {
err = CRYPT_OK;
goto error;
}
err = CRYPT_OK;
*stat = 1;
error:
mp_clear_multi(tmp2, tmp1, NULL);
return err;
}
/**
Primality testing of DSA params p and q
@param key The key to validate
@param stat [out] Result of test, 1==valid, 0==invalid
@return CRYPT_OK if successful
*/
int dsa_int_validate_primes(dsa_key *key, int *stat)
{
int err, res;
*stat = 0;
LTC_ARGCHK(key != NULL);
LTC_ARGCHK(stat != NULL);
/* key->q prime? */
if ((err = mp_prime_is_prime(key->q, LTC_MILLER_RABIN_REPS, &res)) != CRYPT_OK) {
return err;
}
if (res == LTC_MP_NO) {
return CRYPT_OK;
}
/* key->p prime? */
if ((err = mp_prime_is_prime(key->p, LTC_MILLER_RABIN_REPS, &res)) != CRYPT_OK) {
return err;
}
if (res == LTC_MP_NO) {
return CRYPT_OK;
}
*stat = 1;
return CRYPT_OK;
}
/**
Validation of a DSA key (x and y values)
@param key The key to validate
@param stat [out] Result of test, 1==valid, 0==invalid
@return CRYPT_OK if successful
*/
int dsa_int_validate_xy(dsa_key *key, int *stat)
{
void *tmp;
int err;
*stat = 0;
LTC_ARGCHK(key != NULL);
LTC_ARGCHK(stat != NULL);
/* 1 < y < p-1 */
if ((err = mp_init(&tmp)) != CRYPT_OK) {
return err;
}
if ((err = mp_sub_d(key->p, 1, tmp)) != CRYPT_OK) {
goto error;
}
if (mp_cmp_d(key->y, 1) != LTC_MP_GT || mp_cmp(key->y, tmp) != LTC_MP_LT) {
err = CRYPT_OK;
goto error;
}
if (key->type == PK_PRIVATE) {
/* FIPS 186-4 chapter 4.1: 0 < x < q */
if (mp_cmp_d(key->x, 0) != LTC_MP_GT || mp_cmp(key->x, key->q) != LTC_MP_LT) {
err = CRYPT_OK;
goto error;
}
/* FIPS 186-4 chapter 4.1: y = g^x mod p */
if ((err = mp_exptmod(key->g, key->x, key->p, tmp)) != CRYPT_OK) {
goto error;
}
if (mp_cmp(tmp, key->y) != LTC_MP_EQ) {
err = CRYPT_OK;
goto error;
}
}
else {
/* with just a public key we cannot test y = g^x mod p therefore we
* only test that y^q mod p = 1, which makes sure y is in g^x mod p
*/
if ((err = mp_exptmod(key->y, key->q, key->p, tmp)) != CRYPT_OK) {
goto error;
}
if (mp_cmp_d(tmp, 1) != LTC_MP_EQ) {
err = CRYPT_OK;
goto error;
}
}
err = CRYPT_OK;
*stat = 1;
error:
mp_clear(tmp);
return err;
}
#endif
/* ref: HEAD -> master, tag: v1.18.0 */
/* git commit: 0676c9aec7299f5c398d96cbbb64f7e38f67d73f */
/* commit time: 2017-10-10 15:51:36 +0200 */
|
736427.c | /**
******************************************************************************
* @file TIM/TIM_DMABurst/stm32f0xx_it.c
* @author MCD Application Team
* @version V1.6.0
* @date 13-October-2021
* @brief Main Interrupt Service Routines.
* This file provides template for all exceptions handler and
* peripherals interrupt service routine.
******************************************************************************
* @attention
*
* Copyright (c) 2014 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f0xx_it.h"
/** @addtogroup STM32F0xx_StdPeriph_Examples
* @{
*/
/** @addtogroup TIM_DMA_Burst
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/******************************************************************************/
/* Cortex-M0 Processor Exceptions Handlers */
/******************************************************************************/
/**
* @brief This function handles NMI exception.
* @param None
* @retval None
*/
void NMI_Handler(void)
{
}
/**
* @brief This function handles Hard Fault exception.
* @param None
* @retval None
*/
void HardFault_Handler(void)
{
/* Go to infinite loop when Hard Fault exception occurs */
while (1)
{
}
}
/**
* @brief This function handles SVCall exception.
* @param None
* @retval None
*/
void SVC_Handler(void)
{
}
/**
* @brief This function handles PendSVC exception.
* @param None
* @retval None
*/
void PendSV_Handler(void)
{
}
/**
* @brief This function handles SysTick Handler.
* @param None
* @retval None
*/
void SysTick_Handler(void)
{
}
/******************************************************************************/
/* STM32F0xx Peripherals Interrupt Handlers */
/* Add here the Interrupt Handler for the used peripheral(s) (PPP), for the */
/* available peripheral interrupt handler's name please refer to the startup */
/* file (startup_stm32f0xx.s). */
/******************************************************************************/
/**
* @brief This function handles PPP interrupt request.
* @param None
* @retval None
*/
/*void PPP_IRQHandler(void)
{
}*/
/**
* @}
*/
/**
* @}
*/
|
576675.c | /*
* Copyright (c) 2020-2021 Thakee Nathees
* Distributed Under The MIT License
*/
#include "pk_core.h"
#include <ctype.h>
#include <limits.h>
#include <math.h>
#include <time.h>
#include "pk_debug.h"
#include "pk_utils.h"
#include "pk_var.h"
#include "pk_vm.h"
#if defined(_MSC_VER) && _MSC_VER <= 1200
#define inline __inline
#endif
// M_PI is non standard. The macro _USE_MATH_DEFINES defining before importing
// <math.h> will define the constants for MSVC. But for a portable solution,
// we're defining it ourselves if it isn't already.
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
// Returns the docstring of the function, which is a static const char* defined
// just above the function by the DEF() macro below.
#define DOCSTRING(fn) _pk_doc_##fn
// A macro to declare a function, with docstring, which is defined as
// _pk_doc_<fn> = docstring; That'll used to generate function help text.
#define DEF(fn, docstring) \
static const char* DOCSTRING(fn) = docstring; \
static void fn(PKVM* vm)
// Checks if a number is a byte
#define IS_NUM_BYTE(num) ((CHAR_MIN <= (num)) && ((num) <= CHAR_MAX))
/*****************************************************************************/
/* CORE PUBLIC API */
/*****************************************************************************/
// Create a new module with the given [name] and returns as a Script* for
// internal. Which will be wrapped by pkNewModule to return a pkHandle*.
static Script* newModuleInternal(PKVM* vm, const char* name);
// The internal function to add global value to a module.
static void moduleAddGlobalInternal(PKVM* vm, Script* script,
const char* name, Var value);
// The internal function to add functions to a module.
static void moduleAddFunctionInternal(PKVM* vm, Script* script,
const char* name, pkNativeFn fptr,
int arity, const char* docstring);
// pkNewModule implementation (see pocketlang.h for description).
PkHandle* pkNewModule(PKVM* vm, const char* name) {
Script* module = newModuleInternal(vm, name);
return vmNewHandle(vm, VAR_OBJ(module));
}
// pkModuleAddGlobal implementation (see pocketlang.h for description).
PK_PUBLIC void pkModuleAddGlobal(PKVM* vm, PkHandle* module,
const char* name, PkHandle* value) {
Var scr;
__ASSERT(module != NULL, "Argument module was NULL.");
__ASSERT(value != NULL, "Argument value was NULL.");
scr = module->value;
__ASSERT(IS_OBJ_TYPE(scr, OBJ_SCRIPT), "Given handle is not a module");
moduleAddGlobalInternal(vm, (Script*)AS_OBJ(scr), name, value->value);
}
// pkModuleAddFunction implementation (see pocketlang.h for description).
void pkModuleAddFunction(PKVM* vm, PkHandle* module, const char* name,
pkNativeFn fptr, int arity) {
Var scr;
__ASSERT(module != NULL, "Argument module was NULL.");
scr = module->value;
__ASSERT(IS_OBJ_TYPE(scr, OBJ_SCRIPT), "Given handle is not a module");
moduleAddFunctionInternal(vm, (Script*)AS_OBJ(scr), name, fptr, arity,
NULL /*TODO: Public API for function docstring.*/);
}
PkHandle* pkGetFunction(PKVM* vm, PkHandle* module,
const char* name) {
Var scr;
Script* script;
uint32_t i;
__ASSERT(module != NULL, "Argument module was NULL.");
scr = module->value;
__ASSERT(IS_OBJ_TYPE(scr, OBJ_SCRIPT), "Given handle is not a module");
script = (Script*)AS_OBJ(scr);
for (i = 0; i < script->functions.count; i++) {
const char* fn_name = script->functions.data[i]->name;
if (strcmp(name, fn_name) == 0) {
return vmNewHandle(vm, VAR_OBJ(script->functions.data[i]));
}
}
return NULL;
}
// A convenient macro to get the nth (1 based) argument of the current
// function.
#define ARG(n) (vm->fiber->ret[n])
// Evaluates to the current function's argument count.
#define ARGC ((int)(vm->fiber->sp - vm->fiber->ret) - 1)
// Set return value for the current native function and return.
#define RET(value) \
do { \
*(vm->fiber->ret) = value; \
return; \
} while (false)
#define RET_ERR(err) \
do { \
VM_SET_ERROR(vm, err); \
RET(VAR_NULL); \
} while(false)
// Check for errors in before calling the get arg public api function.
#define CHECK_GET_ARG_API_ERRORS() \
do { \
__ASSERT(vm->fiber != NULL, \
"This function can only be called at runtime."); \
__ASSERT(arg > 0 || arg <= ARGC, "Invalid argument index."); \
__ASSERT(value != NULL, "Argument [value] was NULL."); \
} while (false)
// Set error for incompatible type provided as an argument. (TODO: got type).
#define ERR_INVALID_ARG_TYPE(m_type) \
do { \
char buff[STR_INT_BUFF_SIZE]; \
sprintf(buff, "%d", arg); \
VM_SET_ERROR(vm, stringFormat(vm, "Expected a '$' at argument $.", \
m_type, buff)); \
} while (false)
// pkGetArgc implementation (see pocketlang.h for description).
int pkGetArgc(const PKVM* vm) {
__ASSERT(vm->fiber != NULL, "This function can only be called at runtime.");
return ARGC;
}
// pkGetArg implementation (see pocketlang.h for description).
PkVar pkGetArg(const PKVM* vm, int arg) {
__ASSERT(vm->fiber != NULL, "This function can only be called at runtime.");
__ASSERT(arg > 0 || arg <= ARGC, "Invalid argument index.");
return &(ARG(arg));
}
// pkGetArgBool implementation (see pocketlang.h for description).
bool pkGetArgBool(PKVM* vm, int arg, bool* value) {
Var val;
CHECK_GET_ARG_API_ERRORS();
val = ARG(arg);
*value = toBool(val);
return true;
}
// pkGetArgNumber implementation (see pocketlang.h for description).
bool pkGetArgNumber(PKVM* vm, int arg, double* value) {
Var val;
CHECK_GET_ARG_API_ERRORS();
val = ARG(arg);
if (IS_NUM(val)) {
*value = AS_NUM(val);
} else if (IS_BOOL(val)) {
*value = AS_BOOL(val) ? 1 : 0;
} else {
ERR_INVALID_ARG_TYPE("number");
return false;
}
return true;
}
// pkGetArgString implementation (see pocketlang.h for description).
bool pkGetArgString(PKVM* vm, int arg, const char** value, uint32_t* length) {
Var val;
CHECK_GET_ARG_API_ERRORS();
val = ARG(arg);
if (IS_OBJ_TYPE(val, OBJ_STRING)) {
String* str = (String*)AS_OBJ(val);
*value = str->data;
if (length) *length = str->length;
} else {
ERR_INVALID_ARG_TYPE("string");
return false;
}
return true;
}
// pkGetArgInstance implementation (see pocketlang.h for description).
bool pkGetArgInst(PKVM* vm, int arg, uint32_t id, void** value) {
Var val;
bool is_native_instance;
CHECK_GET_ARG_API_ERRORS();
val = ARG(arg);
is_native_instance = false;
if (IS_OBJ_TYPE(val, OBJ_INST)) {
Instance* inst = ((Instance*)AS_OBJ(val));
if (inst->is_native && inst->native_id == id) {
*value = inst->native;
is_native_instance = true;
}
}
if (!is_native_instance) {
const char* ty_name = "$(?)";
if (vm->config.inst_name_fn != NULL) {
ty_name = vm->config.inst_name_fn(id);
}
ERR_INVALID_ARG_TYPE(ty_name);
return false;
}
return true;
}
// pkGetArgValue implementation (see pocketlang.h for description).
bool pkGetArgValue(PKVM* vm, int arg, PkVarType type, PkVar* value) {
Var val;
CHECK_GET_ARG_API_ERRORS();
val = ARG(arg);
if (pkGetValueType((PkVar)&val) != type) {
char buff[STR_INT_BUFF_SIZE]; sprintf(buff, "%d", arg);
VM_SET_ERROR(vm, stringFormat(vm, "Expected a $ at argument $.",
getPkVarTypeName(type), buff));
return false;
}
*value = (PkVar)&val;
return true;
}
// pkReturnNull implementation (see pocketlang.h for description).
void pkReturnNull(PKVM* vm) {
RET(VAR_NULL);
}
// pkReturnBool implementation (see pocketlang.h for description).
void pkReturnBool(PKVM* vm, bool value) {
RET(VAR_BOOL(value));
}
// pkReturnNumber implementation (see pocketlang.h for description).
void pkReturnNumber(PKVM* vm, double value) {
RET(VAR_NUM(value));
}
// pkReturnString implementation (see pocketlang.h for description).
void pkReturnString(PKVM* vm, const char* value) {
RET(VAR_OBJ(newString(vm, value)));
}
// pkReturnStringLength implementation (see pocketlang.h for description).
void pkReturnStringLength(PKVM* vm, const char* value, size_t length) {
RET(VAR_OBJ(newStringLength(vm, value, (uint32_t)length)));
}
// pkReturnValue implementation (see pocketlang.h for description).
void pkReturnValue(PKVM* vm, PkVar value) {
RET(*(Var*)value);
}
// pkReturnHandle implementation (see pocketlang.h for description).
void pkReturnHandle(PKVM* vm, PkHandle* handle) {
RET(handle->value);
}
// pkReturnInstNative implementation (see pocketlang.h for description).
void pkReturnInstNative(PKVM* vm, void* data, uint32_t id) {
RET(VAR_OBJ(newInstanceNative(vm, data, id)));
}
const char* pkStringGetData(const PkVar value) {
const Var str = (*(const Var*)value);
__ASSERT(IS_OBJ_TYPE(str, OBJ_STRING), "Value should be of type string.");
return ((String*)AS_OBJ(str))->data;
}
PkVar pkFiberGetReturnValue(const PkHandle* fiber) {
Var fb;
Fiber* _fiber;
__ASSERT(fiber != NULL, "Handle fiber was NULL.");
fb = fiber->value;
__ASSERT(IS_OBJ_TYPE(fb, OBJ_FIBER), "Given handle is not a fiber");
_fiber = (Fiber*)AS_OBJ(fb);
return (PkVar)_fiber->ret;
}
bool pkFiberIsDone(const PkHandle* fiber) {
Var fb;
Fiber* _fiber;
__ASSERT(fiber != NULL, "Handle fiber was NULL.");
fb = fiber->value;
__ASSERT(IS_OBJ_TYPE(fb, OBJ_FIBER), "Given handle is not a fiber");
_fiber = (Fiber*)AS_OBJ(fb);
return _fiber->state == FIBER_DONE;
}
/*****************************************************************************/
/* VALIDATORS */
/*****************************************************************************/
// Check if [var] is a numeric value (bool/number) and set [value].
static inline bool isNumeric(Var var, double* value) {
if (IS_NUM(var)) {
*value = AS_NUM(var);
return true;
}
if (IS_BOOL(var)) {
*value = AS_BOOL(var);
return true;
}
return false;
}
// Check if [var] is a numeric value (bool/number) and set [value].
static inline bool isInteger(Var var, int64_t* value) {
double number;
if (isNumeric(var, &number)) {
// TODO: check if the number is larger for a 64 bit integer.
if (floor(number) == number) {
ASSERT(INT64_MIN <= number && number <= INT64_MAX,
"TODO: Large numbers haven't handled yet. Please report!");
*value = (int64_t)(number);
return true;
}
}
return false;
}
// Check if [var] is bool/number. If not set error and return false.
static inline bool validateNumeric(PKVM* vm, Var var, double* value,
const char* name) {
if (isNumeric(var, value)) return true;
VM_SET_ERROR(vm, stringFormat(vm, "$ must be a numeric value.", name));
return false;
}
// Check if [var] is 32 bit integer. If not set error and return false.
static inline bool validateInteger(PKVM* vm, Var var, int64_t* value,
const char* name) {
if (isInteger(var, value)) return true;
VM_SET_ERROR(vm, stringFormat(vm, "$ must be a whole number.", name));
return false;
}
// Index is could be larger than 32 bit integer, but the size in pocketlang
// limited to 32 unsigned bit integer
static inline bool validateIndex(PKVM* vm, int64_t index, uint32_t size,
const char* container) {
if (index < 0 || size <= index) {
VM_SET_ERROR(vm, stringFormat(vm, "$ index out of bound.", container));
return false;
}
return true;
}
// Check if [var] is string for argument at [arg]. If not set error and
// return false.
#define VALIDATE_ARG_OBJ(m_class, m_type, m_name) \
static bool validateArg##m_class(PKVM* vm, int arg, m_class** value) { \
Var var = ARG(arg); \
ASSERT(arg > 0 && arg <= ARGC, OOPS); \
if (!IS_OBJ(var) || AS_OBJ(var)->type != m_type) { \
char buff[12]; sprintf(buff, "%d", arg); \
VM_SET_ERROR(vm, stringFormat(vm, "Expected a " m_name \
" at argument $.", buff, false)); \
} \
*value = (m_class*)AS_OBJ(var); \
return true; \
}
VALIDATE_ARG_OBJ(String, OBJ_STRING, "string")
VALIDATE_ARG_OBJ(List, OBJ_LIST, "list")
VALIDATE_ARG_OBJ(Map, OBJ_MAP, "map")
VALIDATE_ARG_OBJ(Function, OBJ_FUNC, "function")
VALIDATE_ARG_OBJ(Fiber, OBJ_FIBER, "fiber")
/*****************************************************************************/
/* SHARED FUNCTIONS */
/*****************************************************************************/
// findBuiltinFunction implementation (see core.h for description).
int findBuiltinFunction(const PKVM* vm, const char* name, uint32_t length) {
uint32_t i;
for (i = 0; i < vm->builtins_count; i++) {
if (length == vm->builtins[i].length &&
strncmp(name, vm->builtins[i].name, length) == 0) {
return i;
}
}
return -1;
}
// getBuiltinFunction implementation (see core.h for description).
Function* getBuiltinFunction(const PKVM* vm, int index) {
ASSERT_INDEX((uint32_t)index, vm->builtins_count);
return vm->builtins[index].fn;
}
// getBuiltinFunctionName implementation (see core.h for description).
const char* getBuiltinFunctionName(const PKVM* vm, int index) {
ASSERT_INDEX((uint32_t)index, vm->builtins_count);
return vm->builtins[index].name;
}
// getCoreLib implementation (see core.h for description).
Script* getCoreLib(const PKVM* vm, String* name) {
Var lib = mapGet(vm->core_libs, VAR_OBJ(name));
if (IS_UNDEF(lib)) return NULL;
ASSERT(IS_OBJ_TYPE(lib, OBJ_SCRIPT), OOPS);
return (Script*)AS_OBJ(lib);
}
/*****************************************************************************/
/* CORE BUILTIN FUNCTIONS */
/*****************************************************************************/
DEF(coreTypeName,
"type_name(value:var) -> string\n"
"Returns the type name of the of the value.") {
RET(VAR_OBJ(newString(vm, varTypeName(ARG(1)))));
}
DEF(coreHelp,
"help([fn]) -> null\n"
"This will write an error message to stdout and return null.") {
int argc = ARGC;
if (argc != 0 && argc != 1) {
RET_ERR(newString(vm, "Invalid argument count."));
}
if (argc == 0) {
// If there ins't an io function callback, we're done.
if (vm->config.write_fn == NULL) RET(VAR_NULL);
vm->config.write_fn(vm, "TODO: print help here\n");
} else if (argc == 1) {
Function* fn;
if (!validateArgFunction(vm, 1, &fn)) return;
// If there ins't an io function callback, we're done.
if (vm->config.write_fn == NULL) RET(VAR_NULL);
if (fn->docstring != NULL) {
vm->config.write_fn(vm, fn->docstring);
vm->config.write_fn(vm, "\n\n");
} else {
// TODO: A better message.
vm->config.write_fn(vm, "function '");
vm->config.write_fn(vm, fn->name);
vm->config.write_fn(vm, "()' doesn't have a docstring.\n");
}
}
}
DEF(coreAssert,
"assert(condition:bool [, msg:string]) -> void\n"
"If the condition is false it'll terminate the current fiber with the "
"optional error message") {
int argc = ARGC;
if (argc != 1 && argc != 2) {
RET_ERR(newString(vm, "Invalid argument count."));
}
if (!toBool(ARG(1))) {
String* msg = NULL;
if (argc == 2) {
if (AS_OBJ(ARG(2))->type != OBJ_STRING) {
msg = toString(vm, ARG(2));
} else {
msg = (String*)AS_OBJ(ARG(2));
}
vmPushTempRef(vm, &msg->_super);
VM_SET_ERROR(vm, stringFormat(vm, "Assertion failed: '@'.", msg));
vmPopTempRef(vm);
} else {
VM_SET_ERROR(vm, newString(vm, "Assertion failed."));
}
}
}
DEF(coreBin,
"bin(value:num) -> string\n"
"Returns as a binary value string with '0x' prefix.") {
char buff[STR_BIN_BUFF_SIZE];
int64_t value;
bool negative;
char* ptr;
uint32_t length;
if (!validateInteger(vm, ARG(1), &value, "Argument 1")) return;
negative = (value < 0) ? true : false;
if (negative) value = -value;
ptr = buff + STR_BIN_BUFF_SIZE - 1;
*ptr-- = '\0'; // NULL byte at the end of the string.
if (value != 0) {
while (value > 0) {
*ptr-- = (char)('0' + (value & 1));
value >>= 1;
}
} else {
*ptr-- = '0';
}
*ptr-- = 'b'; *ptr-- = '0';
if (negative) *ptr-- = '-';
length = (uint32_t)((buff + STR_BIN_BUFF_SIZE - 1) - (ptr + 1));
RET(VAR_OBJ(newStringLength(vm, ptr + 1, length)));
}
DEF(coreHex,
"hex(value:num) -> string\n"
"Returns as a hexadecimal value string with '0x' prefix.") {
char buff[STR_HEX_BUFF_SIZE];
int64_t value;
char* ptr;
uint32_t _x;
int length;
if (!validateInteger(vm, ARG(1), &value, "Argument 1")) return;
ptr = buff;
if (value < 0) *ptr++ = '-';
*ptr++ = '0'; *ptr++ = 'x';
if (value > UINT32_MAX || value < -(int64_t)(UINT32_MAX)) {
VM_SET_ERROR(vm, newString(vm, "Integer is too large."));
RET(VAR_NULL);
}
// TODO: spritnf limits only to 8 character hex value, we need to do it
// outself for a maximum of 16 character long (see bin() for reference).
_x = (uint32_t)((value < 0) ? -value : value);
length = sprintf(ptr, "%x", _x);
RET(VAR_OBJ(newStringLength(vm, buff,
(uint32_t)((ptr + length) - (char*)(buff)))));
}
DEF(coreYield,
"yield([value]) -> var\n"
"Return the current function with the yield [value] to current running "
"fiber. If the fiber is resumed, it'll run from the next statement of the "
"yield() call. If the fiber resumed with with a value, the return value of "
"the yield() would be that value otherwise null.") {
int argc = ARGC;
if (argc > 1) { // yield() or yield(val).
RET_ERR(newString(vm, "Invalid argument count."));
}
vmYieldFiber(vm, (argc == 1) ? &ARG(1) : NULL);
}
DEF(coreToString,
"to_string(value:var) -> string\n"
"Returns the string representation of the value.") {
RET(VAR_OBJ(toString(vm, ARG(1))));
}
DEF(corePrint,
"print(...) -> void\n"
"Write each argument as space seperated, to the stdout and ends with a "
"newline.") {
int i;
// If the host application doesn't provide any write function, discard the
// output.
if (vm->config.write_fn == NULL) return;
for (i = 1; i <= ARGC; i++) {
if (i != 1) vm->config.write_fn(vm, " ");
vm->config.write_fn(vm, toString(vm, ARG(i))->data);
}
vm->config.write_fn(vm, "\n");
}
DEF(coreInput,
"input([msg:var]) -> string\n"
"Read a line from stdin and returns it without the line ending. Accepting "
"an optional argument [msg] and prints it before reading.") {
PkStringPtr result;
String* line;
int argc = ARGC;
if (argc != 1 && argc != 2) {
RET_ERR(newString(vm, "Invalid argument count."));
}
// If the host application doesn't provide any write function, return.
if (vm->config.read_fn == NULL) return;
if (argc == 1) {
vm->config.write_fn(vm, toString(vm, ARG(1))->data);
}
result = vm->config.read_fn(vm);
line = newString(vm, result.string);
if (result.on_done) result.on_done(vm, &result);
RET(VAR_OBJ(line));
}
// String functions.
// -----------------
// TODO: substring.
DEF(coreStrChr,
"str_chr(value:number) -> string\n"
"Returns the ASCII string value of the integer argument.") {
int64_t num;
char c;
if (!validateInteger(vm, ARG(1), &num, "Argument 1")) return;
if (!IS_NUM_BYTE(num)) {
RET_ERR(newString(vm, "The number is not in a byte range."));
}
c = (char)num;
RET(VAR_OBJ(newStringLength(vm, &c, 1)));
}
DEF(coreStrOrd,
"str_ord(value:string) -> number\n"
"Returns integer value of the given ASCII character.") {
String* c;
if (!validateArgString(vm, 1, &c)) return;
if (c->length != 1) {
RET_ERR(newString(vm, "Expected a string of length 1."));
} else {
RET(VAR_NUM((double)c->data[0]));
}
}
// List functions.
// ---------------
DEF(coreListAppend,
"list_append(self:List, value:var) -> List\n"
"Append the [value] to the list [self] and return the list.") {
List* list;
Var elem;
if (!validateArgList(vm, 1, &list)) return;
elem = ARG(2);
listAppend(vm, list, elem);
RET(VAR_OBJ(list));
}
// Map functions.
// --------------
DEF(coreMapRemove,
"map_remove(self:map, key:var) -> var\n"
"Remove the [key] from the map [self] and return it's value if the key "
"exists, otherwise it'll return null.") {
Map* map;
Var key;
if (!validateArgMap(vm, 1, &map)) return;
key = ARG(2);
RET(mapRemoveKey(vm, map, key));
}
/*****************************************************************************/
/* CORE MODULE METHODS */
/*****************************************************************************/
// Create a module and add it to the vm's core modules, returns the script.
static Script* newModuleInternal(PKVM* vm, const char* name) {
Script* scr;
// Create a new Script for the module.
String* _name = newString(vm, name);
vmPushTempRef(vm, &_name->_super);
// Check if any module with the same name already exists and assert to the
// hosting application.
if (!IS_UNDEF(mapGet(vm->core_libs, VAR_OBJ(_name)))) {
vmPopTempRef(vm); // _name
__ASSERT(false, stringFormat(vm,
"A module named '$' already exists", name)->data);
}
scr = newScript(vm, _name);
scr->module = _name;
vmPopTempRef(vm); // _name
// Add the script to core_libs.
vmPushTempRef(vm, &scr->_super);
mapSet(vm, vm->core_libs, VAR_OBJ(_name), VAR_OBJ(scr));
vmPopTempRef(vm);
return scr;
}
// This will fail an assertion if a function or a global with the [name]
// already exists in the module.
static inline void assertModuleNameDef(PKVM* vm, Script* script,
const char* name) {
// Check if function with the same name already exists.
if (scriptGetFunc(script, name, (uint32_t)strlen(name)) != -1) {
__ASSERT(false, stringFormat(vm, "A function named '$' already esists "
"on module '@'", name, script->module)->data);
}
// Check if a global variable with the same name already exists.
if (scriptGetGlobals(script, name, (uint32_t)strlen(name)) != -1) {
__ASSERT(false, stringFormat(vm, "A global variable named '$' already "
"esists on module '@'", name, script->module)->data);
}
}
// The internal function to add global value to a module.
static void moduleAddGlobalInternal(PKVM* vm, Script* script,
const char* name, Var value) {
// Ensure the name isn't defined already.
assertModuleNameDef(vm, script, name);
// Add the value to the globals buffer.
scriptAddGlobal(vm, script, name, (uint32_t)strlen(name), value);
}
// An internal function to add a function to the given [script].
static void moduleAddFunctionInternal(PKVM* vm, Script* script,
const char* name, pkNativeFn fptr,
int arity, const char* docstring) {
Function* fn;
// Ensure the name isn't predefined.
assertModuleNameDef(vm, script, name);
fn = newFunction(vm, name, (int)strlen(name),
script, true, docstring);
fn->native = fptr;
fn->arity = arity;
}
// TODO: make the below module functions as PK_DOC(name, doc);
// 'lang' library methods.
// -----------------------
DEF(stdLangClock,
"clock() -> num\n"
"Returns the number of seconds since the application started") {
RET(VAR_NUM((double)clock() / CLOCKS_PER_SEC));
}
DEF(stdLangGC,
"gc() -> num\n"
"Trigger garbage collection and return the amount of bytes cleaned.") {
size_t garbage;
size_t bytes_before = vm->bytes_allocated;
vmCollectGarbage(vm);
garbage = bytes_before - vm->bytes_allocated;
RET(VAR_NUM((double)garbage));
}
DEF(stdLangDisas,
"disas(fn:Function) -> String\n"
"Returns the disassembled opcode of the function [fn].") {
String* dump;
pkByteBuffer buff;
Function* fn;
if (!validateArgFunction(vm, 1, &fn)) return;
pkByteBufferInit(&buff);
dumpFunctionCode(vm, fn, &buff);
dump = newString(vm, (const char*)buff.data);
pkByteBufferClear(&buff, vm);
RET(VAR_OBJ(dump));
}
#ifdef DEBUG
DEF(stdLangDebugBreak,
"debug_break() -> null\n"
"A debug function for development (will be removed).") {
DEBUG_BREAK();
}
#endif
DEF(stdLangWrite,
"write(...) -> null\n"
"Write function, just like print function but it wont put space between"
"args and write a new line at the end.") {
int i;
String* str; //< Will be cleaned by garbage collector;
// If the host application doesn't provide any write function, discard the
// output.
if (vm->config.write_fn == NULL) return;
for (i = 1; i <= ARGC; i++) {
Var arg = ARG(i);
// If it's already a string don't allocate a new string instead use it.
if (IS_OBJ_TYPE(arg, OBJ_STRING)) {
str = (String*)AS_OBJ(arg);
} else {
str = toString(vm, arg);
}
vm->config.write_fn(vm, str->data);
}
}
// 'math' library methods.
// -----------------------
DEF(stdMathFloor,
"floor(value:num) -> num\n") {
double num;
if (!validateNumeric(vm, ARG(1), &num, "Argument 1")) return;
RET(VAR_NUM(floor(num)));
}
DEF(stdMathCeil,
"ceil(value:num) -> num\n") {
double num;
if (!validateNumeric(vm, ARG(1), &num, "Argument 1")) return;
RET(VAR_NUM(ceil(num)));
}
DEF(stdMathPow,
"pow(value:num) -> num\n") {
double num, ex;
if (!validateNumeric(vm, ARG(1), &num, "Argument 1")) return;
if (!validateNumeric(vm, ARG(2), &ex, "Argument 2")) return;
RET(VAR_NUM(pow(num, ex)));
}
DEF(stdMathSqrt,
"sqrt(value:num) -> num\n") {
double num;
if (!validateNumeric(vm, ARG(1), &num, "Argument 1")) return;
RET(VAR_NUM(sqrt(num)));
}
DEF(stdMathAbs,
"abs(value:num) -> num\n") {
double num;
if (!validateNumeric(vm, ARG(1), &num, "Argument 1")) return;
if (num < 0) num = -num;
RET(VAR_NUM(num));
}
DEF(stdMathSign,
"sign(value:num) -> num\n") {
double num;
if (!validateNumeric(vm, ARG(1), &num, "Argument 1")) return;
if (num < 0) num = -1;
else if (num > 0) num = +1;
else num = 0;
RET(VAR_NUM(num));
}
DEF(stdMathHash,
"hash(value:var) -> num\n"
"Return the hash value of the variable, if it's not hashable it'll "
"return null.") {
if (IS_OBJ(ARG(1))) {
if (!isObjectHashable(AS_OBJ(ARG(1))->type)) {
RET(VAR_NULL);
}
}
RET(VAR_NUM((double)varHashValue(ARG(1))));
}
DEF(stdMathSine,
"sin(rad:num) -> num\n"
"Return the sine value of the argument [rad] which is an angle expressed "
"in radians.") {
double rad;
if (!validateNumeric(vm, ARG(1), &rad, "Argument 1")) return;
RET(VAR_NUM(sin(rad)));
}
DEF(stdMathCosine,
"cos(rad:num) -> num\n"
"Return the cosine value of the argument [rad] which is an angle expressed "
"in radians.") {
double rad;
if (!validateNumeric(vm, ARG(1), &rad, "Argument 1")) return;
RET(VAR_NUM(cos(rad)));
}
DEF(stdMathTangent,
"tan(rad:num) -> num\n"
"Return the tangent value of the argument [rad] which is an angle expressed "
"in radians.") {
double rad;
if (!validateNumeric(vm, ARG(1), &rad, "Argument 1")) return;
RET(VAR_NUM(tan(rad)));
}
// 'Fiber' module methods.
// -----------------------
DEF(stdFiberNew,
"new(fn:Function) -> fiber\n"
"Create and return a new fiber from the given function [fn].") {
Function* fn;
if (!validateArgFunction(vm, 1, &fn)) return;
RET(VAR_OBJ(newFiber(vm, fn)));
}
DEF(stdFiberRun,
"run(fb:Fiber, ...) -> var\n"
"Runs the fiber's function with the provided arguments and returns it's "
"return value or the yielded value if it's yielded.") {
// Buffer of argument to call vmPrepareFiber().
Var* args[MAX_ARGC];
Fiber* fb;
int i;
int argc = ARGC;
if (argc == 0) // Missing the fiber argument.
RET_ERR(newString(vm, "Missing argument - fiber."));
if (!validateArgFiber(vm, 1, &fb)) return;
// ARG(1) is fiber, function arguments are ARG(2), ARG(3), ... ARG(argc).
for (i = 1; i < argc; i++) {
args[i - 1] = &ARG(i + 1);
}
// Switch fiber and start execution.
if (vmPrepareFiber(vm, fb, argc - 1, args)) {
ASSERT(fb == vm->fiber, OOPS);
fb->state = FIBER_RUNNING;
}
}
DEF(stdFiberResume,
"fiber_resume(fb:Fiber) -> var\n"
"Resumes a yielded function from a previous call of fiber_run() function. "
"Return it's return value or the yielded value if it's yielded.") {
Var value;
Fiber* fb;
int argc = ARGC;
if (argc == 0) // Missing the fiber argument.
RET_ERR(newString(vm, "Expected at least 1 argument(s)."));
if (argc > 2) // Can only accept 1 argument for resume.
RET_ERR(newString(vm, "Expected at most 2 argument(s)."));
if (!validateArgFiber(vm, 1, &fb)) return;
value = (argc == 1) ? VAR_NULL : ARG(2);
// Switch fiber and resume execution.
if (vmSwitchFiber(vm, fb, &value)) {
ASSERT(fb == vm->fiber, OOPS);
fb->state = FIBER_RUNNING;
}
}
/*****************************************************************************/
/* CORE INITIALIZATION */
/*****************************************************************************/
static void initializeBuiltinFN(PKVM* vm, BuiltinFn* bfn, const char* name,
int length, int arity, pkNativeFn ptr,
const char* docstring) {
bfn->name = name;
bfn->length = length;
bfn->fn = newFunction(vm, name, length, NULL, true, docstring);
bfn->fn->arity = arity;
bfn->fn->native = ptr;
}
void initializeCore(PKVM* vm) {
#define INITIALIZE_BUILTIN_FN(name, fn, argc) \
initializeBuiltinFN(vm, &vm->builtins[vm->builtins_count++], name, \
(int)strlen(name), argc, fn, DOCSTRING(fn));
#define MODULE_ADD_FN(module, name, fn, argc) \
moduleAddFunctionInternal(vm, module, name, fn, argc, DOCSTRING(fn))
// Initialize builtin functions.
INITIALIZE_BUILTIN_FN("type_name", coreTypeName, 1);
// TODO: Add is keyword with modules for builtin types.
// ex: val is Num; val is null; val is List; val is Range
// List.append(l, e) # List is implicitly imported core module.
// String.lower(s)
INITIALIZE_BUILTIN_FN("help", coreHelp, -1);
INITIALIZE_BUILTIN_FN("assert", coreAssert, -1);
INITIALIZE_BUILTIN_FN("bin", coreBin, 1);
INITIALIZE_BUILTIN_FN("hex", coreHex, 1);
INITIALIZE_BUILTIN_FN("yield", coreYield, -1);
INITIALIZE_BUILTIN_FN("to_string", coreToString, 1);
INITIALIZE_BUILTIN_FN("print", corePrint, -1);
INITIALIZE_BUILTIN_FN("input", coreInput, -1);
// String functions.
INITIALIZE_BUILTIN_FN("str_chr", coreStrChr, 1);
INITIALIZE_BUILTIN_FN("str_ord", coreStrOrd, 1);
// List functions.
INITIALIZE_BUILTIN_FN("list_append", coreListAppend, 2);
// Map functions.
INITIALIZE_BUILTIN_FN("map_remove", coreMapRemove, 2);
// Core Modules /////////////////////////////////////////////////////////////
{
Script* lang = newModuleInternal(vm, "lang");
MODULE_ADD_FN(lang, "clock", stdLangClock, 0);
MODULE_ADD_FN(lang, "gc", stdLangGC, 0);
MODULE_ADD_FN(lang, "disas", stdLangDisas, 1);
MODULE_ADD_FN(lang, "write", stdLangWrite, -1);
#ifdef DEBUG
MODULE_ADD_FN(lang, "debug_break", stdLangDebugBreak, 0);
#endif
}
{
Script* math = newModuleInternal(vm, "math");
MODULE_ADD_FN(math, "floor", stdMathFloor, 1);
MODULE_ADD_FN(math, "ceil", stdMathCeil, 1);
MODULE_ADD_FN(math, "pow", stdMathPow, 2);
MODULE_ADD_FN(math, "sqrt", stdMathSqrt, 1);
MODULE_ADD_FN(math, "abs", stdMathAbs, 1);
MODULE_ADD_FN(math, "sign", stdMathSign, 1);
MODULE_ADD_FN(math, "hash", stdMathHash, 1);
MODULE_ADD_FN(math, "sin", stdMathSine, 1);
MODULE_ADD_FN(math, "cos", stdMathCosine, 1);
MODULE_ADD_FN(math, "tan", stdMathTangent, 1);
// TODO: low priority - sinh, cosh, tanh, asin, acos, atan.
// Note that currently it's mutable (since it's a global variable, not
// constant and pocketlang doesn't support constant) so the user shouldn't
// modify the PI, like in python.
// TODO: at varSetAttrib() we can detect if the user try to change an
// attribute of a core module and we can throw an error.
moduleAddGlobalInternal(vm, math, "PI", VAR_NUM(M_PI));
}
{
Script* fiber = newModuleInternal(vm, "Fiber");
MODULE_ADD_FN(fiber, "new", stdFiberNew, 1);
MODULE_ADD_FN(fiber, "run", stdFiberRun, -1);
MODULE_ADD_FN(fiber, "resume", stdFiberResume, -1);
}
}
/*****************************************************************************/
/* OPERATORS */
/*****************************************************************************/
#define UNSUPPORTED_OPERAND_TYPES(op) \
VM_SET_ERROR(vm, stringFormat(vm, "Unsupported operand types for " \
"operator '" op "' $ and $", varTypeName(v1), varTypeName(v2)))
#define RIGHT_OPERAND "Right operand"
Var varAdd(PKVM* vm, Var v1, Var v2) {
double d1, d2;
if (isNumeric(v1, &d1)) {
if (validateNumeric(vm, v2, &d2, RIGHT_OPERAND)) {
return VAR_NUM(d1 + d2);
}
return VAR_NULL;
}
if (IS_OBJ(v1) && IS_OBJ(v2)) {
Object *o1 = AS_OBJ(v1), *o2 = AS_OBJ(v2);
switch (o1->type) {
case OBJ_STRING:
{
if (o2->type == OBJ_STRING) {
return VAR_OBJ(stringJoin(vm, (String*)o1, (String*)o2));
}
} break;
case OBJ_LIST:
{
if (o2->type == OBJ_LIST) {
return VAR_OBJ(listJoin(vm, (List*)o1, (List*)o2));
}
} break;
case OBJ_MAP:
case OBJ_RANGE:
case OBJ_SCRIPT:
case OBJ_FUNC:
case OBJ_FIBER:
case OBJ_CLASS:
case OBJ_INST:
break;
}
}
UNSUPPORTED_OPERAND_TYPES("+");
return VAR_NULL;
}
Var varSubtract(PKVM* vm, Var v1, Var v2) {
double d1, d2;
if (isNumeric(v1, &d1)) {
if (validateNumeric(vm, v2, &d2, RIGHT_OPERAND)) {
return VAR_NUM(d1 - d2);
}
return VAR_NULL;
}
UNSUPPORTED_OPERAND_TYPES("-");
return VAR_NULL;
}
Var varMultiply(PKVM* vm, Var v1, Var v2) {
double d1, d2;
if (isNumeric(v1, &d1)) {
if (validateNumeric(vm, v2, &d2, RIGHT_OPERAND)) {
return VAR_NUM(d1 * d2);
}
return VAR_NULL;
}
UNSUPPORTED_OPERAND_TYPES("*");
return VAR_NULL;
}
Var varDivide(PKVM* vm, Var v1, Var v2) {
double d1, d2;
if (isNumeric(v1, &d1)) {
if (validateNumeric(vm, v2, &d2, RIGHT_OPERAND)) {
return VAR_NUM(d1 / d2);
}
return VAR_NULL;
}
UNSUPPORTED_OPERAND_TYPES("/");
return VAR_NULL;
}
Var varModulo(PKVM* vm, Var v1, Var v2) {
double d1, d2;
if (isNumeric(v1, &d1)) {
if (validateNumeric(vm, v2, &d2, RIGHT_OPERAND)) {
return VAR_NUM(fmod(d1, d2));
}
return VAR_NULL;
}
if (IS_OBJ_TYPE(v1, OBJ_STRING)) {
//const String* str = (const String*)AS_OBJ(v1);
TODO; // "fmt" % v2.
}
UNSUPPORTED_OPERAND_TYPES("%");
return VAR_NULL;
}
Var varBitAnd(PKVM* vm, Var v1, Var v2) {
int64_t i1, i2;
if (isInteger(v1, &i1)) {
if (validateInteger(vm, v2, &i2, RIGHT_OPERAND)) {
return VAR_NUM((double)(i1 & i2));
}
return VAR_NULL;
}
UNSUPPORTED_OPERAND_TYPES("&");
return VAR_NULL;
}
Var varBitOr(PKVM* vm, Var v1, Var v2) {
int64_t i1, i2;
if (isInteger(v1, &i1)) {
if (validateInteger(vm, v2, &i2, RIGHT_OPERAND)) {
return VAR_NUM((double)(i1 | i2));
}
return VAR_NULL;
}
UNSUPPORTED_OPERAND_TYPES("|");
return VAR_NULL;
}
Var varBitXor(PKVM* vm, Var v1, Var v2) {
int64_t i1, i2;
if (isInteger(v1, &i1)) {
if (validateInteger(vm, v2, &i2, RIGHT_OPERAND)) {
return VAR_NUM((double)(i1 ^ i2));
}
return VAR_NULL;
}
UNSUPPORTED_OPERAND_TYPES("^");
return VAR_NULL;
}
Var varBitLshift(PKVM* vm, Var v1, Var v2) {
int64_t i1, i2;
if (isInteger(v1, &i1)) {
if (validateInteger(vm, v2, &i2, RIGHT_OPERAND)) {
return VAR_NUM((double)(i1 << i2));
}
return VAR_NULL;
}
UNSUPPORTED_OPERAND_TYPES("<<");
return VAR_NULL;
}
Var varBitRshift(PKVM* vm, Var v1, Var v2) {
int64_t i1, i2;
if (isInteger(v1, &i1)) {
if (validateInteger(vm, v2, &i2, RIGHT_OPERAND)) {
return VAR_NUM((double)(i1 >> i2));
}
return VAR_NULL;
}
UNSUPPORTED_OPERAND_TYPES(">>");
return VAR_NULL;
}
Var varBitNot(PKVM* vm, Var v) {
int64_t i;
if (!validateInteger(vm, v, &i, "Unary operand")) return VAR_NULL;
return VAR_NUM((double)(~i));
}
bool varGreater(Var v1, Var v2) {
double d1, d2;
if (isNumeric(v1, &d1) && isNumeric(v2, &d2)) {
return d1 > d2;
}
TODO;
return false;
}
bool varLesser(Var v1, Var v2) {
double d1, d2;
if (isNumeric(v1, &d1) && isNumeric(v2, &d2)) {
return d1 < d2;
}
TODO;
return false;
}
#undef RIGHT_OPERAND
#undef UNSUPPORTED_OPERAND_TYPES
bool varContains(PKVM* vm, Var elem, Var container) {
Object* obj;
if (!IS_OBJ(container)) {
VM_SET_ERROR(vm, stringFormat(vm, "'$' is not iterable.",
varTypeName(container)));
}
obj = AS_OBJ(container);
switch (obj->type) {
case OBJ_STRING: {
String* sub;
String* str;
if (!IS_OBJ_TYPE(elem, OBJ_STRING)) {
VM_SET_ERROR(vm, stringFormat(vm, "Expected a string operand."));
return false;
}
sub = (String*)AS_OBJ(elem);
str = (String*)AS_OBJ(container);
if (sub->length > str->length) return false;
TODO;
} break;
case OBJ_LIST: {
uint32_t i;
List* list = (List*)AS_OBJ(container);
for (i = 0; i < list->elements.count; i++) {
if (isValuesEqual(elem, list->elements.data[i])) return true;
}
return false;
} break;
case OBJ_MAP: {
Map* map = (Map*)AS_OBJ(container);
return !IS_UNDEF(mapGet(map, elem));
} break;
case OBJ_RANGE:
case OBJ_SCRIPT:
case OBJ_FUNC:
case OBJ_FIBER:
case OBJ_CLASS:
case OBJ_INST:
TODO;
}
UNREACHABLE();
}
// Here we're switching the FNV-1a hash value of the name (cstring). Which is
// an efficient way than having multiple if (attrib == "name"). From O(n) * k
// to O(1) where n is the length of the string and k is the number of string
// comparison.
//
// ex:
// SWITCH_ATTRIB(str) { // str = "length"
// CASE_ATTRIB("length", 0x83d03615) : { return string->length; }
// }
//
// In C++11 this can be achieved (in a better way) with user defined literals
// and constexpr. (Reference from my previous compiler written in C++).
// https://github.com/ThakeeNathees/carbon/
//
// However there is a python script that's matching the CASE_ATTRIB() macro
// calls and validate if the string and the hash values are matching.
// TODO: port it to the CI/CD process at github actions.
//
#define SWITCH_ATTRIB(name) switch (utilHashString(name))
#define CASE_ATTRIB(name, hash) case hash
#define CASE_DEFAULT default
// Set error for accessing non-existed attribute.
#define ERR_NO_ATTRIB(vm, on, attrib) \
VM_SET_ERROR(vm, stringFormat(vm, "'$' object has no attribute named '$'", \
varTypeName(on), attrib->data))
Var varGetAttrib(PKVM* vm, Var on, String* attrib) {
Object* obj;
if (!IS_OBJ(on)) {
VM_SET_ERROR(vm, stringFormat(vm, "$ type is not subscriptable.",
varTypeName(on)));
return VAR_NULL;
}
obj = AS_OBJ(on);
switch (obj->type) {
case OBJ_STRING:
{
String* str = (String*)obj;
SWITCH_ATTRIB(attrib->data) {
CASE_ATTRIB("length", 0x83d03615) :
return VAR_NUM((double)(str->length));
CASE_ATTRIB("lower", 0xb51d04ba) :
return VAR_OBJ(stringLower(vm, str));
CASE_ATTRIB("upper", 0xa8c6a47) :
return VAR_OBJ(stringUpper(vm, str));
CASE_ATTRIB("strip", 0xfd1b18d1) :
return VAR_OBJ(stringStrip(vm, str));
CASE_DEFAULT:
ERR_NO_ATTRIB(vm, on, attrib);
return VAR_NULL;
}
UNREACHABLE();
}
case OBJ_LIST:
{
List* list = (List*)obj;
SWITCH_ATTRIB(attrib->data) {
CASE_ATTRIB("length", 0x83d03615) :
return VAR_NUM((double)(list->elements.count));
CASE_DEFAULT:
ERR_NO_ATTRIB(vm, on, attrib);
return VAR_NULL;
}
UNREACHABLE();
}
case OBJ_MAP:
{
// Not sure should I allow string values could be accessed with
// this way. ex:
// map = { "foo" : 42, "can't access" : 32 }
// val = map.foo ## 42
TODO;
UNREACHABLE();
}
case OBJ_RANGE:
{
Range* range = (Range*)obj;
SWITCH_ATTRIB(attrib->data) {
CASE_ATTRIB("as_list", 0x1562c22):
return VAR_OBJ(rangeAsList(vm, range));
// We can't use 'start', 'end' since 'end' in pocketlang is a
// keyword. Also we can't use 'from', 'to' since 'from' is a keyword
// too. So, we're using 'first' and 'last' to access the range limits.
CASE_ATTRIB("first", 0x4881d841):
return VAR_NUM(range->from);
CASE_ATTRIB("last", 0x63e1d819):
return VAR_NUM(range->to);
CASE_DEFAULT:
ERR_NO_ATTRIB(vm, on, attrib);
return VAR_NULL;
}
UNREACHABLE();
}
case OBJ_SCRIPT:
{
Script* scr = (Script*)obj;
// Search in types.
int index = scriptGetClass(scr, attrib->data, attrib->length);
if (index != -1) {
ASSERT_INDEX((uint32_t)index, scr->classes.count);
return VAR_OBJ(scr->classes.data[index]);
}
// Search in functions.
index = scriptGetFunc(scr, attrib->data, attrib->length);
if (index != -1) {
ASSERT_INDEX((uint32_t)index, scr->functions.count);
return VAR_OBJ(scr->functions.data[index]);
}
// Search in globals.
index = scriptGetGlobals(scr, attrib->data, attrib->length);
if (index != -1) {
ASSERT_INDEX((uint32_t)index, scr->globals.count);
return scr->globals.data[index];
}
ERR_NO_ATTRIB(vm, on, attrib);
return VAR_NULL;
}
case OBJ_FUNC:
{
Function* fn = (Function*)obj;
SWITCH_ATTRIB(attrib->data) {
CASE_ATTRIB("arity", 0x3e96bd7a) :
return VAR_NUM((double)(fn->arity));
CASE_ATTRIB("name", 0x8d39bde6) :
return VAR_OBJ(newString(vm, fn->name));
CASE_DEFAULT:
ERR_NO_ATTRIB(vm, on, attrib);
return VAR_NULL;
}
UNREACHABLE();
}
case OBJ_FIBER:
{
Fiber* fb = (Fiber*)obj;
SWITCH_ATTRIB(attrib->data) {
CASE_ATTRIB("is_done", 0x789c2706):
return VAR_BOOL(fb->state == FIBER_DONE);
CASE_ATTRIB("function", 0x9ed64249):
return VAR_OBJ(fb->func);
CASE_DEFAULT:
ERR_NO_ATTRIB(vm, on, attrib);
return VAR_NULL;
}
UNREACHABLE();
}
case OBJ_CLASS:
TODO;
UNREACHABLE();
case OBJ_INST:
{
Instance* inst = (Instance*)obj;
if (inst->is_native) {
TODO;
} else {
uint32_t i;
// TODO: Optimize this with binary search.
Class* ty = inst->ins->type;
for (i = 0; i < ty->field_names.count; i++) {
String* f_name;
ASSERT_INDEX(i, ty->field_names.count);
ASSERT_INDEX(ty->field_names.data[i], ty->owner->names.count);
f_name = ty->owner->names.data[ty->field_names.data[i]];
if (f_name->hash == attrib->hash &&
f_name->length == attrib->length &&
memcmp(f_name->data, attrib->data, attrib->length) == 0) {
return inst->ins->fields.data[i];
}
}
}
ERR_NO_ATTRIB(vm, on, attrib);
return VAR_NULL;
}
default:
UNREACHABLE();
}
UNREACHABLE();
}
void varSetAttrib(PKVM* vm, Var on, String* attrib, Var value) {
#define ATTRIB_IMMUTABLE(name) \
do { \
if ((attrib->length == strlen(name) && strcmp(name, attrib->data) == 0)) { \
VM_SET_ERROR(vm, stringFormat(vm, "'$' attribute is immutable.", name)); \
return; \
} \
} while (false)
Object* obj;
if (!IS_OBJ(on)) {
VM_SET_ERROR(vm, stringFormat(vm, "$ type is not subscriptable.",
varTypeName(on)));
return;
}
obj = AS_OBJ(on);
switch (obj->type) {
case OBJ_STRING:
ATTRIB_IMMUTABLE("length");
ATTRIB_IMMUTABLE("lower");
ATTRIB_IMMUTABLE("upper");
ATTRIB_IMMUTABLE("strip");
ERR_NO_ATTRIB(vm, on, attrib);
return;
case OBJ_LIST:
ATTRIB_IMMUTABLE("length");
ERR_NO_ATTRIB(vm, on, attrib);
return;
case OBJ_MAP:
// Not sure should I allow string values could be accessed with
// this way. ex:
// map = { "foo" : 42, "can't access" : 32 }
// map.foo = 'bar'
TODO;
ERR_NO_ATTRIB(vm, on, attrib);
return;
case OBJ_RANGE:
ATTRIB_IMMUTABLE("as_list");
ATTRIB_IMMUTABLE("first");
ATTRIB_IMMUTABLE("last");
ERR_NO_ATTRIB(vm, on, attrib);
return;
case OBJ_SCRIPT: {
Script* scr = (Script*)obj;
// Check globals.
int index = scriptGetGlobals(scr, attrib->data, attrib->length);
if (index != -1) {
ASSERT_INDEX((uint32_t)index, scr->globals.count);
scr->globals.data[index] = value;
return;
}
// Check function (Functions are immutable).
index = scriptGetFunc(scr, attrib->data, attrib->length);
if (index != -1) {
ASSERT_INDEX((uint32_t)index, scr->functions.count);
ATTRIB_IMMUTABLE(scr->functions.data[index]->name);
return;
}
index = scriptGetClass(scr, attrib->data, attrib->length);
if (index != -1) {
String* name;
ASSERT_INDEX((uint32_t)index, scr->classes.count);
ASSERT_INDEX(scr->classes.data[index]->name, scr->names.count);
name = scr->names.data[scr->classes.data[index]->name];
ATTRIB_IMMUTABLE(name->data);
return;
}
ERR_NO_ATTRIB(vm, on, attrib);
return;
}
case OBJ_FUNC:
ATTRIB_IMMUTABLE("arity");
ATTRIB_IMMUTABLE("name");
ERR_NO_ATTRIB(vm, on, attrib);
return;
case OBJ_FIBER:
ERR_NO_ATTRIB(vm, on, attrib);
return;
case OBJ_CLASS:
ERR_NO_ATTRIB(vm, on, attrib);
return;
case OBJ_INST:
{
Instance* inst = (Instance*)obj;
if (inst->is_native) {
TODO;
return;
} else {
uint32_t i;
// TODO: Optimize this with binary search.
Class* ty = inst->ins->type;
for (i = 0; i < ty->field_names.count; i++) {
String* f_name;
ASSERT_INDEX(i, ty->field_names.count);
ASSERT_INDEX(ty->field_names.data[i], ty->owner->names.count);
f_name = ty->owner->names.data[ty->field_names.data[i]];
if (f_name->hash == attrib->hash &&
f_name->length == attrib->length &&
memcmp(f_name->data, attrib->data, attrib->length) == 0) {
inst->ins->fields.data[i] = value;
return;
}
}
ERR_NO_ATTRIB(vm, on, attrib);
return;
}
UNREACHABLE();
}
default:
UNREACHABLE();
}
UNREACHABLE();
#undef ATTRIB_IMMUTABLE
}
#undef SWITCH_ATTRIB
#undef CASE_ATTRIB
#undef CASE_DEFAULT
#undef ERR_NO_ATTRIB
Var varGetSubscript(PKVM* vm, Var on, Var key) {
Object* obj;
if (!IS_OBJ(on)) {
VM_SET_ERROR(vm, stringFormat(vm, "$ type is not subscriptable.",
varTypeName(on)));
return VAR_NULL;
}
obj = AS_OBJ(on);
switch (obj->type) {
case OBJ_STRING:
{
String* c;
int64_t index;
String* str = ((String*)obj);
if (!validateInteger(vm, key, &index, "List index")) {
return VAR_NULL;
}
if (!validateIndex(vm, index, str->length, "String")) {
return VAR_NULL;
}
c = newStringLength(vm, str->data + index, 1);
return VAR_OBJ(c);
}
case OBJ_LIST:
{
int64_t index;
pkVarBuffer* elems = &((List*)obj)->elements;
if (!validateInteger(vm, key, &index, "List index")) {
return VAR_NULL;
}
if (!validateIndex(vm, index, elems->count, "List")) {
return VAR_NULL;
}
return elems->data[index];
}
case OBJ_MAP:
{
Var value = mapGet((Map*)obj, key);
if (IS_UNDEF(value)) {
String* key_str = toString(vm, key);
vmPushTempRef(vm, &key_str->_super);
if (IS_OBJ(key) && !isObjectHashable(AS_OBJ(key)->type)) {
VM_SET_ERROR(vm, stringFormat(vm, "Invalid key '@'.", key_str));
} else {
VM_SET_ERROR(vm, stringFormat(vm, "Key '@' not exists", key_str));
}
vmPopTempRef(vm);
return VAR_NULL;
}
return value;
}
case OBJ_RANGE:
case OBJ_SCRIPT:
case OBJ_FUNC:
case OBJ_FIBER:
case OBJ_CLASS:
case OBJ_INST:
TODO;
UNREACHABLE();
default:
UNREACHABLE();
}
UNREACHABLE();
}
void varsetSubscript(PKVM* vm, Var on, Var key, Var value) {
Object* obj;
if (!IS_OBJ(on)) {
VM_SET_ERROR(vm, stringFormat(vm, "$ type is not subscriptable.",
varTypeName(on)));
return;
}
obj = AS_OBJ(on);
switch (obj->type) {
case OBJ_STRING:
VM_SET_ERROR(vm, newString(vm, "String objects are immutable."));
return;
case OBJ_LIST:
{
int64_t index;
pkVarBuffer* elems = &((List*)obj)->elements;
if (!validateInteger(vm, key, &index, "List index")) return;
if (!validateIndex(vm, index, elems->count, "List")) return;
elems->data[index] = value;
return;
}
case OBJ_MAP:
{
if (IS_OBJ(key) && !isObjectHashable(AS_OBJ(key)->type)) {
VM_SET_ERROR(vm, stringFormat(vm, "$ type is not hashable.",
varTypeName(key)));
} else {
mapSet(vm, (Map*)obj, key, value);
}
return;
}
case OBJ_RANGE:
case OBJ_SCRIPT:
case OBJ_FUNC:
case OBJ_FIBER:
case OBJ_CLASS:
case OBJ_INST:
TODO;
UNREACHABLE();
default:
UNREACHABLE();
}
UNREACHABLE();
}
#undef DOCSTRING
#undef DEF
|
26143.c |
/* bug #1098 Empty enumerator-list */
/* The C Standard requires that something exists between the braces for
* enum, struct, and union. */
union {
};
int main(void)
{
return 0;
}
|
551133.c | /* UNCMP.C - Does PKUNPAK uncompression
*
* Copyright 1993-2015 CIX Online Ltd, All Rights Reserved
*
* 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 "warnings.h"
#include <windows.h>
#include <string.h>
#include <dos.h>
#include "amlib.h"
#include <io.h>
#include <stdlib.h>
#include <ctype.h>
#include "amctrls.h"
#include "amuser.h"
#define THIS_FILE __FILE__
#define DLE 0x90 /* repeat sequence marker */
#define NOHIST 0 /* don't consider previous input */
#define INREP 1 /* sending a repeated value */
#define TABSIZE 4096
#define STACKSIZE TABSIZE
#define NO_PRED 0xFFFF
#define EMPTY 0xF000
#define NOT_FND 0xFFFF
#define UEOF 0xFFFF
#define UPDATE TRUE
#define OUTBUFSIZE 16384 /* 16k output buffer */
#define INBUFSIZE 16384 /* 16k input buffer */
#define FIRST 257 /* first free entry */
#define CLEAR 256 /* table clear output code */
#define MAXOUTSIZE 16384
#define BITS 13 /* could be restricted to 12 */
#define INIT_BITS 9 /* initial number of bits/code */
#define HSIZE 9001 /* 91% occupancy */
#define SQEOF 256 /* Squeeze EOF */
#define NUMVALS 257 /* 256 data values plus SQEOF */
/* the following is an inline version of Amcmp_AddCRC for 1 character, implemented
* as a macro, it really speeds things up.
*/
#define add1crc( x) crc = ( ( crc >> 8) & 0x00FF) ^ unarccrctab[( crc ^ x) & 0x00FF];
#define MAXCODE( n_bits) ( ( 1<<( n_bits)) - 1)
#define tab_prefixof( i) codetab[i]
#define tab_suffixof( i) ( ( BYTE FAR *)( htab))[i]
#define de_stack ( ( BYTE FAR *)&tab_suffixof( 1<<BITS))
static void FASTCALL Amcmp_AddCRC( char *, int);
static int FASTCALL Amcmp_DlzwDecompress( HFILE, HFILE, char);
static void FASTCALL Amcmp_WriteRLE( BYTE, HFILE);
static int FASTCALL Amcmp_GetHeader( HFILE);
static int FASTCALL Amcmp_SQDecompress( HFILE, HFILE);
static BOOL FASTCALL Amcmp_ExtractFile( HFILE, LPSTR);
static int FASTCALL Amcmp_SlzwDecompress( HFILE, HFILE, int );
static int FASTCALL Amcmp_Uncompress( HFILE, HFILE );
static int FASTCALL Amcmp_StoreDecompressed( HFILE, HFILE );
static int FASTCALL Amcmp_RLEDecompress( HFILE, HFILE );
static int FASTCALL Amcmp_GetCode( HFILE );
static int FASTCALL Amcmp_Dispatch( HFILE, HFILE );
static void FASTCALL Amcmp_WriteOut( HFILE, void FAR *, size_t );
static int FASTCALL Amcmp_GetInByte( HFILE );
static UINT FASTCALL Amcmp_GetInBlock( HFILE, HPVOID, UINT );
static void FASTCALL Amcmp_FlushOut( HFILE );
static void FASTCALL Amcmp_CloseOut( HFILE );
static void FASTCALL Amcmp_SetMemory( char FAR *, char, DWORD );
static void FASTCALL Amcmp_InitTable( void);
static UINT FASTCALL Amcmp_Pop( void);
static void FASTCALL Amcmp_Push( UINT);
static int FASTCALL Amcmp_GetCode12( HFILE);
static void FASTCALL Amcmp_UpdateTable( UINT, UINT);
static UINT FASTCALL Amcmp_Hash( UINT, BYTE, int);
static void FASTCALL Amcmp_FreeBuffer( void );
static LPSTR FASTCALL Amcmp_InitBuffer( HFILE );
static void FASTCALL Amcmp_FillBuffer( HFILE );
typedef struct tagEntry {
char used;
UINT next; /* hi bit is 'used' flag */
UINT predecessor; /* 12 bit code */
BYTE follower;
} entry;
entry FAR * string_tab;
#pragma pack( 1)
struct archive_header {
char arcmark; /* arc mark = 0x1a */
char atype; /* header version 0 = end, else pack method */
char name[13]; /* file name */
DWORD size; /* size of compressed file */
short date; /* file date */
short time; /* file time */
WORD crc; /* cyclic redundancy check */
DWORD length; /* true file length */
};
#pragma pack( )
struct sq_tree {
int children[2]; /* left, right */
}; /* use large buffer */
int unarccrctab[] = /* CRC lookup table */
{
0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040
};
static WORD szBuf;
static WORD wRead;
static WORD wTotal;
static LPSTR lpBuffer; /* pointer to input buffer */
static LPSTR lpBufPtr; /* current pos in input buffer */
static HFILE out;
static int clear_flg;
static int n_bits; /* number of bits/code */
static int max_bits; /* user settable max # bits/code */
static int maxcode; /* maximum code, given n_bits */
static int maxmaxcode; /* should NEVER generate this code */
static int free_ent; /* first unused entry */
static BYTE state; /* state of ncr packing */
static UINT crc; /* crc of current file */
static long sizeleft; /* for fileio routines */
static int errors; /* number of errors */
static char path[ 63 ]; /* path name to output to */
static char headertype; /* headertype of archive */
static HWND hwndStatus;
static long total;
static WORD old_count;
static int sp; /* current stack pointer */
static LPSTR stack; /* stack for pushing and popping */
static BOOL fBuf;
static DWORD dwOutBufSize;
static DWORD dwOutBufCount;
static void FAR * lpOutBuffer;
static BOOL fBuf;
static long FAR * htab;
static WORD FAR * codetab;
static short hsize; /* for dynamic table sizing */
static struct archive_header archead; /* header for current archive */
#ifndef WIN32
static CATCHBUF catchBuf;
#else
static BOOL fEarlyEof;
#endif
/* This function checks whether the specified file is a archived file.
*/
BOOL EXPORT WINAPI Amcmp_IsArcedFile( LPSTR lpFileName )
{
HFILE fh;
char ch;
if( ( fh = _lopen( lpFileName, OF_READ ) ) != HFILE_ERROR )
{
int cRead;
cRead = _lread( fh, &ch, sizeof( ch ) );
_lclose( fh );
if( cRead == 1 && ch == 0x1A )
return( TRUE );
}
return( FALSE );
}
/* This uncompresses the specified file.
*/
BOOL EXPORT WINAPI Amcmp_UncompressFile( HWND hwnd, LPSTR lpszInFile, LPSTR lpszOutFile )
{
HFILE in;
BOOL fOk = FALSE;
total = old_count = 0;
errors = sp = 0;
clear_flg = 0;
free_ent = 0;
max_bits = BITS;
maxmaxcode = 1 << BITS;
if( ( in = _lopen( lpszInFile, OF_READ ) ) != HFILE_ERROR )
{
LPVOID hBuffer;
hBuffer = Amcmp_InitBuffer( in );
fBuf = FALSE;
fOk = TRUE;
out = HFILE_ERROR;
#ifndef WIN32
if( Catch( ( int FAR *)catchBuf ) != 0 )
{
if( out != HFILE_ERROR )
_lclose( out );
fOk = FALSE;
}
#else
fEarlyEof = FALSE;
#endif
if( fOk )
{
if( !Amcmp_GetHeader( in ) )
fOk = FALSE;
else {
hwndStatus = hwnd;
if( NULL != hwndStatus )
SendMessage( hwndStatus, SB_STEPSTATUSGAUGE, 0, 0L );
fOk = Amcmp_ExtractFile( in, lpszOutFile );
}
}
#ifdef WIN32
if( fEarlyEof )
fOk = FALSE;
#endif
Amcmp_FreeBuffer( );
_lclose( in );
}
return( fOk );
}
static BOOL FASTCALL Amcmp_ExtractFile( HFILE in, LPSTR filename )
{
char outfile[80];
BOOL failure = FALSE;
/* create filename with specified path */
lstrcpy( outfile, filename);
if ( ( out = _lcreat( outfile, 0 ) ) == HFILE_ERROR )
return( FALSE);
if( archead.length )
failure = Amcmp_Uncompress( in, out);
Amcmp_CloseOut( out );
/* set date and time, but skip if not MSC since Turbo C has no */
/* equivalent function */
#ifndef WIN32
_dos_setftime( out, archead.date, archead.time);
#endif
_lclose( out);
/* if errors during uncompression, than delete attempt at uncompression */
if( failure )
_unlink( outfile );
return( !failure );
}
/* Amcmp_InitBuffer
* ( Private Internal)
*
* Description:
* This function initalises the input buffer to 0xFF00 bytes, and sets
* the first byte of the buffer to NULL which triggers the next read of
* the buffer to call Amcmp_FillBuffer( ).
*
* Input:
* fh is the input file handle
*
* Return Value
* Returns a pointer to the input buffer
*/
static LPSTR FASTCALL Amcmp_InitBuffer( int fh )
{
DWORD lszBuf;
HGLOBAL hBuffer;
lszBuf = _llseek( fh, 0L, 2 );
_llseek( fh, 0L, 0 );
szBuf = ( unsigned)min( lszBuf, 0x0000FF00L );
if( hBuffer = GlobalAlloc( GHND, ( DWORD)szBuf ) )
{
lpBuffer = GlobalLock( hBuffer );
lpBufPtr = lpBuffer;
wTotal = wRead = 0;
Amcmp_FillBuffer( fh );
}
return( lpBuffer );
}
static void FASTCALL Amcmp_FreeBuffer( void )
{
HGLOBAL hg;
#ifdef WIN32
hg = GlobalHandle( lpBuffer );
#else
hg = ( HGLOBAL)LOWORD( GlobalHandle( SELECTOROF( lpBuffer ) ) );
#endif
GlobalUnlock( hg );
GlobalFree( hg );
}
static UINT FASTCALL Amcmp_GetInBlock( HFILE fh, HPVOID lpBuf, UINT wSize )
{
WORD wRead = 0;
while( wSize-- )
{
*( (HPSTR)lpBuf)++ = Amcmp_GetInByte( fh );
++wRead;
}
return( wRead );
}
static int FASTCALL Amcmp_GetInByte( HFILE fh )
{
#ifdef WIN32
if( fEarlyEof )
return( 0 );
#endif
if( wRead == wTotal )
{
Amcmp_FillBuffer( fh );
#ifdef WIN32
if( wTotal == 0 ) {
fEarlyEof = TRUE;
return( 0 );
}
#else
if( wTotal == 0 )
Throw( ( int FAR *)catchBuf, 1 );
#endif
}
++wRead;
return( *lpBufPtr++ );
}
/* Amcmp_FillBuffer
* ( Private Internal)
*
* Description:
* This function fills the input buffer from the source file.
*
* Input:
* fh is the input file handle
*
* Return Value
* None
*/
static void FASTCALL Amcmp_FillBuffer( int fh )
{
lpBufPtr = lpBuffer;
wTotal = _lread( fh, lpBufPtr, szBuf );
wRead = 0;
}
static int FASTCALL Amcmp_GetHeader( HFILE in)
{
/* read in archead minus the length field */
if ( ( Amcmp_GetInBlock( in, &archead, sizeof( struct archive_header) - sizeof( long))) < 2) {
return( FALSE );
}
/* if archead.arcmark does not have that distinctive arc identifier 0x1a */
/* then it is not an archive */
if ( archead.arcmark != 0x1a) {
return( FALSE);
}
/* if atype is 0 then EOF */
if ( archead.atype == 0)
return ( FALSE);
/* if not obsolete header type then the next long is the length field */
if ( archead.atype != 1) {
if ( Amcmp_GetInBlock( in, &archead.length, sizeof( long)) != sizeof( long)) {
return( FALSE);
}
}
/* if obsolete then set length field equal to size field */
else
archead.length = archead.size;
return ( TRUE);
}
static int FASTCALL Amcmp_Uncompress( HFILE in, HFILE out )
{
switch ( archead.atype) {
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
break;
case 10:
case 11:
_llseek( in, archead.size, 1);
return ( 1);
default:
_llseek( in, archead.size, 1);
errors++;
return ( 1);
}
if( Amcmp_Dispatch( in, out) > 0 )
{
errors++;
return ( 1);
}
if ( crc != archead.crc)
{
errors++;
return ( 1);
}
return ( 0);
}
static int FASTCALL Amcmp_Dispatch( HFILE in, HFILE out )
{
int err = 0;
crc = 0;
sizeleft = archead.size;
state = 0;
switch( archead.atype )
{
case 1:
case 2:
err = Amcmp_StoreDecompressed( in, out);
break;
case 3:
err = Amcmp_RLEDecompress( in, out);
break;
case 4:
err = Amcmp_SQDecompress( in, out);
break;
case 5:
case 6:
case 7:
err = Amcmp_SlzwDecompress( in, out, archead.atype);
break;
case 8:
case 9:
err = Amcmp_DlzwDecompress( in, out, archead.atype);
break;
default:
break;
/* should never reach this code */
}
return( err );
}
/* Amcmp_WriteRLE outputs bytes to a file unchanged, except that runs */
/* more than two characters are compressed to the format: */
/* <char> DLE <number> */
/* When DLE is encountered, the next byte is read and Amcmp_WriteRLE */
/* repeats the previous byte <number> times. A <number> of 0 */
/* indicates a true DLE character. */
static void FASTCALL Amcmp_WriteRLE( BYTE c, HFILE out )
{ /* put RLE coded bytes */
static char lastc;
switch ( state) { /* action depends on our state */
case NOHIST: /* no previous history */
if ( c == DLE) /* if starting a series */
state = INREP; /* then remember it next time */
else {
add1crc( c);
lastc = c;
Amcmp_WriteOut( out, &c, sizeof( char) );
}
return;
case INREP: /* in a repeat */
if ( c) /* if count is nonzero */
while ( --c) { /* then repeatedly ... */
add1crc( lastc);
Amcmp_WriteOut( out, &lastc, sizeof( char) );
}
else {
BYTE ch2;
add1crc( DLE);
ch2 = DLE;
Amcmp_WriteOut( out, &ch2, sizeof( char) );
}
state = NOHIST; /* back to no history */
return;
}
}
static int FASTCALL Amcmp_SlzwDecompress( HFILE in, HFILE out, int arctype)
{
UINT c, tempc;
UINT code, oldcode, incode, finchar, lastchar;
char unknown = FALSE;
int code_count = TABSIZE - 256;
entry FAR *ep;
INITIALISE_PTR(string_tab);
INITIALISE_PTR(stack);
if( !fNewMemory( &string_tab, sizeof( entry) * TABSIZE) )
return( 1);
if( !fNewMemory( &stack, sizeof( char) * STACKSIZE) )
return( 1);
headertype = arctype;
lastchar = 0;
Amcmp_InitTable( ); /* set up atomic code definitions */
code = oldcode = Amcmp_GetCode12( in);
c = string_tab[code].follower; /* first code always known */
if ( headertype == 5) {
add1crc( c);
Amcmp_WriteOut( out, &c, sizeof( char ) );
} else
Amcmp_WriteRLE( ( BYTE)c, out);
finchar = c;
while ( UEOF != ( code = incode = Amcmp_GetCode12( in))) {
ep = &( string_tab[code]); /* initialize pointer */
if ( !ep->used) { /* if code isn't known */
lastchar = finchar;
code = oldcode;
unknown = TRUE;
ep = &( string_tab[code]); /* re-initialize pointer */
}
while ( NO_PRED != ep->predecessor) {
/* decode string backwards into stack */
Amcmp_Push( ep->follower);
code = ep->predecessor;
ep = &( string_tab[code]);
}
finchar = ep->follower;
/* above loop terminates, one way or another, with */
/* string_tab[code].follower = first char in string */
if ( headertype == 5) {
add1crc( finchar);
Amcmp_WriteOut( out, &c, sizeof( char ) );
} else
Amcmp_WriteRLE( ( BYTE)finchar, out);
/* Amcmp_Pop anything stacked during code parsing */
while ( EMPTY != ( tempc = Amcmp_Pop( ))) {
if ( headertype == 5) {
add1crc( tempc);
Amcmp_WriteOut( out, &tempc, sizeof( char));
} else
Amcmp_WriteRLE( ( BYTE)tempc, out);
}
if ( unknown) { /* if code isn't known the follower char of
* last */
if ( headertype == 5) {
finchar = lastchar;
add1crc( finchar);
Amcmp_WriteOut( out, &finchar, sizeof( char));
} else
Amcmp_WriteRLE( ( BYTE)( finchar = lastchar ), out);
unknown = FALSE;
}
if ( code_count) {
Amcmp_UpdateTable( oldcode, finchar);
--code_count;
}
oldcode = incode;
}
FreeMemory( &stack);
FreeMemory( &string_tab);
return ( 0); /* close all files and quit */
}
static unsigned FASTCALL Amcmp_Hash( UINT pred, BYTE foll, int update )
{
register UINT local, tempnext;
static long temp;
register entry FAR *ep;
if ( headertype == 7)
/* I'm not sure if this works, since I've never seen an archive with */
/* header type 7. If you encounter one, please try it and tell me */
local = ( ( pred + foll) * 15073) & 0xFFF;
else {
/* this uses the 'mid-square' algorithm. I.E. for a Amcmp_Hash val of n bits */
/* Amcmp_Hash = middle binary digits of ( key * key). Upon collision, Amcmp_Hash */
/* searches down linked list of keys that hashed to that key already. */
/* It will NOT notice if the table is full. This must be handled */
/* elsewhere. */
temp = ( pred + foll) | 0x0800;
temp *= temp;
local = ( UINT)( temp >> 6) & 0x0FFF; /* middle 12 bits of result */
}
if ( !string_tab[local].used)
return local;
else {
/* if collision has occured */
/* a function called eolist used to be here. tempnext is used */
/* because a temporary variable was needed and tempnext in not */
/* used till later on. */
while ( 0 != ( tempnext = string_tab[local].next))
local = tempnext;
/* search for free entry from local + 101 */
tempnext = ( local + 101) & 0x0FFF;
ep = &( string_tab[tempnext]); /* initialize pointer */
while ( ep->used) {
++tempnext;
if ( tempnext == TABSIZE) {
tempnext = 0; /* handle wrap to beginning of table */
ep = string_tab;/* address of first element of table */
} else
++ep; /* point to next element in table */
}
/* put new tempnext into last element in collision list */
if ( update) /* if update requested */
string_tab[local].next = tempnext;
return tempnext;
}
}
static void FASTCALL Amcmp_InitTable( void )
{
register UINT i;
Amcmp_SetMemory( ( char FAR *) string_tab, ( char) 0, ( DWORD) sizeof( entry) * TABSIZE);
for ( i = 0; i <= 255; i++) {
Amcmp_UpdateTable( NO_PRED, i);
}
}
static void FASTCALL Amcmp_UpdateTable( UINT pred, UINT foll)
{
entry FAR *ep; /* pointer to current entry */
/* calculate offset just once */
ep = &( string_tab[Amcmp_Hash( pred, ( BYTE)foll, UPDATE)]);
ep->used = TRUE;
ep->next = 0;
ep->predecessor = pred;
ep->follower = foll;
}
/* Amcmp_GetCode fills an input buffer of bits and returns the next 12 bits */
/* from that buffer with each call */
static int FASTCALL Amcmp_GetCode12( HFILE in)
{
int localbuf, returnval;
static UINT inbuf = EMPTY;
if ( EMPTY == inbuf) { /* On code boundary */
if ( ( sizeleft - 2) < 0)
return -1;
sizeleft -= 2;
Amcmp_GetInBlock( in, &localbuf, sizeof( char ) );
localbuf &= 0xFF;
Amcmp_GetInBlock( in, &inbuf, sizeof( char ) );
inbuf &= 0xFF;
returnval = ( ( localbuf << 4) & 0xFF0) + ( ( inbuf >> 4) & 0x00F);
inbuf &= 0x000F;
} else { /* buffer contains nibble H */
if ( !sizeleft)
return -1;
sizeleft--;
Amcmp_GetInBlock( in, &localbuf, sizeof( char ) );
localbuf &= 0xFF;
returnval = localbuf + ( ( inbuf << 8) & 0xF00);
inbuf = EMPTY;
}
return returnval;
}
static void FASTCALL Amcmp_SetMemory( char FAR * mem, char value, DWORD size )
{
register DWORD i;
for ( i = 0; i < size; i++)
mem[i] = value;
}
static void FASTCALL Amcmp_Push( UINT c )
{
stack[sp] = ( ( char) c); /* coerce passed integer into a character */
++sp;
ASSERT( sp < STACKSIZE );
}
static UINT FASTCALL Amcmp_Pop( void )
{
if ( sp > 0) {
--sp; /* Amcmp_Push leaves sp pointing to next empty slot */
return ( ( int) stack[sp] ); /* make sure Amcmp_Pop returns char */
}
else
return EMPTY;
}
static void FASTCALL Amcmp_AddCRC( char *cc, int i )
{
for ( cc--; i--;)
crc = ( ( crc >> 8) & 0x00ff) ^ unarccrctab[( crc ^ *++cc) & 0x00ff];
}
static int FASTCALL Amcmp_DlzwDecompress( HFILE in, HFILE out, char arctype )
{
BYTE FAR *stackp;
register int finchar;
int oldcode;
register int code;
int incode;
INITIALISE_PTR(htab);
INITIALISE_PTR(codetab);
if( !fNewMemory( &htab, sizeof( long) * HSIZE) )
return( 1 );
if( !fNewMemory( &codetab, sizeof( WORD) * HSIZE) )
return( 1 );
if ( arctype == 8) { /* UnCrunch */
hsize = 5003;
/* every Crunched file must start with a byte equal to 12, */
/* the maximum bit size of the pointer-length pair */
if ( !sizeleft) { /* no bytes in file */
FreeMemory( &htab);
FreeMemory( &codetab);
return( 0 );
}
sizeleft--;
max_bits = Amcmp_GetInByte( in );
if ( 12 != max_bits ) {
return( 1);
}
} else { /* UnSquash */
max_bits = BITS;
hsize = 9001;
}
maxmaxcode = 1 << max_bits;
/* start of decompression */
maxcode = MAXCODE( INIT_BITS);
n_bits = INIT_BITS;
for ( code = 255; code >= 0; code--) {
tab_suffixof( code) = code;
}
free_ent = FIRST;
incode = finchar = oldcode = Amcmp_GetCode( in);
if ( oldcode == -1) { /* EOF already? */
FreeMemory( &codetab);
FreeMemory( &htab);
return( 0); /* Get out of here */
}
if ( arctype == 8)
Amcmp_WriteRLE( ( char) incode, out);
else {
add1crc( ( char) incode);
Amcmp_WriteOut( out, &incode, sizeof( char));
}
stackp = de_stack;
while ( ( code = Amcmp_GetCode( in)) > -1) {
if ( code == CLEAR) {
for ( code = 255; code >= 0; code--)
tab_prefixof( code) = 0;
clear_flg = 1;
free_ent = FIRST - 1;
if ( ( code = Amcmp_GetCode( in)) == -1) { /* O, untimely death! */
break;
}
}
incode = code;
/* Special case for KwKwK string */
if ( code >= free_ent) {
*stackp++ = finchar;
code = oldcode;
}
/* Generate output characters in reverse order Stop if input */
/* code is in range 0..255 */
while ( code >= 256) {
*stackp++ = tab_suffixof( code);
code = tab_prefixof( code);
}
*stackp++ = finchar = tab_suffixof( code);
/* the following code for arctype 9 used to use memrev( ) to */
/* reverse the order and then output using fread. The following */
/* method was tested to be faster */
/* characters are read in reverse order from the stack ( like any */
/* stack) and then output. */
if ( arctype == 9) {
do {
add1crc( *--stackp);
Amcmp_WriteOut( out, stackp, sizeof( char ) );
} while ( stackp > de_stack);
} else { /* arctype==8 */
do
Amcmp_WriteRLE( *--stackp, out);
while ( stackp > de_stack);
}
/* Generate the new entry */
if ( ( code = free_ent) < maxmaxcode) {
tab_prefixof( code) = ( WORD) oldcode;
tab_suffixof( code) = finchar;
free_ent = code + 1;
}
/* Remember previous code */
oldcode = incode;
}
/* it's important to free all memory used, so Amcmp_Uncompress will run on systems */
/* with limited RAM */
FreeMemory( &htab);
FreeMemory( &codetab);
return( 0 );
}
static int FASTCALL Amcmp_StoreDecompressed( HFILE in, HFILE out)
{
int c;
char *buffer;
/* first time initialization */
INITIALISE_PTR(buffer);
if( !fNewMemory( &buffer, sizeof( char) * MAXOUTSIZE) )
{
/* do char by char if no room for buffer */
while ( !sizeleft) {
sizeleft--;
Amcmp_GetInBlock( in, &c, sizeof( char ) );
add1crc( c);
Amcmp_WriteOut( out, &c, sizeof( char ) );
}
return( 0);
}
while ( sizeleft >= MAXOUTSIZE) {
if ( Amcmp_GetInBlock( in, buffer, MAXOUTSIZE) != MAXOUTSIZE)
return( 1);
Amcmp_AddCRC( buffer, MAXOUTSIZE);
Amcmp_WriteOut( out, buffer, MAXOUTSIZE);
sizeleft -= MAXOUTSIZE;
}
if ( Amcmp_GetInBlock( in, buffer, ( UINT)sizeleft) != ( UINT)sizeleft)
return( 1);
Amcmp_AddCRC( buffer, ( UINT)sizeleft);
Amcmp_WriteOut( out, buffer, ( UINT)sizeleft);
/* free the buffer before exiting */
free( buffer);
sizeleft = 0;
return( 0 );
}
static void FASTCALL Amcmp_WriteOut( HFILE out, void FAR * data, size_t len )
{
WORD count;
if( !fBuf )
{
HGLOBAL hOutBuffer;
dwOutBufSize = 0xFF00;
if( hOutBuffer = GlobalAlloc( GHND, ( DWORD)dwOutBufSize ) )
{
lpOutBuffer = GlobalLock( hOutBuffer );
dwOutBufCount = 0;
}
fBuf = TRUE;
}
if( !fBuf )
_lwrite( out, data, len );
else {
if( dwOutBufCount + len >= dwOutBufSize )
Amcmp_FlushOut( out );
#ifdef WIN32
memcpy( ( LPSTR)lpOutBuffer + dwOutBufCount, data, len );
#else
_fmemcpy( ( LPSTR)lpOutBuffer + dwOutBufCount, data, len );
#endif
dwOutBufCount += len;
}
total += len;
count = ( WORD)( ( 100.0 / ( double)archead.length ) * ( double)total );
if( count != old_count )
{
if( NULL != hwndStatus )
SendMessage( hwndStatus, SB_STEPSTATUSGAUGE, count, 0L );
old_count = count;
}
}
static void FASTCALL Amcmp_FlushOut( HFILE out )
{
if( dwOutBufCount )
{
_lwrite( out, lpOutBuffer, LOWORD( dwOutBufCount ) );
dwOutBufCount = 0;
}
}
static void FASTCALL Amcmp_CloseOut( HFILE out )
{
Amcmp_FlushOut( out );
if( fBuf )
{
HGLOBAL hg;
#ifdef WIN32
hg = GlobalHandle( lpOutBuffer );
#else
hg = ( HGLOBAL)LOWORD( GlobalHandle( SELECTOROF( lpOutBuffer ) ) );
#endif
GlobalUnlock( hg );
GlobalFree( hg );
}
}
static int FASTCALL Amcmp_RLEDecompress( HFILE in, HFILE out)
{
int c;
char *buffer;
INITIALISE_PTR(buffer);
if( !fNewMemory( &buffer, sizeof( char) * MAXOUTSIZE) )
{
/* uncompress char by char if no room for buffer */
while ( sizeleft) {
sizeleft--;
c = Amcmp_GetInByte( in );
Amcmp_WriteRLE( ( BYTE)c, out);
}
}
while ( sizeleft >= MAXOUTSIZE) {
if( Amcmp_GetInBlock( in, buffer, MAXOUTSIZE ) != MAXOUTSIZE )
return( 1);
for ( c = 0; c != MAXOUTSIZE; c++)
Amcmp_WriteRLE( buffer[c], out);
sizeleft -= MAXOUTSIZE;
}
if ( Amcmp_GetInBlock( in, buffer, ( size_t)sizeleft) != ( size_t)sizeleft)
return( 1);
for ( c = 0; c != sizeleft; c++)
Amcmp_WriteRLE( buffer[c], out);
sizeleft = 0;
free( buffer);
return( 0);
}
static int FASTCALL Amcmp_SQDecompress( HFILE in, HFILE out)
{
register int i; /* generic loop index */
register int bitpos; /* last bit position read */
int curbyte; /* last byte value read */
int numnodes;
struct sq_tree FAR *dnode;
/* Allocate memory for decoding tree
*/
INITIALISE_PTR(dnode);
if( !fNewMemory( &dnode, sizeof( struct sq_tree) * NUMVALS) )
return( 1);
/* get number of nodes in tree, this uses two character input calls */
/* instead of one integer input call for speed */
if ( !( sizeleft - 1) <= 0)
numnodes = -1;
sizeleft -= 2;
numnodes = Amcmp_GetInByte( in );
numnodes += Amcmp_GetInByte( in ) * 256;
if ( ( numnodes < 0) || ( numnodes >= NUMVALS)) {
return( 1);
}
/* initialize for possible empty tree ( SQEOF only) */
dnode[0].children[0] = -( SQEOF + 1);
dnode[0].children[1] = -( SQEOF + 1);
for ( i = 0; i < numnodes; ++i) { /* get decoding tree from file */
ASSERT( sizeleft - 3 > 0 );
sizeleft -= 4;
dnode[i].children[0] = Amcmp_GetInByte( in );
dnode[i].children[0] += Amcmp_GetInByte( in ) * 256;
dnode[i].children[1] = Amcmp_GetInByte( in );
dnode[i].children[1] += Amcmp_GetInByte( in ) * 256;
}
bitpos = 8; /* set to above read condition */
curbyte = 0;
while ( i != -1)
{
for ( i = 0; i >= 0;)
{ /* traverse tree */
if ( ++bitpos > 7)
{
if ( !sizeleft)
{
FreeMemory( &dnode);
return( 0);
}
sizeleft--;
curbyte = Amcmp_GetInByte( in );
bitpos = 0;
i = dnode[i].children[1 & curbyte];
}
else
i = dnode[i].children[1 & ( curbyte >>= 1)];
}
/* decode fake node index to original data value */
i = -( i + 1);
/* decode special endfile token to normal EOF */
i = ( i == SQEOF) ? -1 : i;
if ( i != -1)
Amcmp_WriteRLE( ( BYTE)i, out);
}
/* free up decoding table for later use */
FreeMemory( &dnode);
return( 0);
}
static int FASTCALL Amcmp_GetCode( HFILE in )
{
static char iobuf[BITS];
int code;
static int offset = 0;
static int size = 0;
register int r_off;
int bits;
BYTE *bp = iobuf;
static BYTE rmask[9] = { /* for use with Amcmp_GetCode( ) */
0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff
};
if ( clear_flg > 0 || offset >= size || free_ent > maxcode) {
/* set size to a register variable. Since size is used often, and */
/* only two registers may be defined in MSC, I'm using r_off instead */
/* of size, because r_off is a register variable. */
r_off = size;
/* If the next entry will be too big for the current code */
/* size, then we must increase the size. This implies */
/* reading a new buffer full, too. */
if ( free_ent > maxcode) {
n_bits++;
if ( n_bits == max_bits)
maxcode = maxmaxcode; /* won't get any bigger now */
else
maxcode = MAXCODE( n_bits);
}
if ( clear_flg > 0) {
maxcode = MAXCODE( INIT_BITS);
n_bits = INIT_BITS;
clear_flg = 0;
}
for ( r_off = 0; r_off < n_bits; r_off++) {
if ( !sizeleft)
break; /* if EOF */
sizeleft--;
code = Amcmp_GetInByte( in );
iobuf[r_off] = code;
}
if ( r_off <= 0)
return -1; /* end of file */
offset = 0;
/* Round size down to integral number of codes */
r_off = ( r_off << 3) - ( n_bits - 1);
size = r_off; /* set size back to r_off */
}
r_off = offset;
bits = n_bits;
/* Get to the first byte. */
bp += ( r_off >> 3);
r_off &= 7;
/* Get first part ( low order bits) */
code = ( *bp++ >> r_off);
bits -= ( 8 - r_off);
r_off = 8 - r_off; /* now, offset into code word */
/* Get any 8 bit parts in the middle ( <=1 for up to 16 bits). */
if ( bits >= 8) {
code |= *bp++ << r_off;
r_off += 8;
bits -= 8;
}
/* high order bits. */
code |= ( *bp & rmask[bits]) << r_off;
offset += n_bits;
return code;
}
|
89901.c | /**
* @file tester.c Driver for testing allocation/deallocation mechanisms.
* @brief
* Allocate REALLY large number of allocations and then time the
* cost to deallocate just one of these (the last one).
*
* Note that each trial must be a separate execution since we don't want
* to mistakenly compare (i) what happens when you allocate memory for
* the first time; with (ii) what happens when you allocate memory
* where some previously allocated memory has been free'd.
*
* @author George Heineman
* @date 6/15/08
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#include "report.h"
/** \def FREEERROR
Invalid Strategy.
*/
#define FREEERROR 0
/** \def FREEUP
Strategy to deallocate in order.
*/
#define FREEUP 1
/** \def FREEDOWN
Strategy to deallocate in reverse order.
*/
#define FREEDOWN 2
/** \def FREESCATTERED
Strategy to deallocate in random order.
*/
#define FREESCATTERED 3
/** Known allocation types (1-3 are valid). */
static char *types[4] = {"", "UP", "DOWN", "SCATTERED" };
/** Time before process starts. */
static struct timeval before;
/** Time after process completes. */
static struct timeval after;
/** value for number of elements in a trial suite. */
int n;
/** Low value for number of elements in trial suite. */
int lowN;
/** High value for number of elements in trial suite. */
int highN;
/**
* Generate a table of memory and release with given strategy
*
* \param strategy UP, DOWN, or SCATTERED as the strategy to use.
*/
void generateTable(int strategy) {
int i, j, k;
void **pointers, **scattered;
int NUM_CHUNKS = 4096;
/* times. */
long allocateT;
long freeT = 0; /* to compile cleanly */
/* memory will be here... */
pointers = calloc (NUM_CHUNKS, sizeof (void *));
/* for scattered. */
scattered = calloc (NUM_CHUNKS, sizeof (void *));
/* Time the allocation of memory */
/* ----------------------------- */
gettimeofday(&before, (struct timezone *) NULL);
for (i = 0; i < NUM_CHUNKS; i++) {
pointers[i] = malloc (n);
}
gettimeofday(&after, (struct timezone *) NULL);
allocateT = diffTimer (&before, &after);
/* prepare scattered array by randomly shuffling n times. */
for (i = 0; i < NUM_CHUNKS; i++) {
scattered[i] = pointers[i];
}
for (i = 0; i < NUM_CHUNKS; i++) {
void *tmp;
j = (int) (NUM_CHUNKS*(rand() / (RAND_MAX + 1.0)));
k = (int) (NUM_CHUNKS*(rand() / (RAND_MAX + 1.0)));
tmp = scattered[j];
scattered[j] = scattered[k];
scattered[k] = tmp;
}
/* determine which one to apply. */
switch (strategy) {
case FREEUP:
/* time deallocation of memory, based on strategy */
gettimeofday(&before, (struct timezone *) NULL);
for (i = 0; i < NUM_CHUNKS; i++) {
free (pointers[i]);
}
gettimeofday(&after, (struct timezone *) NULL);
freeT = diffTimer (&before, &after);
break;
case FREEDOWN:
/* time deallocation of memory, based on strategy */
gettimeofday(&before, (struct timezone *) NULL);
for (i = NUM_CHUNKS-1; i >=0; i--) {
free (pointers[i]);
}
gettimeofday(&after, (struct timezone *) NULL);
freeT = diffTimer (&before, &after);
break;
case FREESCATTERED:
/* time deallocation of memory, based on strategy */
gettimeofday(&before, (struct timezone *) NULL);
for (i = 0; i < NUM_CHUNKS; i++) {
free (scattered[i]);
}
gettimeofday(&after, (struct timezone *) NULL);
freeT = diffTimer (&before, &after);
break;
}
printf ("%d\t%ld\t%ld\n", n, allocateT, freeT);
}
int main (int argc, char **argv) {
int type = FREEERROR; /** Error case. */
int i;
if (argc < 3) {
printf ("Usage: ./test {UP/DOWN/SCATTERED} n\n");
exit (-1);
}
for (i = 1; i <= 3; i++) {
if (!strcmp (types[i], argv[1])) {
type = i;
}
}
if (type == FREEERROR) {
printf ("Usage: ./test {UP/DOWN/SCATTERED} n\n");
exit (-1);
}
n = atoi (argv[2]);
generateTable(type);
exit (0);
}
|
458146.c | /*
* Copyright (c) 2009-2012 Oak Ridge National Laboratory. All rights reserved.
* Copyright (c) 2009-2012 Mellanox Technologies. All rights reserved.
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* $HEADER$
*/
#include "ompi_config.h"
#include "ompi/include/ompi/constants.h"
#include "ompi/mca/bcol/bcol.h"
#include "bcol_ptpcoll_allreduce.h"
/*
* Recursive K-ing allgather
*/
/*
*
* Recurssive k-ing algorithm
* Example k=3 n=9
*
*
* Number of Exchange steps = log (basek) n
* Number of steps in exchange step = k (radix)
*
*/
int bcol_ptpcoll_k_nomial_allgather_init(bcol_function_args_t *input_args,
struct mca_bcol_base_function_t *const_args)
{
/* local variables */
mca_bcol_ptpcoll_module_t *ptpcoll_module = (mca_bcol_ptpcoll_module_t *) const_args->bcol_module;
int *group_list = ptpcoll_module->super.sbgp_partner_module->group_list;
netpatterns_k_exchange_node_t *exchange_node = &ptpcoll_module->knomial_allgather_tree;
int my_group_index = ptpcoll_module->super.sbgp_partner_module->my_index;
int group_size = ptpcoll_module->group_size;
int *list_connected = ptpcoll_module->super.list_n_connected; /* critical for hierarchical colls */
int tag;
int i, j;
int knt;
int comm_src, comm_dst, src, dst;
int recv_offset, recv_len;
int send_offset, send_len;
uint32_t buffer_index = input_args->buffer_index;
int pow_k, tree_order;
int rc = OMPI_SUCCESS;
ompi_communicator_t* comm = ptpcoll_module->super.sbgp_partner_module->group_comm;
ompi_request_t **requests =
ptpcoll_module->ml_mem.ml_buf_desc[buffer_index].requests;
int *active_requests =
&(ptpcoll_module->ml_mem.ml_buf_desc[buffer_index].active_requests);
int completed = 0; /* initialized */
void *data_buffer = (void*)(
(unsigned char *) input_args->sbuf +
(size_t) input_args->sbuf_offset);
int pack_len = input_args->count * input_args->dtype->super.size;
#if 0
fprintf(stderr,"entering p2p allgather pack_len %d. exchange node: %p\n",pack_len, exchange_node);
#endif
/* initialize the iteration counter */
int *iteration = &ptpcoll_module->ml_mem.ml_buf_desc[buffer_index].iteration;
*iteration = 0;
/* reset active request counter */
*active_requests = 0;
/* keep tag within the limit supported by the pml */
tag = (PTPCOLL_TAG_OFFSET + input_args->sequence_num * PTPCOLL_TAG_FACTOR) & (ptpcoll_module->tag_mask);
/* mark this as a collective tag, to avoid conflict with user-level flags */
tag = -tag;
/* k-nomial parameters */
tree_order = exchange_node->tree_order;
pow_k = exchange_node->log_tree_order;
/* let's begin the collective, starting with extra ranks and their
* respective proxies
*/
if( EXTRA_NODE == exchange_node->node_type ) {
/* then I will send to my proxy rank*/
dst = exchange_node->rank_extra_sources_array[0];
/* find rank in the communicator */
comm_dst = group_list[dst];
/* now I need to calculate my own offset */
knt = 0;
for (i = 0 ; i < my_group_index; i++){
knt += list_connected[i];
}
/* send the data to my proxy */
rc = MCA_PML_CALL(isend((void *) ( (unsigned char *) data_buffer +
knt*pack_len),
pack_len * list_connected[my_group_index],
MPI_BYTE,
comm_dst, tag,
MCA_PML_BASE_SEND_STANDARD, comm,
&(requests[*active_requests])));
if( OMPI_SUCCESS != rc ) {
PTPCOLL_VERBOSE(10,("Failed to isend data"));
return OMPI_ERROR;
}
++(*active_requests);
/* now I go ahead and post the receive from my proxy */
comm_src = comm_dst;
knt = 0;
for( i =0; i < group_size; i++){
knt += list_connected[i];
}
rc = MCA_PML_CALL(irecv(data_buffer,
knt * pack_len,
MPI_BYTE,
comm_src,
tag , comm, &(requests[*active_requests])));
if( OMPI_SUCCESS != rc ) {
PTPCOLL_VERBOSE(10, ("Failed to post ireceive "));
return OMPI_ERROR;
}
++(*active_requests);
/* poll for completion */
/* this polls internally */
completed = mca_bcol_ptpcoll_test_all_for_match(active_requests, requests, &rc);
if(completed){
/* go to buffer release */
goto FINISHED;
}else{
/* save state and hop out
* nothing to save here
*/
return ((OMPI_SUCCESS != rc) ? OMPI_ERROR : BCOL_FN_STARTED);
}
}else if ( 0 < exchange_node->n_extra_sources ) {
/* I am a proxy for someone */
src = exchange_node->rank_extra_sources_array[0];
/* find the rank in the communicator */
comm_src = group_list[src];
knt = 0;
for(i = 0; i < src; i++){
knt += list_connected[i];
}
/* post the receive */
rc = MCA_PML_CALL(irecv((void *) ( (unsigned char *) data_buffer
+ knt*pack_len),
pack_len * list_connected[src],
MPI_BYTE,
comm_src,
tag , comm, &(requests[*active_requests])));
if( OMPI_SUCCESS != rc ) {
PTPCOLL_VERBOSE(10, ("Failed to post ireceive "));
return OMPI_ERROR;
}
++(*active_requests);
/* poll for completion */
/* this routine polls internally */
completed = mca_bcol_ptpcoll_test_all_for_match(active_requests, requests, &rc);
if(!completed){
/* save state and hop out
* We really do need to block here so set
* the iteration to -1 indicating we need to
* finish this part first
*/
*iteration = -1;
return ((OMPI_SUCCESS != rc )? OMPI_ERROR : BCOL_FN_STARTED);
}
}
/* we start the recursive k - ing phase */
/* fprintf(stderr,"tree order %d pow_k %d \n",tree_order,pow_k);*/
for( i = 0; i < pow_k; i++) {
for(j = 0; j < (tree_order - 1); j++) {
/* send phase */
dst = exchange_node->rank_exchanges[i][j];
if( dst < 0 ){
continue;
}
comm_dst = group_list[dst];
send_offset = exchange_node->payload_info[i][j].s_offset * pack_len;
send_len = exchange_node->payload_info[i][j].s_len * pack_len;
/* debug print */
/* fprintf(stderr,"sending %d bytes to rank %d at offset %d\n",send_len, */
/* comm_dst,send_offset); */
rc = MCA_PML_CALL(isend((void*)((unsigned char *) data_buffer +
send_offset),
send_len,
MPI_BYTE,
comm_dst, tag,
MCA_PML_BASE_SEND_STANDARD, comm,
&(requests[*active_requests])));
if( OMPI_SUCCESS != rc ) {
PTPCOLL_VERBOSE(10,("Failed to isend data"));
return OMPI_ERROR;
}
++(*active_requests);
/* sends are posted */
}
/* Now post the recv's */
for( j = 0; j < (tree_order - 1); j++ ) {
/* recv phase */
src = exchange_node->rank_exchanges[i][j];
if( src < 0 ) {
continue;
}
comm_src = group_list[src];
recv_offset = exchange_node->payload_info[i][j].r_offset * pack_len;
recv_len = exchange_node->payload_info[i][j].r_len * pack_len;
/* debug print */
/* fprintf(stderr,"recving %d bytes to rank %d at offset %d\n",recv_len, */
/* comm_src,recv_offset); */
/* post the receive */
rc = MCA_PML_CALL(irecv((void *) ((unsigned char *) data_buffer +
recv_offset),
recv_len,
MPI_BYTE,
comm_src,
tag, comm, &(requests[*active_requests])));
if( OMPI_SUCCESS != rc ) {
PTPCOLL_VERBOSE(10, ("Failed to post ireceive "));
return OMPI_ERROR;
}
++(*active_requests);
}
/* finished all send/recv's now poll for completion before
* continuing to next iteration
*/
completed = 0;
/* polling internally on 2*(k - 1) requests */
completed = mca_bcol_ptpcoll_test_all_for_match(active_requests, requests, &rc);
if(!completed){
/* save state and hop out
* only the iteration needs to be tracked
*/
*iteration = i; /* need to pick up here */
return ((OMPI_SUCCESS != rc) ? OMPI_ERROR : BCOL_FN_STARTED);
}
}
/* finish off the last piece, send the data back to the extra */
if( 0 < exchange_node->n_extra_sources ) {
dst = exchange_node->rank_extra_sources_array[0];
comm_dst = group_list[dst];
knt = 0;
for( i = 0; i < group_size; i++){
knt += list_connected[i];
}
/* debug print */
/*
fprintf(stderr,"sending %d bytes to extra %d \n",pack_len*knt,comm_dst);
*/
rc = MCA_PML_CALL(isend(data_buffer,
pack_len * knt,
MPI_BYTE,
comm_dst, tag,
MCA_PML_BASE_SEND_STANDARD, comm,
&(requests[*active_requests])));
if( OMPI_SUCCESS != rc ) {
PTPCOLL_VERBOSE(10,("Failed to isend data"));
return OMPI_ERROR;
}
++(*active_requests);
/* probe for send completion */
completed = 0;
/* polling internally */
completed = mca_bcol_ptpcoll_test_all_for_match(active_requests, requests, &rc);
if(!completed){
/* save state and hop out
* We really do need to block here so set
* the iteration to pow_k +1 indicating we need to
* finish progressing the last part
*/
*iteration = pow_k + 1;
return (OMPI_SUCCESS != rc ? OMPI_ERROR : BCOL_FN_STARTED);
}
}
FINISHED:
/* recycle buffer if need be */
return BCOL_FN_COMPLETE;
}
/* allgather progress function */
int bcol_ptpcoll_k_nomial_allgather_progress(bcol_function_args_t *input_args,
struct mca_bcol_base_function_t *const_args)
{
/* local variables */
mca_bcol_ptpcoll_module_t *ptpcoll_module = (mca_bcol_ptpcoll_module_t *) const_args->bcol_module;
int *group_list = ptpcoll_module->super.sbgp_partner_module->group_list;
netpatterns_k_exchange_node_t *exchange_node = &ptpcoll_module->knomial_allgather_tree;
int group_size = ptpcoll_module->group_size;
int *list_connected = ptpcoll_module->super.list_n_connected; /* critical for hierarchical colls */
int tag;
int i, j;
int knt;
int comm_src, comm_dst, src, dst;
int recv_offset, recv_len;
int send_offset, send_len;
uint32_t buffer_index = input_args->buffer_index;
int pow_k, tree_order;
int rc = OMPI_SUCCESS;
ompi_communicator_t* comm = ptpcoll_module->super.sbgp_partner_module->group_comm;
ompi_request_t **requests =
ptpcoll_module->ml_mem.ml_buf_desc[buffer_index].requests;
int *active_requests =
&(ptpcoll_module->ml_mem.ml_buf_desc[buffer_index].active_requests);
int completed = 0; /* initialized */
void *data_buffer = (void*)(
(unsigned char *) input_args->sbuf +
(size_t) input_args->sbuf_offset);
int pack_len = input_args->count * input_args->dtype->super.size;
/* initialize the counter */
int *iteration = &ptpcoll_module->ml_mem.ml_buf_desc[buffer_index].iteration;
#if 0
fprintf(stderr,"%d: entering p2p allgather progress AR: %d iter: %d\n",my_group_index,*active_requests,
*iteration);
#endif
/* keep tag within the limit supported by the pml */
tag = (PTPCOLL_TAG_OFFSET + input_args->sequence_num * PTPCOLL_TAG_FACTOR) & (ptpcoll_module->tag_mask);
/* mark this as a collective tag, to avoid conflict with user-level flags */
tag = -tag;
/* k-nomial tree parameters */
tree_order = exchange_node->tree_order;
pow_k = exchange_node->log_tree_order;
/* let's begin the collective, starting with extra ranks and their
* respective proxies
*/
if( EXTRA_NODE == exchange_node->node_type ) {
/* debug print */
/*fprintf(stderr,"666 \n");*/
/* simply poll for completion */
completed = 0;
/* polling internally */
completed = mca_bcol_ptpcoll_test_all_for_match(active_requests, requests, &rc);
if(completed){
/* go to buffer release */
goto FINISHED;
}else{
/* save state and hop out
* nothing to save here
*/
return ((OMPI_SUCCESS != rc) ? OMPI_ERROR : BCOL_FN_STARTED);
}
}else if ( 0 < exchange_node->n_extra_sources && (-1 == *iteration)) {
/* I am a proxy for someone */
/* Simply poll for completion */
completed = 0;
/* polling internally */
assert( 1 == *active_requests);
completed = mca_bcol_ptpcoll_test_all_for_match(active_requests, requests, &rc);
if(!completed){
/* save state and hop out
* We really do need to block here so set
* the iteration to -1 indicating we need to
* finish this part first
*/
(*iteration) = -1;
return ((OMPI_SUCCESS != rc) ? OMPI_ERROR : BCOL_FN_STARTED);
}
/* I may now proceed to the recursive k - ing phase */
*iteration = 0;
}
/* the ordering here between the extra rank and progress active requests
* is critical
*/
/* extra rank */
if( (pow_k + 1) == *iteration ){
/* finish off the last one */
goto PROGRESS_EXTRA;
}
/* active requests must be completed before continuing on to
* recursive k -ing step
* CAREFUL HERE, IT THIS REALLY WHAT YOU WANT??
*/
if( 0 < (*active_requests) ) {
/* then we have something to progress from last step */
/* debug print */
/*
fprintf(stderr,"%d: entering progress AR: %d iter: %d\n",my_group_index,*active_requests,
*iteration);
*/
completed = 0;
completed = mca_bcol_ptpcoll_test_all_for_match(active_requests, requests, &rc);
if(!completed){
/* save state and hop out
* state hasn't changed
*/
return ((MPI_SUCCESS != rc) ? OMPI_ERROR : BCOL_FN_STARTED);
}
++(*iteration);
}
/* we start the recursive k - ing phase */
for( i = *iteration; i < pow_k; i++) {
/* nothing changes here */
for(j = 0; j < (tree_order - 1); j++) {
/* send phase */
dst = exchange_node->rank_exchanges[i][j];
if( dst < 0 ){
continue;
}
comm_dst = group_list[dst];
send_offset = exchange_node->payload_info[i][j].s_offset * pack_len;
send_len = exchange_node->payload_info[i][j].s_len * pack_len;
rc = MCA_PML_CALL(isend((void*)((unsigned char *) data_buffer +
send_offset),
send_len,
MPI_BYTE,
comm_dst, tag,
MCA_PML_BASE_SEND_STANDARD, comm,
&(requests[*active_requests])));
if( OMPI_SUCCESS != rc ) {
PTPCOLL_VERBOSE(10,("Failed to isend data"));
return OMPI_ERROR;
}
++(*active_requests);
/* sends are posted */
}
/* Now post the recv's */
for( j = 0; j < (tree_order - 1); j++ ) {
/* recv phase */
src = exchange_node->rank_exchanges[i][j];
if( src < 0 ) {
continue;
}
comm_src = group_list[src];
recv_offset = exchange_node->payload_info[i][j].r_offset * pack_len;
recv_len = exchange_node->payload_info[i][j].r_len * pack_len;
/* post the receive */
rc = MCA_PML_CALL(irecv((void *) ((unsigned char *) data_buffer +
recv_offset),
recv_len,
MPI_BYTE,
comm_src,
tag, comm, &(requests[*active_requests])));
if( OMPI_SUCCESS != rc ) {
PTPCOLL_VERBOSE(10, ("Failed to post ireceive "));
return OMPI_ERROR;
}
++(*active_requests);
}
/* finished all send/recv's now poll for completion before
* continuing to next iteration
*/
completed = 0;
/* make this non-blocking */
completed = mca_bcol_ptpcoll_test_all_for_match(active_requests, requests, &rc);
if(!completed){
/* save state and hop out
* We really do need to block here so set
* the iteration to -1 indicating we need to
* finish this part first
*/
*iteration = i; /* need to pick up here */
return ((OMPI_SUCCESS != rc) ? OMPI_ERROR : BCOL_FN_STARTED);
}
}
/* finish off the last piece, send the data back to the extra */
if( 0 < exchange_node->n_extra_sources ) {
dst = exchange_node->rank_extra_sources_array[0];
comm_dst = group_list[dst];
knt = 0;
for( i = 0; i < group_size; i++){
knt += list_connected[i];
}
rc = MCA_PML_CALL(isend(data_buffer,
pack_len * knt,
MPI_BYTE,
comm_dst, tag,
MCA_PML_BASE_SEND_STANDARD, comm,
&(requests[*active_requests])));
if( OMPI_SUCCESS != rc ) {
PTPCOLL_VERBOSE(10,("Failed to isend data"));
return OMPI_ERROR;
}
++(*active_requests);
/* probe for send completion */
completed = 0;
/* make this non-blocking */
completed = mca_bcol_ptpcoll_test_all_for_match(active_requests, requests, &rc);
if(!completed){
/* save state and hop out
* We really do need to block here so set
* the iteration to pow_k +1 indicating we need to
* finish progressing the last part
*/
*iteration = pow_k + 1;
return ((OMPI_SUCCESS != rc) ? OMPI_ERROR : BCOL_FN_STARTED);
}
}
/* folks need to skip this unless they really are the proxy
* reentering with the intent of progressing the final send
*/
goto FINISHED;
PROGRESS_EXTRA:
/* probe for send completion */
completed = 0;
/* make this non-blocking */
completed = mca_bcol_ptpcoll_test_all_for_match(active_requests, requests, &rc);
if(!completed){
/* save state and hop out
* We really do need to block here so set
* the iteration to pow_k +1 indicating we need to
* finish progressing the last part
*/
return ((OMPI_SUCCESS != rc) ? OMPI_ERROR : BCOL_FN_STARTED);
}
FINISHED:
/* recycle buffer if need be */
return BCOL_FN_COMPLETE;
}
/*
* Register allreduce functions to the BCOL function table,
* so they can be selected
*/
int bcol_ptpcoll_allgather_init(mca_bcol_base_module_t *super)
{
mca_bcol_base_coll_fn_comm_attributes_t comm_attribs;
mca_bcol_base_coll_fn_invoke_attributes_t inv_attribs;
comm_attribs.bcoll_type = BCOL_ALLGATHER;
comm_attribs.comm_size_min = 0;
comm_attribs.comm_size_max = 1024 * 1024;
comm_attribs.waiting_semantics = NON_BLOCKING;
inv_attribs.bcol_msg_min = 0;
inv_attribs.bcol_msg_max = 20000; /* range 1 */
inv_attribs.datatype_bitmap = 0xffffffff;
inv_attribs.op_types_bitmap = 0xffffffff;
comm_attribs.data_src = DATA_SRC_KNOWN;
mca_bcol_base_set_attributes(super, &comm_attribs, &inv_attribs,
bcol_ptpcoll_k_nomial_allgather_init,
bcol_ptpcoll_k_nomial_allgather_progress);
comm_attribs.data_src = DATA_SRC_KNOWN;
inv_attribs.bcol_msg_min = 10000000;
inv_attribs.bcol_msg_max = 10485760; /* range 4 */
mca_bcol_base_set_attributes(super, &comm_attribs, &inv_attribs,
bcol_ptpcoll_k_nomial_allgather_init,
bcol_ptpcoll_k_nomial_allgather_progress);
return OMPI_SUCCESS;
}
|
618314.c | /*
+----------------------------------------------------------------------+
| PHP Version 7 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2015 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 |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Edin Kadribasic <[email protected]> |
| Ilia Alshanestsky <[email protected]> |
| Wez Furlong <[email protected]> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "pdo/php_pdo.h"
#include "pdo/php_pdo_driver.h"
#include "php_pdo_pgsql.h"
#include "php_pdo_pgsql_int.h"
#if HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
/* from postgresql/src/include/catalog/pg_type.h */
#define BOOLOID 16
#define BYTEAOID 17
#define INT8OID 20
#define INT2OID 21
#define INT4OID 23
#define TEXTOID 25
#define OIDOID 26
static int pgsql_stmt_dtor(pdo_stmt_t *stmt)
{
pdo_pgsql_stmt *S = (pdo_pgsql_stmt*)stmt->driver_data;
if (S->result) {
/* free the resource */
PQclear(S->result);
S->result = NULL;
}
if (S->stmt_name) {
pdo_pgsql_db_handle *H = S->H;
char *q = NULL;
PGresult *res;
if (S->is_prepared) {
spprintf(&q, 0, "DEALLOCATE %s", S->stmt_name);
res = PQexec(H->server, q);
efree(q);
if (res) {
PQclear(res);
}
}
efree(S->stmt_name);
S->stmt_name = NULL;
}
if (S->param_lengths) {
efree(S->param_lengths);
S->param_lengths = NULL;
}
if (S->param_values) {
efree(S->param_values);
S->param_values = NULL;
}
if (S->param_formats) {
efree(S->param_formats);
S->param_formats = NULL;
}
if (S->param_types) {
efree(S->param_types);
S->param_types = NULL;
}
if (S->query) {
efree(S->query);
S->query = NULL;
}
if (S->cursor_name) {
pdo_pgsql_db_handle *H = S->H;
char *q = NULL;
PGresult *res;
spprintf(&q, 0, "CLOSE %s", S->cursor_name);
res = PQexec(H->server, q);
efree(q);
if (res) PQclear(res);
efree(S->cursor_name);
S->cursor_name = NULL;
}
if(S->cols) {
efree(S->cols);
S->cols = NULL;
}
efree(S);
stmt->driver_data = NULL;
return 1;
}
static int pgsql_stmt_execute(pdo_stmt_t *stmt)
{
pdo_pgsql_stmt *S = (pdo_pgsql_stmt*)stmt->driver_data;
pdo_pgsql_db_handle *H = S->H;
ExecStatusType status;
/* ensure that we free any previous unfetched results */
if(S->result) {
PQclear(S->result);
S->result = NULL;
}
S->current_row = 0;
if (S->cursor_name) {
char *q = NULL;
if (S->is_prepared) {
spprintf(&q, 0, "CLOSE %s", S->cursor_name);
S->result = PQexec(H->server, q);
efree(q);
}
spprintf(&q, 0, "DECLARE %s SCROLL CURSOR WITH HOLD FOR %s", S->cursor_name, stmt->active_query_string);
S->result = PQexec(H->server, q);
efree(q);
/* check if declare failed */
status = PQresultStatus(S->result);
if (status != PGRES_COMMAND_OK && status != PGRES_TUPLES_OK) {
pdo_pgsql_error_stmt(stmt, status, pdo_pgsql_sqlstate(S->result));
return 0;
}
/* the cursor was declared correctly */
S->is_prepared = 1;
/* fetch to be able to get the number of tuples later, but don't advance the cursor pointer */
spprintf(&q, 0, "FETCH FORWARD 0 FROM %s", S->cursor_name);
S->result = PQexec(H->server, q);
efree(q);
} else if (S->stmt_name) {
/* using a prepared statement */
if (!S->is_prepared) {
stmt_retry:
/* we deferred the prepare until now, because we didn't
* know anything about the parameter types; now we do */
S->result = PQprepare(H->server, S->stmt_name, S->query,
stmt->bound_params ? zend_hash_num_elements(stmt->bound_params) : 0,
S->param_types);
status = PQresultStatus(S->result);
switch (status) {
case PGRES_COMMAND_OK:
case PGRES_TUPLES_OK:
/* it worked */
S->is_prepared = 1;
PQclear(S->result);
break;
default: {
char *sqlstate = pdo_pgsql_sqlstate(S->result);
/* 42P05 means that the prepared statement already existed. this can happen if you use
* a connection pooling software line pgpool which doesn't close the db-connection once
* php disconnects. if php dies (no chance to run RSHUTDOWN) during execution it has no
* chance to DEALLOCATE the prepared statements it has created. so, if we hit a 42P05 we
* deallocate it and retry ONCE (thies 2005.12.15)
*/
if (sqlstate && !strcmp(sqlstate, "42P05")) {
char buf[100]; /* stmt_name == "pdo_crsr_%08x" */
PGresult *res;
snprintf(buf, sizeof(buf), "DEALLOCATE %s", S->stmt_name);
res = PQexec(H->server, buf);
if (res) {
PQclear(res);
}
goto stmt_retry;
} else {
pdo_pgsql_error_stmt(stmt, status, sqlstate);
return 0;
}
}
}
}
S->result = PQexecPrepared(H->server, S->stmt_name,
stmt->bound_params ?
zend_hash_num_elements(stmt->bound_params) :
0,
(const char**)S->param_values,
S->param_lengths,
S->param_formats,
0);
} else if (stmt->supports_placeholders == PDO_PLACEHOLDER_NAMED) {
/* execute query with parameters */
S->result = PQexecParams(H->server, S->query,
stmt->bound_params ? zend_hash_num_elements(stmt->bound_params) : 0,
S->param_types,
(const char**)S->param_values,
S->param_lengths,
S->param_formats,
0);
} else {
/* execute plain query (with embedded parameters) */
S->result = PQexec(H->server, stmt->active_query_string);
}
status = PQresultStatus(S->result);
if (status != PGRES_COMMAND_OK && status != PGRES_TUPLES_OK) {
pdo_pgsql_error_stmt(stmt, status, pdo_pgsql_sqlstate(S->result));
return 0;
}
if (!stmt->executed && (!stmt->column_count || S->cols == NULL)) {
stmt->column_count = (int) PQnfields(S->result);
S->cols = ecalloc(stmt->column_count, sizeof(pdo_pgsql_column));
}
if (status == PGRES_COMMAND_OK) {
ZEND_ATOL(stmt->row_count, PQcmdTuples(S->result));
H->pgoid = PQoidValue(S->result);
} else {
stmt->row_count = (zend_long)PQntuples(S->result);
}
return 1;
}
static int pgsql_stmt_param_hook(pdo_stmt_t *stmt, struct pdo_bound_param_data *param,
enum pdo_param_event event_type)
{
pdo_pgsql_stmt *S = (pdo_pgsql_stmt*)stmt->driver_data;
if (stmt->supports_placeholders == PDO_PLACEHOLDER_NAMED && param->is_param) {
switch (event_type) {
case PDO_PARAM_EVT_FREE:
if (param->driver_data) {
efree(param->driver_data);
}
break;
case PDO_PARAM_EVT_NORMALIZE:
/* decode name from $1, $2 into 0, 1 etc. */
if (param->name) {
if (ZSTR_VAL(param->name)[0] == '$') {
ZEND_ATOL(param->paramno, ZSTR_VAL(param->name) + 1);
} else {
/* resolve parameter name to rewritten name */
char *namevar;
if (stmt->bound_param_map && (namevar = zend_hash_find_ptr(stmt->bound_param_map,
param->name)) != NULL) {
ZEND_ATOL(param->paramno, namevar + 1);
param->paramno--;
} else {
pdo_raise_impl_error(stmt->dbh, stmt, "HY093", ZSTR_VAL(param->name));
return 0;
}
}
}
break;
case PDO_PARAM_EVT_ALLOC:
case PDO_PARAM_EVT_EXEC_POST:
case PDO_PARAM_EVT_FETCH_PRE:
case PDO_PARAM_EVT_FETCH_POST:
/* work is handled by EVT_NORMALIZE */
return 1;
case PDO_PARAM_EVT_EXEC_PRE:
if (!stmt->bound_param_map) {
return 0;
}
if (!S->param_values) {
S->param_values = ecalloc(
zend_hash_num_elements(stmt->bound_param_map),
sizeof(char*));
S->param_lengths = ecalloc(
zend_hash_num_elements(stmt->bound_param_map),
sizeof(int));
S->param_formats = ecalloc(
zend_hash_num_elements(stmt->bound_param_map),
sizeof(int));
S->param_types = ecalloc(
zend_hash_num_elements(stmt->bound_param_map),
sizeof(Oid));
}
if (param->paramno >= 0) {
zval *parameter;
if (param->paramno >= zend_hash_num_elements(stmt->bound_params)) {
pdo_raise_impl_error(stmt->dbh, stmt, "HY093", "parameter was not defined");
return 0;
}
if (Z_ISREF(param->parameter)) {
parameter = Z_REFVAL(param->parameter);
} else {
parameter = ¶m->parameter;
}
if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_LOB &&
Z_TYPE_P(parameter) == IS_RESOURCE) {
php_stream *stm;
php_stream_from_zval_no_verify(stm, parameter);
if (stm) {
if (php_stream_is(stm, &pdo_pgsql_lob_stream_ops)) {
struct pdo_pgsql_lob_self *self = (struct pdo_pgsql_lob_self*)stm->abstract;
pdo_pgsql_bound_param *P = param->driver_data;
if (P == NULL) {
P = ecalloc(1, sizeof(*P));
param->driver_data = P;
}
P->oid = htonl(self->oid);
S->param_values[param->paramno] = (char*)&P->oid;
S->param_lengths[param->paramno] = sizeof(P->oid);
S->param_formats[param->paramno] = 1;
S->param_types[param->paramno] = OIDOID;
return 1;
} else {
zend_string *str = php_stream_copy_to_mem(stm, PHP_STREAM_COPY_ALL, 0);
if (str != NULL) {
//??SEPARATE_ZVAL_IF_NOT_REF(¶m->parameter);
ZVAL_STR(parameter, str);
} else {
ZVAL_EMPTY_STRING(parameter);
}
}
} else {
/* expected a stream resource */
pdo_pgsql_error_stmt(stmt, PGRES_FATAL_ERROR, "HY105");
return 0;
}
}
if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_NULL ||
Z_TYPE_P(parameter) == IS_NULL) {
S->param_values[param->paramno] = NULL;
S->param_lengths[param->paramno] = 0;
} else if (Z_TYPE_P(parameter) == IS_FALSE || Z_TYPE_P(parameter) == IS_TRUE) {
S->param_values[param->paramno] = Z_TYPE_P(parameter) == IS_TRUE ? "t" : "f";
S->param_lengths[param->paramno] = 1;
S->param_formats[param->paramno] = 0;
} else {
//SEPARATE_ZVAL_IF_NOT_REF(¶m->parameter);
convert_to_string_ex(parameter);
S->param_values[param->paramno] = Z_STRVAL_P(parameter);
S->param_lengths[param->paramno] = Z_STRLEN_P(parameter);
S->param_formats[param->paramno] = 0;
}
if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_LOB) {
S->param_types[param->paramno] = 0;
S->param_formats[param->paramno] = 1;
} else {
S->param_types[param->paramno] = 0;
}
}
break;
}
} else if (param->is_param) {
/* We need to manually convert to a pg native boolean value */
if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_BOOL &&
((param->param_type & PDO_PARAM_INPUT_OUTPUT) != PDO_PARAM_INPUT_OUTPUT)) {
SEPARATE_ZVAL(¶m->parameter);
param->param_type = PDO_PARAM_STR;
convert_to_boolean(¶m->parameter);
ZVAL_STRINGL(¶m->parameter, Z_TYPE_P(¶m->parameter) == IS_TRUE ? "t" : "f", 1);
}
}
return 1;
}
static int pgsql_stmt_fetch(pdo_stmt_t *stmt,
enum pdo_fetch_orientation ori, zend_long offset)
{
pdo_pgsql_stmt *S = (pdo_pgsql_stmt*)stmt->driver_data;
if (S->cursor_name) {
char *ori_str = NULL;
char *q = NULL;
ExecStatusType status;
switch (ori) {
case PDO_FETCH_ORI_NEXT: spprintf(&ori_str, 0, "NEXT"); break;
case PDO_FETCH_ORI_PRIOR: spprintf(&ori_str, 0, "BACKWARD"); break;
case PDO_FETCH_ORI_FIRST: spprintf(&ori_str, 0, "FIRST"); break;
case PDO_FETCH_ORI_LAST: spprintf(&ori_str, 0, "LAST"); break;
case PDO_FETCH_ORI_ABS: spprintf(&ori_str, 0, "ABSOLUTE %pd", offset); break;
case PDO_FETCH_ORI_REL: spprintf(&ori_str, 0, "RELATIVE %pd", offset); break;
default:
return 0;
}
spprintf(&q, 0, "FETCH %s FROM %s", ori_str, S->cursor_name);
efree(ori_str);
S->result = PQexec(S->H->server, q);
efree(q);
status = PQresultStatus(S->result);
if (status != PGRES_COMMAND_OK && status != PGRES_TUPLES_OK) {
pdo_pgsql_error_stmt(stmt, status, pdo_pgsql_sqlstate(S->result));
return 0;
}
if (PQntuples(S->result)) {
S->current_row = 1;
return 1;
} else {
return 0;
}
} else {
if (S->current_row < stmt->row_count) {
S->current_row++;
return 1;
} else {
return 0;
}
}
}
static int pgsql_stmt_describe(pdo_stmt_t *stmt, int colno)
{
pdo_pgsql_stmt *S = (pdo_pgsql_stmt*)stmt->driver_data;
struct pdo_column_data *cols = stmt->columns;
struct pdo_bound_param_data *param;
char *str;
if (!S->result) {
return 0;
}
str = PQfname(S->result, colno);
cols[colno].name = zend_string_init(str, strlen(str), 0);
cols[colno].maxlen = PQfsize(S->result, colno);
cols[colno].precision = PQfmod(S->result, colno);
S->cols[colno].pgsql_type = PQftype(S->result, colno);
switch (S->cols[colno].pgsql_type) {
case BOOLOID:
cols[colno].param_type = PDO_PARAM_BOOL;
break;
case OIDOID:
/* did the user bind the column as a LOB ? */
if (stmt->bound_columns && (
(param = zend_hash_index_find_ptr(stmt->bound_columns, colno)) != NULL ||
(param = zend_hash_find_ptr(stmt->bound_columns, cols[colno].name)) != NULL)) {
if (PDO_PARAM_TYPE(param->param_type) == PDO_PARAM_LOB) {
cols[colno].param_type = PDO_PARAM_LOB;
break;
}
}
cols[colno].param_type = PDO_PARAM_INT;
break;
case INT2OID:
case INT4OID:
cols[colno].param_type = PDO_PARAM_INT;
break;
case INT8OID:
if (sizeof(zend_long)>=8) {
cols[colno].param_type = PDO_PARAM_INT;
} else {
cols[colno].param_type = PDO_PARAM_STR;
}
break;
case BYTEAOID:
cols[colno].param_type = PDO_PARAM_LOB;
break;
default:
cols[colno].param_type = PDO_PARAM_STR;
}
return 1;
}
static int pgsql_stmt_get_col(pdo_stmt_t *stmt, int colno, char **ptr, zend_ulong *len, int *caller_frees )
{
pdo_pgsql_stmt *S = (pdo_pgsql_stmt*)stmt->driver_data;
struct pdo_column_data *cols = stmt->columns;
size_t tmp_len;
if (!S->result) {
return 0;
}
/* We have already increased count by 1 in pgsql_stmt_fetch() */
if (PQgetisnull(S->result, S->current_row - 1, colno)) { /* Check if we got NULL */
*ptr = NULL;
*len = 0;
} else {
*ptr = PQgetvalue(S->result, S->current_row - 1, colno);
*len = PQgetlength(S->result, S->current_row - 1, colno);
switch (cols[colno].param_type) {
case PDO_PARAM_INT:
ZEND_ATOL(S->cols[colno].intval, *ptr);
*ptr = (char *) &(S->cols[colno].intval);
*len = sizeof(zend_long);
break;
case PDO_PARAM_BOOL:
S->cols[colno].boolval = **ptr == 't' ? 1: 0;
*ptr = (char *) &(S->cols[colno].boolval);
*len = sizeof(zend_bool);
break;
case PDO_PARAM_LOB:
if (S->cols[colno].pgsql_type == OIDOID) {
/* ooo, a real large object */
char *end_ptr;
Oid oid = (Oid)strtoul(*ptr, &end_ptr, 10);
int loid = lo_open(S->H->server, oid, INV_READ);
if (loid >= 0) {
*ptr = (char*)pdo_pgsql_create_lob_stream(&stmt->database_object_handle, loid, oid);
*len = 0;
return *ptr ? 1 : 0;
}
*ptr = NULL;
*len = 0;
return 0;
} else {
char *tmp_ptr = (char *)PQunescapeBytea((unsigned char *)*ptr, &tmp_len);
if (!tmp_ptr) {
/* PQunescapeBytea returned an error */
*len = 0;
return 0;
}
if (!tmp_len) {
/* Empty string, return as empty stream */
*ptr = (char *)php_stream_memory_open(TEMP_STREAM_READONLY, "", 0);
PQfreemem(tmp_ptr);
*len = 0;
} else {
*ptr = estrndup(tmp_ptr, tmp_len);
PQfreemem(tmp_ptr);
*len = tmp_len;
*caller_frees = 1;
}
}
break;
case PDO_PARAM_NULL:
case PDO_PARAM_STR:
case PDO_PARAM_STMT:
case PDO_PARAM_INPUT_OUTPUT:
case PDO_PARAM_ZVAL:
default:
break;
}
}
return 1;
}
static int pgsql_stmt_get_column_meta(pdo_stmt_t *stmt, zend_long colno, zval *return_value)
{
pdo_pgsql_stmt *S = (pdo_pgsql_stmt*)stmt->driver_data;
PGresult *res;
char *q=NULL;
ExecStatusType status;
if (!S->result) {
return FAILURE;
}
if (colno >= stmt->column_count) {
return FAILURE;
}
array_init(return_value);
add_assoc_long(return_value, "pgsql:oid", S->cols[colno].pgsql_type);
/* Fetch metadata from Postgres system catalogue */
spprintf(&q, 0, "SELECT TYPNAME FROM PG_TYPE WHERE OID=%u", S->cols[colno].pgsql_type);
res = PQexec(S->H->server, q);
efree(q);
status = PQresultStatus(res);
if (status != PGRES_TUPLES_OK) {
/* Failed to get system catalogue, but return success
* with the data we have collected so far
*/
goto done;
}
/* We want exactly one row returned */
if (1 != PQntuples(res)) {
goto done;
}
add_assoc_string(return_value, "native_type", PQgetvalue(res, 0, 0));
done:
PQclear(res);
return 1;
}
static int pdo_pgsql_stmt_cursor_closer(pdo_stmt_t *stmt)
{
pdo_pgsql_stmt *S = (pdo_pgsql_stmt*)stmt->driver_data;
if (S->cols != NULL){
efree(S->cols);
S->cols = NULL;
}
return 1;
}
struct pdo_stmt_methods pgsql_stmt_methods = {
pgsql_stmt_dtor,
pgsql_stmt_execute,
pgsql_stmt_fetch,
pgsql_stmt_describe,
pgsql_stmt_get_col,
pgsql_stmt_param_hook,
NULL, /* set_attr */
NULL, /* get_attr */
pgsql_stmt_get_column_meta,
NULL, /* next_rowset */
pdo_pgsql_stmt_cursor_closer
};
/*
* 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
*/
|
130359.c | /*
* Copyright (c) 2015-2018 The DragonFly Project. All rights reserved.
*
* This code is derived from software contributed to The DragonFly Project
* by Matthew Dillon <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name of The DragonFly Project 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 HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* This module implements the hammer2 helper thread API, including
* the frontend/backend XOP API.
*/
#include "hammer2.h"
#define H2XOPDESCRIPTOR(label) \
hammer2_xop_desc_t hammer2_##label##_desc = { \
.storage_func = hammer2_xop_##label, \
.id = #label \
}
H2XOPDESCRIPTOR(ipcluster);
H2XOPDESCRIPTOR(readdir);
H2XOPDESCRIPTOR(nresolve);
H2XOPDESCRIPTOR(unlink);
H2XOPDESCRIPTOR(nrename);
H2XOPDESCRIPTOR(scanlhc);
H2XOPDESCRIPTOR(scanall);
H2XOPDESCRIPTOR(lookup);
H2XOPDESCRIPTOR(delete);
H2XOPDESCRIPTOR(inode_mkdirent);
H2XOPDESCRIPTOR(inode_create);
H2XOPDESCRIPTOR(inode_create_det);
H2XOPDESCRIPTOR(inode_create_ins);
H2XOPDESCRIPTOR(inode_destroy);
H2XOPDESCRIPTOR(inode_chain_sync);
H2XOPDESCRIPTOR(inode_unlinkall);
H2XOPDESCRIPTOR(inode_connect);
H2XOPDESCRIPTOR(inode_flush);
H2XOPDESCRIPTOR(strategy_read);
H2XOPDESCRIPTOR(strategy_write);
/*
* Set flags and wakeup any waiters.
*
* WARNING! During teardown (thr) can disappear the instant our cmpset
* succeeds.
*/
void
hammer2_thr_signal(hammer2_thread_t *thr, uint32_t flags)
{
uint32_t oflags;
uint32_t nflags;
for (;;) {
oflags = thr->flags;
cpu_ccfence();
nflags = (oflags | flags) & ~HAMMER2_THREAD_WAITING;
if (oflags & HAMMER2_THREAD_WAITING) {
if (atomic_cmpset_int(&thr->flags, oflags, nflags)) {
wakeup(&thr->flags);
break;
}
} else {
if (atomic_cmpset_int(&thr->flags, oflags, nflags))
break;
}
}
}
/*
* Set and clear flags and wakeup any waiters.
*
* WARNING! During teardown (thr) can disappear the instant our cmpset
* succeeds.
*/
void
hammer2_thr_signal2(hammer2_thread_t *thr, uint32_t posflags, uint32_t negflags)
{
uint32_t oflags;
uint32_t nflags;
for (;;) {
oflags = thr->flags;
cpu_ccfence();
nflags = (oflags | posflags) &
~(negflags | HAMMER2_THREAD_WAITING);
if (oflags & HAMMER2_THREAD_WAITING) {
if (atomic_cmpset_int(&thr->flags, oflags, nflags)) {
wakeup(&thr->flags);
break;
}
} else {
if (atomic_cmpset_int(&thr->flags, oflags, nflags))
break;
}
}
}
/*
* Wait until all the bits in flags are set.
*
* WARNING! During teardown (thr) can disappear the instant our cmpset
* succeeds.
*/
void
hammer2_thr_wait(hammer2_thread_t *thr, uint32_t flags)
{
uint32_t oflags;
uint32_t nflags;
for (;;) {
oflags = thr->flags;
cpu_ccfence();
if ((oflags & flags) == flags)
break;
nflags = oflags | HAMMER2_THREAD_WAITING;
tsleep_interlock(&thr->flags, 0);
if (atomic_cmpset_int(&thr->flags, oflags, nflags)) {
tsleep(&thr->flags, PINTERLOCKED, "h2twait", hz*60);
}
}
}
/*
* Wait until any of the bits in flags are set, with timeout.
*
* WARNING! During teardown (thr) can disappear the instant our cmpset
* succeeds.
*/
int
hammer2_thr_wait_any(hammer2_thread_t *thr, uint32_t flags, int timo)
{
uint32_t oflags;
uint32_t nflags;
int error;
error = 0;
for (;;) {
oflags = thr->flags;
cpu_ccfence();
if (oflags & flags)
break;
nflags = oflags | HAMMER2_THREAD_WAITING;
tsleep_interlock(&thr->flags, 0);
if (atomic_cmpset_int(&thr->flags, oflags, nflags)) {
error = tsleep(&thr->flags, PINTERLOCKED,
"h2twait", timo);
}
if (error == ETIMEDOUT) {
error = HAMMER2_ERROR_ETIMEDOUT;
break;
}
}
return error;
}
/*
* Wait until the bits in flags are clear.
*
* WARNING! During teardown (thr) can disappear the instant our cmpset
* succeeds.
*/
void
hammer2_thr_wait_neg(hammer2_thread_t *thr, uint32_t flags)
{
uint32_t oflags;
uint32_t nflags;
for (;;) {
oflags = thr->flags;
cpu_ccfence();
if ((oflags & flags) == 0)
break;
nflags = oflags | HAMMER2_THREAD_WAITING;
tsleep_interlock(&thr->flags, 0);
if (atomic_cmpset_int(&thr->flags, oflags, nflags)) {
tsleep(&thr->flags, PINTERLOCKED, "h2twait", hz*60);
}
}
}
/*
* Initialize the supplied thread structure, starting the specified
* thread.
*
* NOTE: thr structure can be retained across mounts and unmounts for this
* pmp, so make sure the flags are in a sane state.
*/
void
hammer2_thr_create(hammer2_thread_t *thr, hammer2_pfs_t *pmp,
hammer2_dev_t *hmp,
const char *id, int clindex, int repidx,
void (*func)(void *arg))
{
thr->pmp = pmp; /* xop helpers */
thr->hmp = hmp; /* bulkfree */
thr->clindex = clindex;
thr->repidx = repidx;
TAILQ_INIT(&thr->xopq);
atomic_clear_int(&thr->flags, HAMMER2_THREAD_STOP |
HAMMER2_THREAD_STOPPED |
HAMMER2_THREAD_FREEZE |
HAMMER2_THREAD_FROZEN);
if (thr->scratch == NULL)
thr->scratch = kmalloc(MAXPHYS, M_HAMMER2, M_WAITOK | M_ZERO);
if (repidx >= 0) {
lwkt_create(func, thr, &thr->td, NULL, 0, repidx % ncpus,
"%s-%s.%02d", id, pmp->pfs_names[clindex], repidx);
} else if (pmp) {
lwkt_create(func, thr, &thr->td, NULL, 0, -1,
"%s-%s", id, pmp->pfs_names[clindex]);
} else {
lwkt_create(func, thr, &thr->td, NULL, 0, -1, "%s", id);
}
}
/*
* Terminate a thread. This function will silently return if the thread
* was never initialized or has already been deleted.
*
* This is accomplished by setting the STOP flag and waiting for the td
* structure to become NULL.
*/
void
hammer2_thr_delete(hammer2_thread_t *thr)
{
if (thr->td == NULL)
return;
hammer2_thr_signal(thr, HAMMER2_THREAD_STOP);
hammer2_thr_wait(thr, HAMMER2_THREAD_STOPPED);
thr->pmp = NULL;
if (thr->scratch) {
kfree(thr->scratch, M_HAMMER2);
thr->scratch = NULL;
}
KKASSERT(TAILQ_EMPTY(&thr->xopq));
}
/*
* Asynchronous remaster request. Ask the synchronization thread to
* start over soon (as if it were frozen and unfrozen, but without waiting).
* The thread always recalculates mastership relationships when restarting.
*/
void
hammer2_thr_remaster(hammer2_thread_t *thr)
{
if (thr->td == NULL)
return;
hammer2_thr_signal(thr, HAMMER2_THREAD_REMASTER);
}
void
hammer2_thr_freeze_async(hammer2_thread_t *thr)
{
hammer2_thr_signal(thr, HAMMER2_THREAD_FREEZE);
}
void
hammer2_thr_freeze(hammer2_thread_t *thr)
{
if (thr->td == NULL)
return;
hammer2_thr_signal(thr, HAMMER2_THREAD_FREEZE);
hammer2_thr_wait(thr, HAMMER2_THREAD_FROZEN);
}
void
hammer2_thr_unfreeze(hammer2_thread_t *thr)
{
if (thr->td == NULL)
return;
hammer2_thr_signal(thr, HAMMER2_THREAD_UNFREEZE);
hammer2_thr_wait_neg(thr, HAMMER2_THREAD_FROZEN);
}
int
hammer2_thr_break(hammer2_thread_t *thr)
{
if (thr->flags & (HAMMER2_THREAD_STOP |
HAMMER2_THREAD_REMASTER |
HAMMER2_THREAD_FREEZE)) {
return 1;
}
return 0;
}
/****************************************************************************
* HAMMER2 XOPS API *
****************************************************************************/
/*
* Allocate a XOP request.
*
* Once allocated a XOP request can be started, collected, and retired,
* and can be retired early if desired.
*
* NOTE: Fifo indices might not be zero but ri == wi on objcache_get().
*/
void *
hammer2_xop_alloc(hammer2_inode_t *ip, int flags)
{
hammer2_xop_t *xop;
xop = objcache_get(cache_xops, M_WAITOK);
KKASSERT(xop->head.cluster.array[0].chain == NULL);
xop->head.ip1 = ip;
xop->head.desc = NULL;
xop->head.flags = flags;
xop->head.state = 0;
xop->head.error = 0;
xop->head.collect_key = 0;
xop->head.focus_dio = NULL;
if (flags & HAMMER2_XOP_MODIFYING)
xop->head.mtid = hammer2_trans_sub(ip->pmp);
else
xop->head.mtid = 0;
xop->head.cluster.nchains = ip->cluster.nchains;
xop->head.cluster.pmp = ip->pmp;
xop->head.cluster.flags = HAMMER2_CLUSTER_LOCKED;
/*
* run_mask - Active thread (or frontend) associated with XOP
*/
xop->head.run_mask = HAMMER2_XOPMASK_VOP;
hammer2_inode_ref(ip);
return xop;
}
void
hammer2_xop_setname(hammer2_xop_head_t *xop, const char *name, size_t name_len)
{
xop->name1 = kmalloc(name_len + 1, M_HAMMER2, M_WAITOK | M_ZERO);
xop->name1_len = name_len;
bcopy(name, xop->name1, name_len);
}
void
hammer2_xop_setname2(hammer2_xop_head_t *xop, const char *name, size_t name_len)
{
xop->name2 = kmalloc(name_len + 1, M_HAMMER2, M_WAITOK | M_ZERO);
xop->name2_len = name_len;
bcopy(name, xop->name2, name_len);
}
size_t
hammer2_xop_setname_inum(hammer2_xop_head_t *xop, hammer2_key_t inum)
{
const size_t name_len = 18;
xop->name1 = kmalloc(name_len + 1, M_HAMMER2, M_WAITOK | M_ZERO);
xop->name1_len = name_len;
ksnprintf(xop->name1, name_len + 1, "0x%016jx", (intmax_t)inum);
return name_len;
}
void
hammer2_xop_setip2(hammer2_xop_head_t *xop, hammer2_inode_t *ip2)
{
xop->ip2 = ip2;
hammer2_inode_ref(ip2);
}
void
hammer2_xop_setip3(hammer2_xop_head_t *xop, hammer2_inode_t *ip3)
{
xop->ip3 = ip3;
hammer2_inode_ref(ip3);
}
void
hammer2_xop_setip4(hammer2_xop_head_t *xop, hammer2_inode_t *ip4)
{
xop->ip4 = ip4;
hammer2_inode_ref(ip4);
}
void
hammer2_xop_reinit(hammer2_xop_head_t *xop)
{
xop->state = 0;
xop->error = 0;
xop->collect_key = 0;
xop->run_mask = HAMMER2_XOPMASK_VOP;
}
/*
* A mounted PFS needs Xops threads to support frontend operations.
*/
void
hammer2_xop_helper_create(hammer2_pfs_t *pmp)
{
int i;
int j;
lockmgr(&pmp->lock, LK_EXCLUSIVE);
pmp->has_xop_threads = 1;
pmp->xop_groups = kmalloc(hammer2_xop_nthreads *
sizeof(hammer2_xop_group_t),
M_HAMMER2, M_WAITOK | M_ZERO);
for (i = 0; i < pmp->iroot->cluster.nchains; ++i) {
for (j = 0; j < hammer2_xop_nthreads; ++j) {
if (pmp->xop_groups[j].thrs[i].td)
continue;
hammer2_thr_create(&pmp->xop_groups[j].thrs[i],
pmp, NULL,
"h2xop", i, j,
hammer2_primary_xops_thread);
}
}
lockmgr(&pmp->lock, LK_RELEASE);
}
void
hammer2_xop_helper_cleanup(hammer2_pfs_t *pmp)
{
int i;
int j;
if (pmp->xop_groups == NULL) {
KKASSERT(pmp->has_xop_threads == 0);
return;
}
for (i = 0; i < pmp->pfs_nmasters; ++i) {
for (j = 0; j < hammer2_xop_nthreads; ++j) {
if (pmp->xop_groups[j].thrs[i].td)
hammer2_thr_delete(&pmp->xop_groups[j].thrs[i]);
}
}
pmp->has_xop_threads = 0;
kfree(pmp->xop_groups, M_HAMMER2);
pmp->xop_groups = NULL;
}
/*
* Start a XOP request, queueing it to all nodes in the cluster to
* execute the cluster op.
*
* XXX optimize single-target case.
*/
void
hammer2_xop_start_except(hammer2_xop_head_t *xop, hammer2_xop_desc_t *desc,
int notidx)
{
hammer2_inode_t *ip1;
hammer2_pfs_t *pmp;
hammer2_thread_t *thr;
int i;
int ng;
int nchains;
ip1 = xop->ip1;
pmp = ip1->pmp;
if (pmp->has_xop_threads == 0)
hammer2_xop_helper_create(pmp);
/*
* The sequencer assigns a worker thread to the XOP.
*
* (1) The worker threads are partitioned into two sets, one for
* NON-STRATEGY XOPs, and the other for STRATEGY XOPs. This
* guarantees that strategy calls will always be able to make
* progress and will not deadlock against non-strategy calls.
*
* (2) If clustered, non-strategy operations to the same inode must
* be serialized. This is to avoid confusion when issuing
* modifying operations because a XOP completes the instant a
* quorum is reached.
*
* TODO - RENAME fails here because it is potentially modifying
* three different inodes, but we triple-lock the inodes
* involved so it shouldn't create a sequencing schism.
*/
if (xop->flags & HAMMER2_XOP_STRATEGY) {
/*
* Use worker space 0 associated with the current cpu
* for strategy ops.
*/
hammer2_xop_strategy_t *xopst;
u_int which;
xopst = &((hammer2_xop_t *)xop)->xop_strategy;
which = ((unsigned int)ip1->ihash +
((unsigned int)xopst->lbase >> HAMMER2_PBUFRADIX)) %
hammer2_xop_sgroups;
ng = mycpu->gd_cpuid % hammer2_xop_mod +
hammer2_xop_mod * which;
} else if (hammer2_spread_workers == 0 && ip1->cluster.nchains == 1) {
/*
* For now try to keep the work on the same cpu to reduce
* IPI overhead. Several threads are assigned to each cpu,
* don't be very smart and select the one to use based on
* the inode hash.
*/
u_int which;
which = (unsigned int)ip1->ihash % hammer2_xop_xgroups;
ng = mycpu->gd_cpuid % hammer2_xop_mod +
(which * hammer2_xop_mod) +
hammer2_xop_xbase;
} else {
/*
* Hash based on inode only, must serialize inode to same
* thread regardless of current cpu.
*/
ng = (unsigned int)ip1->ihash %
(hammer2_xop_mod * hammer2_xop_xgroups) +
hammer2_xop_xbase;
}
xop->desc = desc;
/*
* The instant xop is queued another thread can pick it off. In the
* case of asynchronous ops, another thread might even finish and
* deallocate it.
*/
hammer2_spin_ex(&pmp->xop_spin);
nchains = ip1->cluster.nchains;
for (i = 0; i < nchains; ++i) {
/*
* XXX ip1->cluster.array* not stable here. This temporary
* hack fixes basic issues in target XOPs which need to
* obtain a starting chain from the inode but does not
* address possible races against inode updates which
* might NULL-out a chain.
*/
if (i != notidx && ip1->cluster.array[i].chain) {
thr = &pmp->xop_groups[ng].thrs[i];
atomic_set_64(&xop->run_mask, 1LLU << i);
atomic_set_64(&xop->chk_mask, 1LLU << i);
xop->collect[i].thr = thr;
TAILQ_INSERT_TAIL(&thr->xopq, xop, collect[i].entry);
}
}
hammer2_spin_unex(&pmp->xop_spin);
/* xop can become invalid at this point */
/*
* Each thread has its own xopq
*/
for (i = 0; i < nchains; ++i) {
if (i != notidx) {
thr = &pmp->xop_groups[ng].thrs[i];
hammer2_thr_signal(thr, HAMMER2_THREAD_XOPQ);
}
}
}
void
hammer2_xop_start(hammer2_xop_head_t *xop, hammer2_xop_desc_t *desc)
{
hammer2_xop_start_except(xop, desc, -1);
}
/*
* Retire a XOP. Used by both the VOP frontend and by the XOP backend.
*/
void
hammer2_xop_retire(hammer2_xop_head_t *xop, uint64_t mask)
{
hammer2_chain_t *chain;
uint64_t nmask;
int i;
/*
* Remove the frontend collector or remove a backend feeder.
*
* When removing the frontend we must wakeup any backend feeders
* who are waiting for FIFO space.
*
* When removing the last backend feeder we must wakeup any waiting
* frontend.
*/
KKASSERT(xop->run_mask & mask);
nmask = atomic_fetchadd_64(&xop->run_mask,
-mask + HAMMER2_XOPMASK_FEED);
/*
* More than one entity left
*/
if ((nmask & HAMMER2_XOPMASK_ALLDONE) != mask) {
/*
* Frontend terminating, wakeup any backends waiting on
* fifo full.
*
* NOTE!!! The xop can get ripped out from under us at
* this point, so do not reference it again.
* The wakeup(xop) doesn't touch the xop and
* is ok.
*/
if (mask == HAMMER2_XOPMASK_VOP) {
if (nmask & HAMMER2_XOPMASK_FIFOW)
wakeup(xop);
}
/*
* Wakeup frontend if the last backend is terminating.
*/
nmask -= mask;
if ((nmask & HAMMER2_XOPMASK_ALLDONE) == HAMMER2_XOPMASK_VOP) {
if (nmask & HAMMER2_XOPMASK_WAIT)
wakeup(xop);
}
return;
}
/* else nobody else left, we can ignore FIFOW */
/*
* All collectors are gone, we can cleanup and dispose of the XOP.
* Note that this can wind up being a frontend OR a backend.
* Pending chains are locked shared and not owned by any thread.
*
* Cleanup the collection cluster.
*/
for (i = 0; i < xop->cluster.nchains; ++i) {
xop->cluster.array[i].flags = 0;
chain = xop->cluster.array[i].chain;
if (chain) {
xop->cluster.array[i].chain = NULL;
hammer2_chain_drop_unhold(chain);
}
}
/*
* Cleanup the fifos. Since we are the only entity left on this
* xop we don't have to worry about fifo flow control, and one
* lfence() will do the job.
*/
cpu_lfence();
mask = xop->chk_mask;
for (i = 0; mask && i < HAMMER2_MAXCLUSTER; ++i) {
hammer2_xop_fifo_t *fifo = &xop->collect[i];
while (fifo->ri != fifo->wi) {
chain = fifo->array[fifo->ri & HAMMER2_XOPFIFO_MASK];
if (chain)
hammer2_chain_drop_unhold(chain);
++fifo->ri;
}
mask &= ~(1U << i);
}
/*
* The inode is only held at this point, simply drop it.
*/
if (xop->ip1) {
hammer2_inode_drop(xop->ip1);
xop->ip1 = NULL;
}
if (xop->ip2) {
hammer2_inode_drop(xop->ip2);
xop->ip2 = NULL;
}
if (xop->ip3) {
hammer2_inode_drop(xop->ip3);
xop->ip3 = NULL;
}
if (xop->ip4) {
hammer2_inode_drop(xop->ip4);
xop->ip4 = NULL;
}
if (xop->name1) {
kfree(xop->name1, M_HAMMER2);
xop->name1 = NULL;
xop->name1_len = 0;
}
if (xop->name2) {
kfree(xop->name2, M_HAMMER2);
xop->name2 = NULL;
xop->name2_len = 0;
}
objcache_put(cache_xops, xop);
}
/*
* (Backend) Returns non-zero if the frontend is still attached.
*/
int
hammer2_xop_active(hammer2_xop_head_t *xop)
{
if (xop->run_mask & HAMMER2_XOPMASK_VOP)
return 1;
else
return 0;
}
/*
* (Backend) Feed chain data through the cluster validator and back to
* the frontend. Chains are fed from multiple nodes concurrently
* and pipelined via per-node FIFOs in the XOP.
*
* The chain must be locked (either shared or exclusive). The caller may
* unlock and drop the chain on return. This function will add an extra
* ref and hold the chain's data for the pass-back.
*
* No xop lock is needed because we are only manipulating fields under
* our direct control.
*
* Returns 0 on success and a hammer2 error code if sync is permanently
* lost. The caller retains a ref on the chain but by convention
* the lock is typically inherited by the xop (caller loses lock).
*
* Returns non-zero on error. In this situation the caller retains a
* ref on the chain but loses the lock (we unlock here).
*/
int
hammer2_xop_feed(hammer2_xop_head_t *xop, hammer2_chain_t *chain,
int clindex, int error)
{
hammer2_xop_fifo_t *fifo;
uint64_t mask;
/*
* Early termination (typicaly of xop_readir)
*/
if (hammer2_xop_active(xop) == 0) {
error = HAMMER2_ERROR_ABORTED;
goto done;
}
/*
* Multi-threaded entry into the XOP collector. We own the
* fifo->wi for our clindex.
*/
fifo = &xop->collect[clindex];
if (fifo->ri == fifo->wi - HAMMER2_XOPFIFO)
lwkt_yield();
while (fifo->ri == fifo->wi - HAMMER2_XOPFIFO) {
atomic_set_int(&fifo->flags, HAMMER2_XOP_FIFO_STALL);
mask = xop->run_mask;
if ((mask & HAMMER2_XOPMASK_VOP) == 0) {
error = HAMMER2_ERROR_ABORTED;
goto done;
}
tsleep_interlock(xop, 0);
if (atomic_cmpset_64(&xop->run_mask, mask,
mask | HAMMER2_XOPMASK_FIFOW)) {
if (fifo->ri == fifo->wi - HAMMER2_XOPFIFO) {
tsleep(xop, PINTERLOCKED, "h2feed", hz*60);
}
}
/* retry */
}
atomic_clear_int(&fifo->flags, HAMMER2_XOP_FIFO_STALL);
if (chain)
hammer2_chain_ref_hold(chain);
if (error == 0 && chain)
error = chain->error;
fifo->errors[fifo->wi & HAMMER2_XOPFIFO_MASK] = error;
fifo->array[fifo->wi & HAMMER2_XOPFIFO_MASK] = chain;
cpu_sfence();
++fifo->wi;
mask = atomic_fetchadd_64(&xop->run_mask, HAMMER2_XOPMASK_FEED);
if (mask & HAMMER2_XOPMASK_WAIT) {
atomic_clear_64(&xop->run_mask, HAMMER2_XOPMASK_WAIT);
wakeup(xop);
}
error = 0;
/*
* Cleanup. If an error occurred we eat the lock. If no error
* occurred the fifo inherits the lock and gains an additional ref.
*
* The caller's ref remains in both cases.
*/
done:
return error;
}
/*
* (Frontend) collect a response from a running cluster op.
*
* Responses are fed from all appropriate nodes concurrently
* and collected into a cohesive response >= collect_key.
*
* The collector will return the instant quorum or other requirements
* are met, even if some nodes get behind or become non-responsive.
*
* HAMMER2_XOP_COLLECT_NOWAIT - Used to 'poll' a completed collection,
* usually called synchronously from the
* node XOPs for the strategy code to
* fake the frontend collection and complete
* the BIO as soon as possible.
*
* HAMMER2_XOP_SYNCHRONIZER - Reqeuest synchronization with a particular
* cluster index, prevents looping when that
* index is out of sync so caller can act on
* the out of sync element. ESRCH and EDEADLK
* can be returned if this flag is specified.
*
* Returns 0 on success plus a filled out xop->cluster structure.
* Return ENOENT on normal termination.
* Otherwise return an error.
*
* WARNING! If the xop returns a cluster with a non-NULL focus, note that
* none of the chains in the cluster (or the focus) are either
* locked or I/O synchronized with the cpu. hammer2_xop_gdata()
* and hammer2_xop_pdata() must be used to safely access the focus
* chain's content.
*
* The frontend can make certain assumptions based on higher-level
* locking done by the frontend, but data integrity absolutely
* requires using the gdata/pdata API.
*/
int
hammer2_xop_collect(hammer2_xop_head_t *xop, int flags)
{
hammer2_xop_fifo_t *fifo;
hammer2_chain_t *chain;
hammer2_key_t lokey;
uint64_t mask;
int error;
int keynull;
int adv; /* advance the element */
int i;
loop:
/*
* First loop tries to advance pieces of the cluster which
* are out of sync.
*/
lokey = HAMMER2_KEY_MAX;
keynull = HAMMER2_CHECK_NULL;
mask = xop->run_mask;
cpu_lfence();
for (i = 0; i < xop->cluster.nchains; ++i) {
chain = xop->cluster.array[i].chain;
if (chain == NULL) {
adv = 1;
} else if (chain->bref.key < xop->collect_key) {
adv = 1;
} else {
keynull &= ~HAMMER2_CHECK_NULL;
if (lokey > chain->bref.key)
lokey = chain->bref.key;
adv = 0;
}
if (adv == 0)
continue;
/*
* Advance element if possible, advanced element may be NULL.
*/
if (chain)
hammer2_chain_drop_unhold(chain);
fifo = &xop->collect[i];
if (fifo->ri != fifo->wi) {
cpu_lfence();
chain = fifo->array[fifo->ri & HAMMER2_XOPFIFO_MASK];
error = fifo->errors[fifo->ri & HAMMER2_XOPFIFO_MASK];
++fifo->ri;
xop->cluster.array[i].chain = chain;
xop->cluster.array[i].error = error;
if (chain == NULL) {
/* XXX */
xop->cluster.array[i].flags |=
HAMMER2_CITEM_NULL;
}
if (fifo->wi - fifo->ri <= HAMMER2_XOPFIFO / 2) {
if (fifo->flags & HAMMER2_XOP_FIFO_STALL) {
atomic_clear_int(&fifo->flags,
HAMMER2_XOP_FIFO_STALL);
wakeup(xop);
lwkt_yield();
}
}
--i; /* loop on same index */
} else {
/*
* Retain CITEM_NULL flag. If set just repeat EOF.
* If not, the NULL,0 combination indicates an
* operation in-progress.
*/
xop->cluster.array[i].chain = NULL;
/* retain any CITEM_NULL setting */
}
}
/*
* Determine whether the lowest collected key meets clustering
* requirements. Returns:
*
* 0 - key valid, cluster can be returned.
*
* ENOENT - normal end of scan, return ENOENT.
*
* ESRCH - sufficient elements collected, quorum agreement
* that lokey is not a valid element and should be
* skipped.
*
* EDEADLK - sufficient elements collected, no quorum agreement
* (and no agreement possible). In this situation a
* repair is needed, for now we loop.
*
* EINPROGRESS - insufficient elements collected to resolve, wait
* for event and loop.
*/
if ((flags & HAMMER2_XOP_COLLECT_WAITALL) &&
(mask & HAMMER2_XOPMASK_ALLDONE) != HAMMER2_XOPMASK_VOP) {
error = HAMMER2_ERROR_EINPROGRESS;
} else {
error = hammer2_cluster_check(&xop->cluster, lokey, keynull);
}
if (error == HAMMER2_ERROR_EINPROGRESS) {
if (flags & HAMMER2_XOP_COLLECT_NOWAIT)
goto done;
tsleep_interlock(xop, 0);
if (atomic_cmpset_64(&xop->run_mask,
mask, mask | HAMMER2_XOPMASK_WAIT)) {
tsleep(xop, PINTERLOCKED, "h2coll", hz*60);
}
goto loop;
}
if (error == HAMMER2_ERROR_ESRCH) {
if (lokey != HAMMER2_KEY_MAX) {
xop->collect_key = lokey + 1;
goto loop;
}
error = HAMMER2_ERROR_ENOENT;
}
if (error == HAMMER2_ERROR_EDEADLK) {
kprintf("hammer2: no quorum possible lokey %016jx\n",
lokey);
if (lokey != HAMMER2_KEY_MAX) {
xop->collect_key = lokey + 1;
goto loop;
}
error = HAMMER2_ERROR_ENOENT;
}
if (lokey == HAMMER2_KEY_MAX)
xop->collect_key = lokey;
else
xop->collect_key = lokey + 1;
done:
return error;
}
/*
* N x M processing threads are available to handle XOPs, N per cluster
* index x M cluster nodes.
*
* Locate and return the next runnable xop, or NULL if no xops are
* present or none of the xops are currently runnable (for various reasons).
* The xop is left on the queue and serves to block other dependent xops
* from being run.
*
* Dependent xops will not be returned.
*
* Sets HAMMER2_XOP_FIFO_RUN on the returned xop or returns NULL.
*
* NOTE! Xops run concurrently for each cluster index.
*/
#define XOP_HASH_SIZE 16
#define XOP_HASH_MASK (XOP_HASH_SIZE - 1)
static __inline
int
xop_testhash(hammer2_thread_t *thr, hammer2_inode_t *ip, uint32_t *hash)
{
uint32_t mask;
int hv;
hv = (int)((uintptr_t)ip + (uintptr_t)thr) / sizeof(hammer2_inode_t);
mask = 1U << (hv & 31);
hv >>= 5;
return ((int)(hash[hv & XOP_HASH_MASK] & mask));
}
static __inline
void
xop_sethash(hammer2_thread_t *thr, hammer2_inode_t *ip, uint32_t *hash)
{
uint32_t mask;
int hv;
hv = (int)((uintptr_t)ip + (uintptr_t)thr) / sizeof(hammer2_inode_t);
mask = 1U << (hv & 31);
hv >>= 5;
hash[hv & XOP_HASH_MASK] |= mask;
}
static
hammer2_xop_head_t *
hammer2_xop_next(hammer2_thread_t *thr)
{
hammer2_pfs_t *pmp = thr->pmp;
int clindex = thr->clindex;
uint32_t hash[XOP_HASH_SIZE] = { 0 };
hammer2_xop_head_t *xop;
hammer2_spin_ex(&pmp->xop_spin);
TAILQ_FOREACH(xop, &thr->xopq, collect[clindex].entry) {
/*
* Check dependency
*/
if (xop_testhash(thr, xop->ip1, hash) ||
(xop->ip2 && xop_testhash(thr, xop->ip2, hash)) ||
(xop->ip3 && xop_testhash(thr, xop->ip3, hash)) ||
(xop->ip4 && xop_testhash(thr, xop->ip4, hash)))
{
continue;
}
xop_sethash(thr, xop->ip1, hash);
if (xop->ip2)
xop_sethash(thr, xop->ip2, hash);
if (xop->ip3)
xop_sethash(thr, xop->ip3, hash);
if (xop->ip4)
xop_sethash(thr, xop->ip4, hash);
/*
* Check already running
*/
if (xop->collect[clindex].flags & HAMMER2_XOP_FIFO_RUN)
continue;
/*
* Found a good one, return it.
*/
atomic_set_int(&xop->collect[clindex].flags,
HAMMER2_XOP_FIFO_RUN);
break;
}
hammer2_spin_unex(&pmp->xop_spin);
return xop;
}
/*
* Remove the completed XOP from the queue, clear HAMMER2_XOP_FIFO_RUN.
*
* NOTE! Xops run concurrently for each cluster index.
*/
static
void
hammer2_xop_dequeue(hammer2_thread_t *thr, hammer2_xop_head_t *xop)
{
hammer2_pfs_t *pmp = thr->pmp;
int clindex = thr->clindex;
hammer2_spin_ex(&pmp->xop_spin);
TAILQ_REMOVE(&thr->xopq, xop, collect[clindex].entry);
atomic_clear_int(&xop->collect[clindex].flags,
HAMMER2_XOP_FIFO_RUN);
hammer2_spin_unex(&pmp->xop_spin);
if (TAILQ_FIRST(&thr->xopq))
hammer2_thr_signal(thr, HAMMER2_THREAD_XOPQ);
}
/*
* Primary management thread for xops support. Each node has several such
* threads which replicate front-end operations on cluster nodes.
*
* XOPS thread node operations, allowing the function to focus on a single
* node in the cluster after validating the operation with the cluster.
* This is primarily what prevents dead or stalled nodes from stalling
* the front-end.
*/
void
hammer2_primary_xops_thread(void *arg)
{
hammer2_thread_t *thr = arg;
hammer2_pfs_t *pmp;
hammer2_xop_head_t *xop;
uint64_t mask;
uint32_t flags;
uint32_t nflags;
hammer2_xop_desc_t *last_desc = NULL;
pmp = thr->pmp;
/*xgrp = &pmp->xop_groups[thr->repidx]; not needed */
mask = 1LLU << thr->clindex;
for (;;) {
flags = thr->flags;
/*
* Handle stop request
*/
if (flags & HAMMER2_THREAD_STOP)
break;
/*
* Handle freeze request
*/
if (flags & HAMMER2_THREAD_FREEZE) {
hammer2_thr_signal2(thr, HAMMER2_THREAD_FROZEN,
HAMMER2_THREAD_FREEZE);
continue;
}
if (flags & HAMMER2_THREAD_UNFREEZE) {
hammer2_thr_signal2(thr, 0,
HAMMER2_THREAD_FROZEN |
HAMMER2_THREAD_UNFREEZE);
continue;
}
/*
* Force idle if frozen until unfrozen or stopped.
*/
if (flags & HAMMER2_THREAD_FROZEN) {
hammer2_thr_wait_any(thr,
HAMMER2_THREAD_UNFREEZE |
HAMMER2_THREAD_STOP,
0);
continue;
}
/*
* Reset state on REMASTER request
*/
if (flags & HAMMER2_THREAD_REMASTER) {
hammer2_thr_signal2(thr, 0, HAMMER2_THREAD_REMASTER);
/* reset state here */
continue;
}
/*
* Process requests. Each request can be multi-queued.
*
* If we get behind and the frontend VOP is no longer active,
* we retire the request without processing it. The callback
* may also abort processing if the frontend VOP becomes
* inactive.
*/
if (flags & HAMMER2_THREAD_XOPQ) {
nflags = flags & ~HAMMER2_THREAD_XOPQ;
if (!atomic_cmpset_int(&thr->flags, flags, nflags))
continue;
flags = nflags;
/* fall through */
}
while ((xop = hammer2_xop_next(thr)) != NULL) {
if (hammer2_xop_active(xop)) {
last_desc = xop->desc;
xop->desc->storage_func((hammer2_xop_t *)xop,
thr->scratch,
thr->clindex);
hammer2_xop_dequeue(thr, xop);
hammer2_xop_retire(xop, mask);
} else {
last_desc = xop->desc;
hammer2_xop_feed(xop, NULL, thr->clindex,
ECONNABORTED);
hammer2_xop_dequeue(thr, xop);
hammer2_xop_retire(xop, mask);
}
}
/*
* Wait for event, interlock using THREAD_WAITING and
* THREAD_SIGNAL.
*
* For robustness poll on a 30-second interval, but nominally
* expect to be woken up.
*/
nflags = flags | HAMMER2_THREAD_WAITING;
tsleep_interlock(&thr->flags, 0);
if (atomic_cmpset_int(&thr->flags, flags, nflags)) {
tsleep(&thr->flags, PINTERLOCKED, "h2idle", hz*30);
}
}
#if 0
/*
* Cleanup / termination
*/
while ((xop = TAILQ_FIRST(&thr->xopq)) != NULL) {
kprintf("hammer2_thread: aborting xop %s\n", xop->desc->id);
TAILQ_REMOVE(&thr->xopq, xop,
collect[thr->clindex].entry);
hammer2_xop_retire(xop, mask);
}
#endif
thr->td = NULL;
hammer2_thr_signal(thr, HAMMER2_THREAD_STOPPED);
/* thr structure can go invalid after this point */
}
|
779923.c | /* $Id: mkspans.c,v 1.12 2015/10/09 21:36:11 drolon Exp $ */
/*
* Copyright (c) 1991-1997 Sam Leffler
* Copyright (c) 1991-1997 Silicon Graphics, Inc.
*
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
* LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
#include <string.h>
#include <stdio.h>
/*
* Hack program to construct tables used to find
* runs of zeros and ones in Group 3 Fax encoding.
*/
dumparray(name, runs)
char *name;
unsigned char runs[256];
{
int i;
char *sep;
printf("static unsigned char %s[256] = {\n", name);
sep = " ";
for (i = 0; i < 256; i++) {
printf("%s%d", sep, runs[i]);
if (((i + 1) % 16) == 0) {
printf(", /* 0x%02x - 0x%02x */\n", i-15, i);
sep = " ";
} else
sep = ", ";
}
printf("\n};\n");
}
main()
{
unsigned char runs[2][256];
memset(runs[0], 0, 256*sizeof (char));
memset(runs[1], 0, 256*sizeof (char));
{ register int run, runlen, i;
runlen = 1;
for (run = 0x80; run != 0xff; run = (run>>1)|0x80) {
for (i = run-1; i >= 0; i--) {
runs[1][run|i] = runlen;
runs[0][(~(run|i)) & 0xff] = runlen;
}
runlen++;
}
runs[1][0xff] = runs[0][0] = 8;
}
dumparray("bruns", runs[0]);
dumparray("wruns", runs[1]);
}
/* vim: set ts=8 sts=8 sw=8 noet: */
/*
* Local Variables:
* mode: c
* c-basic-offset: 8
* fill-column: 78
* End:
*/
|
596333.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
│vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright 2020 Justine Alexandra Roberts Tunney │
│ │
│ 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. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/log/internal.h"
#include "libc/log/libfatal.internal.h"
#include "libc/log/log.h"
#include "libc/runtime/runtime.h"
bool g_isrunningundermake;
/**
* Returns true if current process was spawned by GNU Make.
*/
bool IsRunningUnderMake(void) {
return g_isrunningundermake;
}
textstartup void g_isrunningundermake_init(int argc, char **argv, char **envp,
intptr_t *auxv) {
g_isrunningundermake = !!__getenv(envp, "MAKEFLAGS");
}
const void *const g_isrunningundermake_ctor[] initarray = {
g_isrunningundermake_init,
};
|
299438.c | /* mbed Microcontroller Library
*******************************************************************************
* Copyright (c) 2017, STMicroelectronics
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics 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 HOLDER 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 "cmsis.h"
#include "gpio_irq_device.h"
// Used to return the index for channels array.
const exti_lines_t pin_lines_desc[16] = {
// EXTI0
{.gpio_idx = 0, .irq_index = 0, .irq_n = EXTI0_IRQn}, // pin 0
// EXTI1
{.gpio_idx = 0, .irq_index = 1, .irq_n = EXTI1_IRQn}, // pin 1
// EXTI2
{.gpio_idx = 0, .irq_index = 2, .irq_n = EXTI2_IRQn}, // pin 2
// EXTI3
{.gpio_idx = 0, .irq_index = 3, .irq_n = EXTI3_IRQn}, // pin 3
// EXTI4
{.gpio_idx = 0, .irq_index = 4, .irq_n = EXTI4_IRQn}, // pin 4
// EXTI5_9
{.gpio_idx = 0, .irq_index = 5, .irq_n = EXTI9_5_IRQn},// pin 5
{.gpio_idx = 1, .irq_index = 5, .irq_n = EXTI9_5_IRQn},// pin 6
{.gpio_idx = 2, .irq_index = 5, .irq_n = EXTI9_5_IRQn},// pin 7
{.gpio_idx = 3, .irq_index = 5, .irq_n = EXTI9_5_IRQn},// pin 8
{.gpio_idx = 4, .irq_index = 5, .irq_n = EXTI9_5_IRQn},// pin 9
// EXTI10_15
{.gpio_idx = 0, .irq_index = 6, .irq_n = EXTI15_10_IRQn},// pin 10
{.gpio_idx = 1, .irq_index = 6, .irq_n = EXTI15_10_IRQn},// pin 11
{.gpio_idx = 2, .irq_index = 6, .irq_n = EXTI15_10_IRQn},// pin 12
{.gpio_idx = 3, .irq_index = 6, .irq_n = EXTI15_10_IRQn},// pin 13
{.gpio_idx = 4, .irq_index = 6, .irq_n = EXTI15_10_IRQn},// pin 14
{.gpio_idx = 5, .irq_index = 6, .irq_n = EXTI15_10_IRQn}// pin 15
};
|
116797.c | //**********************************************************************;
// Copyright (c) 2015, Intel Corporation
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of 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 THE COPYRIGHT HOLDER 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 <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sapi/tpm20.h>
#include "files.h"
#include "log.h"
#include "pcr.h"
#include "conversion.h"
#include "tpm2_alg_util.h"
#include "tpm2_password_util.h"
#include "tpm2_tool.h"
#include "tpm2_util.h"
typedef struct {
int size;
UINT32 id[24];
} PCR_LIST;
static TPMS_AUTH_COMMAND sessionData;
static char *outFilePath;
static char *signature_path;
static char *message_path;
static signature_format sig_format;
static TPMI_ALG_HASH sig_hash_algorithm;
static TPM2B_DATA qualifyingData = TPM2B_EMPTY_INIT;
static TPML_PCR_SELECTION pcrSelections;
static bool is_auth_session;
static TPMI_SH_AUTH_SESSION auth_session_handle;
static int k_flag, c_flag, l_flag, g_flag, L_flag, o_flag, G_flag;
static char *contextFilePath;
static TPM2_HANDLE akHandle;
static void PrintBuffer( UINT8 *buffer, UINT32 size )
{
UINT32 i;
for( i = 0; i < size; i++ )
{
tpm2_tool_output("%2.2x", buffer[i]);
}
tpm2_tool_output("\n");
}
static bool write_output_files(TPM2B_ATTEST *quoted, TPMT_SIGNATURE *signature) {
bool res = true;
if (signature_path) {
res &= tpm2_convert_signature(signature, sig_format, signature_path);
}
if (message_path) {
res &= files_save_bytes_to_file(message_path,
(UINT8*)quoted->attestationData,
quoted->size);
}
return res;
}
static int quote(TSS2_SYS_CONTEXT *sapi_context, TPM2_HANDLE akHandle, TPML_PCR_SELECTION *pcrSelection)
{
UINT32 rval;
TPMT_SIG_SCHEME inScheme;
TSS2L_SYS_AUTH_COMMAND sessionsData = { 1, {{.sessionHandle=TPM2_RS_PW}}};
TSS2L_SYS_AUTH_RESPONSE sessionsDataOut;
TPM2B_ATTEST quoted = TPM2B_TYPE_INIT(TPM2B_ATTEST, attestationData);
TPMT_SIGNATURE signature;
if (is_auth_session) {
sessionsData.auths[0].sessionHandle = auth_session_handle;
}
if(!G_flag || !get_signature_scheme(sapi_context, akHandle, sig_hash_algorithm, &inScheme)) {
inScheme.scheme = TPM2_ALG_NULL;
}
memset( (void *)&signature, 0, sizeof(signature) );
rval = TSS2_RETRY_EXP(Tss2_Sys_Quote(sapi_context, akHandle, &sessionsData,
&qualifyingData, &inScheme, pcrSelection, "ed,
&signature, &sessionsDataOut));
if(rval != TPM2_RC_SUCCESS)
{
printf("\nQuote Failed ! ErrorCode: 0x%0x\n\n", rval);
return -1;
}
tpm2_tool_output( "\nquoted:\n " );
tpm2_util_print_tpm2b( (TPM2B *)"ed );
//PrintTPM2B_ATTEST("ed);
tpm2_tool_output( "\nsignature:\n " );
PrintBuffer( (UINT8 *)&signature, sizeof(signature) );
//PrintTPMT_SIGNATURE(&signature);
bool res = write_output_files("ed, &signature);
return res == true ? 0 : 1;
}
static bool on_option(char key, char *value) {
switch(key)
{
case 'k':
if(!tpm2_util_string_to_uint32(value, &akHandle))
{
LOG_ERR("Invalid AK handle, got\"%s\"", value);
return false;
}
k_flag = 1;
break;
case 'c':
contextFilePath = optarg;
c_flag = 1;
break;
case 'P': {
bool res = tpm2_password_util_from_optarg(value, &sessionData.hmac);
if (!res) {
LOG_ERR("Invalid AK password, got\"%s\"", value);
return false;
}
} break;
case 'l':
if(!pcr_parse_list(value, strlen(value), &pcrSelections.pcrSelections[0]))
{
LOG_ERR("Could not parse pcr list, got: \"%s\"", value);
return false;
}
l_flag = 1;
break;
case 'g':
pcrSelections.pcrSelections[0].hash = tpm2_alg_util_from_optarg(optarg);
if (pcrSelections.pcrSelections[0].hash == TPM2_ALG_ERROR)
{
LOG_ERR("Could not convert pcr hash selection, got: \"%s\"", value);
return false;
}
pcrSelections.count = 1;
g_flag = 1;
break;
case 'L':
if(!pcr_parse_selections(value, &pcrSelections))
{
LOG_ERR("Could not parse pcr selections, got: \"%s\"", value);
return false;
}
L_flag = 1;
break;
case 'o':
outFilePath = optarg;
o_flag = 1;
break;
case 'q':
qualifyingData.size = sizeof(qualifyingData) - 2;
if(tpm2_util_hex_to_byte_structure(value,&qualifyingData.size,qualifyingData.buffer) != 0)
{
LOG_ERR("Could not convert \"%s\" from a hex string to byte array!", value);
return false;
}
break;
case 'S':
if (!tpm2_util_string_to_uint32(value, &auth_session_handle)) {
LOG_ERR("Could not convert session handle to number, got: \"%s\"",
optarg);
return false;
}
is_auth_session = true;
break;
case 's':
signature_path = optarg;
break;
case 'm':
message_path = optarg;
break;
case 'f':
sig_format = tpm2_parse_signature_format(optarg);
if (sig_format == signature_format_err) {
return false;
}
break;
case 'G':
sig_hash_algorithm = tpm2_alg_util_from_optarg(optarg);
if(sig_hash_algorithm == TPM2_ALG_ERROR) {
LOG_ERR("Could not convert signature hash algorithm selection, got: \"%s\"", value);
return false;
}
G_flag = 1;
break;
}
return true;
}
bool tpm2_tool_onstart(tpm2_options **opts) {
static const struct option topts[] = {
{ "ak-handle", required_argument, NULL, 'k' },
{ "ak-context", required_argument, NULL, 'c' },
{ "ak-passwd", required_argument, NULL, 'P' },
{ "id-list", required_argument, NULL, 'l' },
{ "algorithm", required_argument, NULL, 'g' },
{ "sel-list", required_argument, NULL, 'L' },
{ "qualify-data", required_argument, NULL, 'q' },
{ "input-session-handle", required_argument, NULL, 'S' },
{ "signature", required_argument, NULL, 's' },
{ "message", required_argument, NULL, 'm' },
{ "format", required_argument, NULL, 'f' },
{ "sig-hash-algorithm", required_argument, NULL, 'G' }
};
*opts = tpm2_options_new("k:c:P:l:g:L:o:S:q:s:m:f:G:", ARRAY_LEN(topts), topts,
on_option, NULL, true);
return *opts != NULL;
}
int tpm2_tool_onrun(TSS2_SYS_CONTEXT *sapi_context, tpm2_option_flags flags) {
UNUSED(flags);
/* TODO this whole file needs to be re-done, especially the option validation */
if (!l_flag && !L_flag) {
LOG_ERR("Expected either -l or -L to be specified");
return 1;
}
if(c_flag) {
bool result = files_load_tpm_context_from_file(sapi_context, &akHandle, contextFilePath);
if (!result) {
return 1;
}
}
return quote(sapi_context, akHandle, &pcrSelections);
}
|
670956.c | /****************************************************************************
* arch/risc-v/src/common/riscv_blocktask.c
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you 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.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <stdbool.h>
#include <sched.h>
#include <syscall.h>
#include <assert.h>
#include <debug.h>
#include <nuttx/arch.h>
#include <nuttx/sched.h>
#include "sched/sched.h"
#include "group/group.h"
#include "riscv_internal.h"
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: up_block_task
*
* Description:
* The currently executing task at the head of the ready to run list must
* be stopped. Save its context and move it to the inactive list
* specified by task_state.
*
* Input Parameters:
* tcb: Refers to a task in the ready-to-run list (normally the task at
* the head of the list). It must be stopped, its context saved and
* moved into one of the waiting task lists. If it was the task at the
* head of the ready-to-run list, then a context switch to the new
* ready to run task must be performed.
* task_state: Specifies which waiting task list should hold the blocked
* task TCB.
*
****************************************************************************/
void up_block_task(struct tcb_s *tcb, tstate_t task_state)
{
struct tcb_s *rtcb = this_task();
bool switch_needed;
/* Verify that the context switch can be performed */
DEBUGASSERT((tcb->task_state >= FIRST_READY_TO_RUN_STATE) &&
(tcb->task_state <= LAST_READY_TO_RUN_STATE));
/* Remove the tcb task from the ready-to-run list. If we are blocking the
* task at the head of the task list (the most likely case), then a
* context switch to the next ready-to-run task is needed. In this case,
* it should also be true that rtcb == tcb.
*/
switch_needed = nxsched_remove_readytorun(tcb);
/* Add the task to the specified blocked task list */
nxsched_add_blocked(tcb, (tstate_t)task_state);
/* If there are any pending tasks, then add them to the ready-to-run
* task list now
*/
if (g_pendingtasks.head)
{
switch_needed |= nxsched_merge_pending();
}
/* Now, perform the context switch if one is needed */
if (switch_needed)
{
/* Update scheduler parameters */
nxsched_suspend_scheduler(rtcb);
/* Are we in an interrupt handler? */
if (CURRENT_REGS)
{
/* Yes, then we have to do things differently.
* Just copy the CURRENT_REGS into the OLD rtcb.
*/
riscv_savestate(rtcb->xcp.regs);
/* Restore the exception context of the rtcb at the (new) head
* of the ready-to-run task list.
*/
rtcb = this_task();
/* Reset scheduler parameters */
nxsched_resume_scheduler(rtcb);
/* Then switch contexts. Any necessary address environment
* changes will be made when the interrupt returns.
*/
riscv_restorestate(rtcb->xcp.regs);
}
/* No, then we will need to perform the user context switch */
else
{
/* Get the context of the task at the head of the ready to
* run list.
*/
struct tcb_s *nexttcb = this_task();
#ifdef CONFIG_ARCH_ADDRENV
/* Make sure that the address environment for the previously
* running task is closed down gracefully (data caches dump,
* MMU flushed) and set up the address environment for the new
* thread at the head of the ready-to-run list.
*/
(void)group_addrenv(nexttcb);
#endif
/* Reset scheduler parameters */
nxsched_resume_scheduler(nexttcb);
/* Then switch contexts */
riscv_switchcontext(rtcb->xcp.regs, nexttcb->xcp.regs);
/* riscv_switchcontext forces a context switch to the task at the
* head of the ready-to-run list. It does not 'return' in the
* normal sense. When it does return, it is because the blocked
* task is again ready to run and has execution priority.
*/
}
}
}
|
371283.c | // This file is generated by GenLP_setting.pl v1.4
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <mach/mt_typedefs.h>
#include <mach/mt_power_gs.h>
const unsigned int CHG33_CHG_BUCK_gs_dpidle_data[] = {
// Address Mask Golden Setting Value
0x006D, 0x007F, 0x0000,// VCORE_CON22
0x009F, 0x0080, 0x0000,// VRF18_CON21
0x00A0, 0x0007, 0x0004 // VRF18_CON22
};
const unsigned int *CHG33_CHG_BUCK_gs_dpidle = CHG33_CHG_BUCK_gs_dpidle_data;
unsigned int CHG33_CHG_BUCK_gs_dpidle_len = 9;
const unsigned int CHG33_CHG_BUCK_gs_suspend_data[] = {
// Address Mask Golden Setting Value
0x006D, 0x007F, 0x0000,// VCORE_CON22
0x009F, 0x0080, 0x0000,// VRF18_CON21
0x00A0, 0x0007, 0x0000 // VRF18_CON22
};
const unsigned int *CHG33_CHG_BUCK_gs_suspend = CHG33_CHG_BUCK_gs_suspend_data;
unsigned int CHG33_CHG_BUCK_gs_suspend_len = 9;
const unsigned int CHG33_CHG_BUCK_gs_vp_data[] = {
// Address Mask Golden Setting Value
0x006D, 0x007F, 0x0000,// VCORE_CON22
0x009F, 0x0080, 0x0000,// VRF18_CON21
0x00A0, 0x0007, 0x0003 // VRF18_CON22
};
const unsigned int *CHG33_CHG_BUCK_gs_vp = CHG33_CHG_BUCK_gs_vp_data;
unsigned int CHG33_CHG_BUCK_gs_vp_len = 9;
const unsigned int CHG33_CHG_BUCK_gs_paging_data[] = {
// Address Mask Golden Setting Value
0x006D, 0x007F, 0x0000,// VCORE_CON22
0x009F, 0x0080, 0x0000,// VRF18_CON21
0x00A0, 0x0007, 0x0003 // VRF18_CON22
};
const unsigned int *CHG33_CHG_BUCK_gs_paging = CHG33_CHG_BUCK_gs_paging_data;
unsigned int CHG33_CHG_BUCK_gs_paging_len = 9;
const unsigned int CHG33_CHG_BUCK_gs_mp3_play_data[] = {
// Address Mask Golden Setting Value
0x006D, 0x007F, 0x0000,// VCORE_CON22
0x009F, 0x0080, 0x0000,// VRF18_CON21
0x00A0, 0x0007, 0x0004 // VRF18_CON22
};
const unsigned int *CHG33_CHG_BUCK_gs_mp3_play = CHG33_CHG_BUCK_gs_mp3_play_data;
unsigned int CHG33_CHG_BUCK_gs_mp3_play_len = 9;
const unsigned int CHG33_CHG_BUCK_gs_idle_data[] = {
// Address Mask Golden Setting Value
0x006D, 0x007F, 0x0000,// VCORE_CON22
0x009F, 0x0080, 0x0000,// VRF18_CON21
0x00A0, 0x0007, 0x0003 // VRF18_CON22
};
const unsigned int *CHG33_CHG_BUCK_gs_idle = CHG33_CHG_BUCK_gs_idle_data;
unsigned int CHG33_CHG_BUCK_gs_idle_len = 9;
const unsigned int CHG33_CHG_BUCK_gs_talk_data[] = {
// Address Mask Golden Setting Value
0x006D, 0x007F, 0x0000,// VCORE_CON22
0x009F, 0x0080, 0x0000,// VRF18_CON21
0x00A0, 0x0007, 0x0003 // VRF18_CON22
};
const unsigned int *CHG33_CHG_BUCK_gs_talk = CHG33_CHG_BUCK_gs_talk_data;
unsigned int CHG33_CHG_BUCK_gs_talk_len = 9;
const unsigned int CHG33_CHG_BUCK_gs_connsys_data[] = {
// Address Mask Golden Setting Value
0x006D, 0x007F, 0x0000,// VCORE_CON22
0x009F, 0x0080, 0x0000,// VRF18_CON21
0x00A0, 0x0007, 0x0003 // VRF18_CON22
};
const unsigned int *CHG33_CHG_BUCK_gs_connsys = CHG33_CHG_BUCK_gs_connsys_data;
unsigned int CHG33_CHG_BUCK_gs_connsys_len = 9;
const unsigned int CHG33_CHG_BUCK_gs_datalink_data[] = {
// Address Mask Golden Setting Value
0x006D, 0x007F, 0x0000,// VCORE_CON22
0x009F, 0x0080, 0x0000,// VRF18_CON21
0x00A0, 0x0007, 0x0003 // VRF18_CON22
};
const unsigned int *CHG33_CHG_BUCK_gs_datalink = CHG33_CHG_BUCK_gs_datalink_data;
unsigned int CHG33_CHG_BUCK_gs_datalink_len = 9;
const unsigned int CHG33_CHG_BUCK_gs_vr_data[] = {
// Address Mask Golden Setting Value
0x006D, 0x007F, 0x0000,// VCORE_CON22
0x009F, 0x0080, 0x0000,// VRF18_CON21
0x00A0, 0x0007, 0x0003 // VRF18_CON22
};
const unsigned int *CHG33_CHG_BUCK_gs_vr = CHG33_CHG_BUCK_gs_vr_data;
unsigned int CHG33_CHG_BUCK_gs_vr_len = 9;
|
884859.c | /*
* User-defined destination (and option) support for CUPS.
*
* Copyright © 2007-2019 by Apple Inc.
* Copyright © 1997-2007 by Easy Software Products.
*
* Licensed under Apache License v2.0. See the file "LICENSE" for more
* information.
*/
/*
* Include necessary headers...
*/
#include "cups-private.h"
#include "debug-internal.h"
#include <sys/stat.h>
#ifdef HAVE_NOTIFY_H
# include <notify.h>
#endif /* HAVE_NOTIFY_H */
#ifdef HAVE_POLL
# include <poll.h>
#endif /* HAVE_POLL */
#ifdef HAVE_DNSSD
# include <dns_sd.h>
#endif /* HAVE_DNSSD */
#ifdef HAVE_AVAHI
# include <avahi-client/client.h>
# include <avahi-client/lookup.h>
# include <avahi-common/simple-watch.h>
# include <avahi-common/domain.h>
# include <avahi-common/error.h>
# include <avahi-common/malloc.h>
#define kDNSServiceMaxDomainName AVAHI_DOMAIN_NAME_MAX
#endif /* HAVE_AVAHI */
/*
* Constants...
*/
#ifdef __APPLE__
# if HAVE_SCDYNAMICSTORECOPYCOMPUTERNAME
# include <SystemConfiguration/SystemConfiguration.h>
# define _CUPS_LOCATION_DEFAULTS 1
# endif /* HAVE_SCDYNAMICSTORECOPYCOMPUTERNAME */
# define kCUPSPrintingPrefs CFSTR("org.cups.PrintingPrefs")
# define kDefaultPaperIDKey CFSTR("DefaultPaperID")
# define kLastUsedPrintersKey CFSTR("LastUsedPrinters")
# define kLocationNetworkKey CFSTR("Network")
# define kLocationPrinterIDKey CFSTR("PrinterID")
# define kUseLastPrinter CFSTR("UseLastPrinter")
#endif /* __APPLE__ */
#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
# define _CUPS_DNSSD_GET_DESTS 250 /* Milliseconds for cupsGetDests */
# define _CUPS_DNSSD_MAXTIME 50 /* Milliseconds for maximum quantum of time */
#else
# define _CUPS_DNSSD_GET_DESTS 0 /* Milliseconds for cupsGetDests */
#endif /* HAVE_DNSSD || HAVE_AVAHI */
/*
* Types...
*/
#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
typedef enum _cups_dnssd_state_e /* Enumerated device state */
{
_CUPS_DNSSD_NEW,
_CUPS_DNSSD_QUERY,
_CUPS_DNSSD_PENDING,
_CUPS_DNSSD_ACTIVE,
_CUPS_DNSSD_INCOMPATIBLE,
_CUPS_DNSSD_ERROR
} _cups_dnssd_state_t;
typedef struct _cups_dnssd_data_s /* Enumeration data */
{
# ifdef HAVE_DNSSD
DNSServiceRef main_ref; /* Main service reference */
# else /* HAVE_AVAHI */
AvahiSimplePoll *simple_poll; /* Polling interface */
AvahiClient *client; /* Client information */
int got_data; /* Did we get data? */
int browsers; /* How many browsers are running? */
# endif /* HAVE_DNSSD */
cups_dest_cb_t cb; /* Callback */
void *user_data; /* User data pointer */
cups_ptype_t type, /* Printer type filter */
mask; /* Printer type mask */
cups_array_t *devices; /* Devices found so far */
int num_dests; /* Number of lpoptions destinations */
cups_dest_t *dests; /* lpoptions destinations */
char def_name[1024], /* Default printer name, if any */
*def_instance; /* Default printer instance, if any */
} _cups_dnssd_data_t;
typedef struct _cups_dnssd_device_s /* Enumerated device */
{
_cups_dnssd_state_t state; /* State of device listing */
# ifdef HAVE_DNSSD
DNSServiceRef ref; /* Service reference for query */
# else /* HAVE_AVAHI */
AvahiRecordBrowser *ref; /* Browser for query */
# endif /* HAVE_DNSSD */
char *fullName, /* Full name */
*regtype, /* Registration type */
*domain; /* Domain name */
cups_ptype_t type; /* Device registration type */
cups_dest_t dest; /* Destination record */
} _cups_dnssd_device_t;
typedef struct _cups_dnssd_resolve_s /* Data for resolving URI */
{
int *cancel; /* Pointer to "cancel" variable */
struct timeval end_time; /* Ending time */
} _cups_dnssd_resolve_t;
#endif /* HAVE_DNSSD */
typedef struct _cups_getdata_s
{
int num_dests; /* Number of destinations */
cups_dest_t *dests; /* Destinations */
char def_name[1024], /* Default printer name, if any */
*def_instance; /* Default printer instance, if any */
} _cups_getdata_t;
typedef struct _cups_namedata_s
{
const char *name; /* Named destination */
cups_dest_t *dest; /* Destination */
} _cups_namedata_t;
/*
* Local functions...
*/
#if _CUPS_LOCATION_DEFAULTS
static CFArrayRef appleCopyLocations(void);
static CFStringRef appleCopyNetwork(void);
#endif /* _CUPS_LOCATION_DEFAULTS */
#ifdef __APPLE__
static char *appleGetPaperSize(char *name, size_t namesize);
#endif /* __APPLE__ */
#if _CUPS_LOCATION_DEFAULTS
static CFStringRef appleGetPrinter(CFArrayRef locations,
CFStringRef network, CFIndex *locindex);
#endif /* _CUPS_LOCATION_DEFAULTS */
static cups_dest_t *cups_add_dest(const char *name, const char *instance,
int *num_dests, cups_dest_t **dests);
#ifdef __BLOCKS__
static int cups_block_cb(cups_dest_block_t block, unsigned flags,
cups_dest_t *dest);
#endif /* __BLOCKS__ */
static int cups_compare_dests(cups_dest_t *a, cups_dest_t *b);
#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
# ifdef HAVE_DNSSD
static void cups_dnssd_browse_cb(DNSServiceRef sdRef,
DNSServiceFlags flags,
uint32_t interfaceIndex,
DNSServiceErrorType errorCode,
const char *serviceName,
const char *regtype,
const char *replyDomain,
void *context);
# else /* HAVE_AVAHI */
static void cups_dnssd_browse_cb(AvahiServiceBrowser *browser,
AvahiIfIndex interface,
AvahiProtocol protocol,
AvahiBrowserEvent event,
const char *serviceName,
const char *regtype,
const char *replyDomain,
AvahiLookupResultFlags flags,
void *context);
static void cups_dnssd_client_cb(AvahiClient *client,
AvahiClientState state,
void *context);
# endif /* HAVE_DNSSD */
static int cups_dnssd_compare_devices(_cups_dnssd_device_t *a,
_cups_dnssd_device_t *b);
static void cups_dnssd_free_device(_cups_dnssd_device_t *device,
_cups_dnssd_data_t *data);
static _cups_dnssd_device_t *
cups_dnssd_get_device(_cups_dnssd_data_t *data,
const char *serviceName,
const char *regtype,
const char *replyDomain);
# ifdef HAVE_DNSSD
static void cups_dnssd_query_cb(DNSServiceRef sdRef,
DNSServiceFlags flags,
uint32_t interfaceIndex,
DNSServiceErrorType errorCode,
const char *fullName,
uint16_t rrtype, uint16_t rrclass,
uint16_t rdlen, const void *rdata,
uint32_t ttl, void *context);
# else /* HAVE_AVAHI */
static int cups_dnssd_poll_cb(struct pollfd *pollfds,
unsigned int num_pollfds,
int timeout, void *context);
static void cups_dnssd_query_cb(AvahiRecordBrowser *browser,
AvahiIfIndex interface,
AvahiProtocol protocol,
AvahiBrowserEvent event,
const char *name, uint16_t rrclass,
uint16_t rrtype, const void *rdata,
size_t rdlen,
AvahiLookupResultFlags flags,
void *context);
# endif /* HAVE_DNSSD */
static const char *cups_dnssd_resolve(cups_dest_t *dest, const char *uri,
int msec, int *cancel,
cups_dest_cb_t cb, void *user_data);
static int cups_dnssd_resolve_cb(void *context);
static void cups_dnssd_unquote(char *dst, const char *src,
size_t dstsize);
static int cups_elapsed(struct timeval *t);
#endif /* HAVE_DNSSD || HAVE_AVAHI */
static int cups_enum_dests(http_t *http, unsigned flags, int msec, int *cancel, cups_ptype_t type, cups_ptype_t mask, cups_dest_cb_t cb, void *user_data);
static int cups_find_dest(const char *name, const char *instance,
int num_dests, cups_dest_t *dests, int prev,
int *rdiff);
static int cups_get_cb(_cups_getdata_t *data, unsigned flags, cups_dest_t *dest);
static char *cups_get_default(const char *filename, char *namebuf,
size_t namesize, const char **instance);
static int cups_get_dests(const char *filename, const char *match_name, const char *match_inst, int load_all, int user_default_set, int num_dests, cups_dest_t **dests);
static char *cups_make_string(ipp_attribute_t *attr, char *buffer,
size_t bufsize);
static int cups_name_cb(_cups_namedata_t *data, unsigned flags, cups_dest_t *dest);
static void cups_queue_name(char *name, const char *serviceName, size_t namesize);
/*
* 'cupsAddDest()' - Add a destination to the list of destinations.
*
* This function cannot be used to add a new class or printer queue,
* it only adds a new container of saved options for the named
* destination or instance.
*
* If the named destination already exists, the destination list is
* returned unchanged. Adding a new instance of a destination creates
* a copy of that destination's options.
*
* Use the @link cupsSaveDests@ function to save the updated list of
* destinations to the user's lpoptions file.
*/
int /* O - New number of destinations */
cupsAddDest(const char *name, /* I - Destination name */
const char *instance, /* I - Instance name or @code NULL@ for none/primary */
int num_dests, /* I - Number of destinations */
cups_dest_t **dests) /* IO - Destinations */
{
int i; /* Looping var */
cups_dest_t *dest; /* Destination pointer */
cups_dest_t *parent = NULL; /* Parent destination */
cups_option_t *doption, /* Current destination option */
*poption; /* Current parent option */
if (!name || !dests)
return (0);
if (!cupsGetDest(name, instance, num_dests, *dests))
{
if (instance && !cupsGetDest(name, NULL, num_dests, *dests))
return (num_dests);
if ((dest = cups_add_dest(name, instance, &num_dests, dests)) == NULL)
return (num_dests);
/*
* Find the base dest again now the array has been realloc'd.
*/
parent = cupsGetDest(name, NULL, num_dests, *dests);
if (instance && parent && parent->num_options > 0)
{
/*
* Copy options from parent...
*/
dest->options = calloc(sizeof(cups_option_t), (size_t)parent->num_options);
if (dest->options)
{
dest->num_options = parent->num_options;
for (i = dest->num_options, doption = dest->options,
poption = parent->options;
i > 0;
i --, doption ++, poption ++)
{
doption->name = _cupsStrRetain(poption->name);
doption->value = _cupsStrRetain(poption->value);
}
}
}
}
return (num_dests);
}
#ifdef __APPLE__
/*
* '_cupsAppleCopyDefaultPaperID()' - Get the default paper ID.
*/
CFStringRef /* O - Default paper ID */
_cupsAppleCopyDefaultPaperID(void)
{
return (CFPreferencesCopyAppValue(kDefaultPaperIDKey,
kCUPSPrintingPrefs));
}
/*
* '_cupsAppleCopyDefaultPrinter()' - Get the default printer at this location.
*/
CFStringRef /* O - Default printer name */
_cupsAppleCopyDefaultPrinter(void)
{
# if _CUPS_LOCATION_DEFAULTS
CFStringRef network; /* Network location */
CFArrayRef locations; /* Location array */
CFStringRef locprinter; /* Current printer */
/*
* Use location-based defaults only if "use last printer" is selected in the
* system preferences...
*/
if (!_cupsAppleGetUseLastPrinter())
{
DEBUG_puts("1_cupsAppleCopyDefaultPrinter: Not using last printer as "
"default.");
return (NULL);
}
/*
* Get the current location...
*/
if ((network = appleCopyNetwork()) == NULL)
{
DEBUG_puts("1_cupsAppleCopyDefaultPrinter: Unable to get current "
"network.");
return (NULL);
}
/*
* Lookup the network in the preferences...
*/
if ((locations = appleCopyLocations()) == NULL)
{
/*
* Missing or bad location array, so no location-based default...
*/
DEBUG_puts("1_cupsAppleCopyDefaultPrinter: Missing or bad last used "
"printer array.");
CFRelease(network);
return (NULL);
}
DEBUG_printf(("1_cupsAppleCopyDefaultPrinter: Got locations, %d entries.",
(int)CFArrayGetCount(locations)));
if ((locprinter = appleGetPrinter(locations, network, NULL)) != NULL)
CFRetain(locprinter);
CFRelease(network);
CFRelease(locations);
return (locprinter);
# else
return (NULL);
# endif /* _CUPS_LOCATION_DEFAULTS */
}
/*
* '_cupsAppleGetUseLastPrinter()' - Get whether to use the last used printer.
*/
int /* O - 1 to use last printer, 0 otherwise */
_cupsAppleGetUseLastPrinter(void)
{
Boolean uselast, /* Use last printer preference value */
uselast_set; /* Valid is set? */
if (getenv("CUPS_DISABLE_APPLE_DEFAULT"))
return (0);
uselast = CFPreferencesGetAppBooleanValue(kUseLastPrinter,
kCUPSPrintingPrefs,
&uselast_set);
if (!uselast_set)
return (1);
else
return (uselast);
}
/*
* '_cupsAppleSetDefaultPaperID()' - Set the default paper id.
*/
void
_cupsAppleSetDefaultPaperID(
CFStringRef name) /* I - New paper ID */
{
CFPreferencesSetAppValue(kDefaultPaperIDKey, name, kCUPSPrintingPrefs);
CFPreferencesAppSynchronize(kCUPSPrintingPrefs);
# ifdef HAVE_NOTIFY_POST
notify_post("com.apple.printerPrefsChange");
# endif /* HAVE_NOTIFY_POST */
}
/*
* '_cupsAppleSetDefaultPrinter()' - Set the default printer for this location.
*/
void
_cupsAppleSetDefaultPrinter(
CFStringRef name) /* I - Default printer/class name */
{
# if _CUPS_LOCATION_DEFAULTS
CFStringRef network; /* Current network */
CFArrayRef locations; /* Old locations array */
CFIndex locindex; /* Index in locations array */
CFStringRef locprinter; /* Current printer */
CFMutableArrayRef newlocations; /* New locations array */
CFMutableDictionaryRef newlocation; /* New location */
/*
* Get the current location...
*/
if ((network = appleCopyNetwork()) == NULL)
{
DEBUG_puts("1_cupsAppleSetDefaultPrinter: Unable to get current network...");
return;
}
/*
* Lookup the network in the preferences...
*/
if ((locations = appleCopyLocations()) != NULL)
locprinter = appleGetPrinter(locations, network, &locindex);
else
{
locprinter = NULL;
locindex = -1;
}
if (!locprinter || CFStringCompare(locprinter, name, 0) != kCFCompareEqualTo)
{
/*
* Need to change the locations array...
*/
if (locations)
{
newlocations = CFArrayCreateMutableCopy(kCFAllocatorDefault, 0,
locations);
if (locprinter)
CFArrayRemoveValueAtIndex(newlocations, locindex);
}
else
newlocations = CFArrayCreateMutable(kCFAllocatorDefault, 0,
&kCFTypeArrayCallBacks);
newlocation = CFDictionaryCreateMutable(kCFAllocatorDefault, 0,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
if (newlocation && newlocations)
{
/*
* Put the new location at the front of the array...
*/
CFDictionaryAddValue(newlocation, kLocationNetworkKey, network);
CFDictionaryAddValue(newlocation, kLocationPrinterIDKey, name);
CFArrayInsertValueAtIndex(newlocations, 0, newlocation);
/*
* Limit the number of locations to 10...
*/
while (CFArrayGetCount(newlocations) > 10)
CFArrayRemoveValueAtIndex(newlocations, 10);
/*
* Push the changes out...
*/
CFPreferencesSetAppValue(kLastUsedPrintersKey, newlocations,
kCUPSPrintingPrefs);
CFPreferencesAppSynchronize(kCUPSPrintingPrefs);
# ifdef HAVE_NOTIFY_POST
notify_post("com.apple.printerPrefsChange");
# endif /* HAVE_NOTIFY_POST */
}
if (newlocations)
CFRelease(newlocations);
if (newlocation)
CFRelease(newlocation);
}
if (locations)
CFRelease(locations);
CFRelease(network);
# else
(void)name;
# endif /* _CUPS_LOCATION_DEFAULTS */
}
/*
* '_cupsAppleSetUseLastPrinter()' - Set whether to use the last used printer.
*/
void
_cupsAppleSetUseLastPrinter(
int uselast) /* O - 1 to use last printer, 0 otherwise */
{
CFPreferencesSetAppValue(kUseLastPrinter,
uselast ? kCFBooleanTrue : kCFBooleanFalse,
kCUPSPrintingPrefs);
CFPreferencesAppSynchronize(kCUPSPrintingPrefs);
# ifdef HAVE_NOTIFY_POST
notify_post("com.apple.printerPrefsChange");
# endif /* HAVE_NOTIFY_POST */
}
#endif /* __APPLE__ */
/*
* 'cupsConnectDest()' - Open a connection to the destination.
*
* Connect to the destination, returning a new @code http_t@ connection object
* and optionally the resource path to use for the destination. These calls
* will block until a connection is made, the timeout expires, the integer
* pointed to by "cancel" is non-zero, or the callback function (or block)
* returns 0. The caller is responsible for calling @link httpClose@ on the
* returned connection.
*
* Starting with CUPS 2.2.4, the caller can pass @code CUPS_DEST_FLAGS_DEVICE@
* for the "flags" argument to connect directly to the device associated with
* the destination. Otherwise, the connection is made to the CUPS scheduler
* associated with the destination.
*
* @since CUPS 1.6/macOS 10.8@
*/
http_t * /* O - Connection to destination or @code NULL@ */
cupsConnectDest(
cups_dest_t *dest, /* I - Destination */
unsigned flags, /* I - Connection flags */
int msec, /* I - Timeout in milliseconds */
int *cancel, /* I - Pointer to "cancel" variable */
char *resource, /* I - Resource buffer */
size_t resourcesize, /* I - Size of resource buffer */
cups_dest_cb_t cb, /* I - Callback function */
void *user_data) /* I - User data pointer */
{
const char *uri; /* Printer URI */
char scheme[32], /* URI scheme */
userpass[256], /* Username and password (unused) */
hostname[256], /* Hostname */
tempresource[1024]; /* Temporary resource buffer */
int port; /* Port number */
char portstr[16]; /* Port number string */
http_encryption_t encryption; /* Encryption to use */
http_addrlist_t *addrlist; /* Address list for server */
http_t *http; /* Connection to server */
DEBUG_printf(("cupsConnectDest(dest=%p, flags=0x%x, msec=%d, cancel=%p(%d), resource=\"%s\", resourcesize=" CUPS_LLFMT ", cb=%p, user_data=%p)", (void *)dest, flags, msec, (void *)cancel, cancel ? *cancel : -1, resource, CUPS_LLCAST resourcesize, (void *)cb, user_data));
/*
* Range check input...
*/
if (!dest)
{
if (resource)
*resource = '\0';
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
return (NULL);
}
if (!resource || resourcesize < 1)
{
resource = tempresource;
resourcesize = sizeof(tempresource);
}
/*
* Grab the printer URI...
*/
if (flags & CUPS_DEST_FLAGS_DEVICE)
{
if ((uri = cupsGetOption("device-uri", dest->num_options, dest->options)) != NULL)
{
#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
if (strstr(uri, "._tcp"))
uri = cups_dnssd_resolve(dest, uri, msec, cancel, cb, user_data);
#endif /* HAVE_DNSSD || HAVE_AVAHI */
}
}
else if ((uri = cupsGetOption("printer-uri-supported", dest->num_options, dest->options)) == NULL)
{
if ((uri = cupsGetOption("device-uri", dest->num_options, dest->options)) != NULL)
{
#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
if (strstr(uri, "._tcp"))
uri = cups_dnssd_resolve(dest, uri, msec, cancel, cb, user_data);
#endif /* HAVE_DNSSD || HAVE_AVAHI */
}
if (uri)
uri = _cupsCreateDest(dest->name, cupsGetOption("printer-info", dest->num_options, dest->options), NULL, uri, tempresource, sizeof(tempresource));
if (uri)
{
dest->num_options = cupsAddOption("printer-uri-supported", uri, dest->num_options, &dest->options);
uri = cupsGetOption("printer-uri-supported", dest->num_options, dest->options);
}
}
if (!uri)
{
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(ENOENT), 0);
if (cb)
(*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_ERROR, dest);
return (NULL);
}
if (httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme, sizeof(scheme),
userpass, sizeof(userpass), hostname, sizeof(hostname),
&port, resource, (int)resourcesize) < HTTP_URI_STATUS_OK)
{
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad printer-uri."), 1);
if (cb)
(*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_ERROR,
dest);
return (NULL);
}
/*
* Lookup the address for the server...
*/
if (cb)
(*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_RESOLVING, dest);
snprintf(portstr, sizeof(portstr), "%d", port);
if ((addrlist = httpAddrGetList(hostname, AF_UNSPEC, portstr)) == NULL)
{
if (cb)
(*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_ERROR, dest);
return (NULL);
}
if (cancel && *cancel)
{
httpAddrFreeList(addrlist);
if (cb)
(*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_CANCELED, dest);
return (NULL);
}
/*
* Create the HTTP object pointing to the server referenced by the URI...
*/
if (!strcmp(scheme, "ipps") || port == 443)
encryption = HTTP_ENCRYPTION_ALWAYS;
else
encryption = HTTP_ENCRYPTION_IF_REQUESTED;
http = httpConnect2(hostname, port, addrlist, AF_UNSPEC, encryption, 1, 0, NULL);
httpAddrFreeList(addrlist);
/*
* Connect if requested...
*/
if (flags & CUPS_DEST_FLAGS_UNCONNECTED)
{
if (cb)
(*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED, dest);
}
else
{
if (cb)
(*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_CONNECTING, dest);
if (!httpReconnect2(http, msec, cancel) && cb)
{
if (cancel && *cancel)
(*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_CONNECTING, dest);
else
(*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_ERROR, dest);
}
else if (cb)
(*cb)(user_data, CUPS_DEST_FLAGS_NONE, dest);
}
return (http);
}
#ifdef __BLOCKS__
/*
* 'cupsConnectDestBlock()' - Open a connection to the destination.
*
* Connect to the destination, returning a new @code http_t@ connection object
* and optionally the resource path to use for the destination. These calls
* will block until a connection is made, the timeout expires, the integer
* pointed to by "cancel" is non-zero, or the block returns 0. The caller is
* responsible for calling @link httpClose@ on the returned connection.
*
* Starting with CUPS 2.2.4, the caller can pass @code CUPS_DEST_FLAGS_DEVICE@
* for the "flags" argument to connect directly to the device associated with
* the destination. Otherwise, the connection is made to the CUPS scheduler
* associated with the destination.
*
* @since CUPS 1.6/macOS 10.8@ @exclude all@
*/
http_t * /* O - Connection to destination or @code NULL@ */
cupsConnectDestBlock(
cups_dest_t *dest, /* I - Destination */
unsigned flags, /* I - Connection flags */
int msec, /* I - Timeout in milliseconds */
int *cancel, /* I - Pointer to "cancel" variable */
char *resource, /* I - Resource buffer */
size_t resourcesize, /* I - Size of resource buffer */
cups_dest_block_t block) /* I - Callback block */
{
return (cupsConnectDest(dest, flags, msec, cancel, resource, resourcesize,
(cups_dest_cb_t)cups_block_cb, (void *)block));
}
#endif /* __BLOCKS__ */
/*
* 'cupsCopyDest()' - Copy a destination.
*
* Make a copy of the destination to an array of destinations (or just a single
* copy) - for use with the cupsEnumDests* functions. The caller is responsible
* for calling cupsFreeDests() on the returned object(s).
*
* @since CUPS 1.6/macOS 10.8@
*/
int /* O - New number of destinations */
cupsCopyDest(cups_dest_t *dest, /* I - Destination to copy */
int num_dests, /* I - Number of destinations */
cups_dest_t **dests) /* IO - Destination array */
{
int i; /* Looping var */
cups_dest_t *new_dest; /* New destination pointer */
cups_option_t *new_option, /* Current destination option */
*option; /* Current parent option */
/*
* Range check input...
*/
if (!dest || num_dests < 0 || !dests)
return (num_dests);
/*
* See if the destination already exists...
*/
if ((new_dest = cupsGetDest(dest->name, dest->instance, num_dests,
*dests)) != NULL)
{
/*
* Protect against copying destination to itself...
*/
if (new_dest == dest)
return (num_dests);
/*
* Otherwise, free the options...
*/
cupsFreeOptions(new_dest->num_options, new_dest->options);
new_dest->num_options = 0;
new_dest->options = NULL;
}
else
new_dest = cups_add_dest(dest->name, dest->instance, &num_dests, dests);
if (new_dest)
{
new_dest->is_default = dest->is_default;
if ((new_dest->options = calloc(sizeof(cups_option_t), (size_t)dest->num_options)) == NULL)
return (cupsRemoveDest(dest->name, dest->instance, num_dests, dests));
new_dest->num_options = dest->num_options;
for (i = dest->num_options, option = dest->options,
new_option = new_dest->options;
i > 0;
i --, option ++, new_option ++)
{
new_option->name = _cupsStrRetain(option->name);
new_option->value = _cupsStrRetain(option->value);
}
}
return (num_dests);
}
/*
* '_cupsCreateDest()' - Create a local (temporary) queue.
*/
char * /* O - Printer URI or @code NULL@ on error */
_cupsCreateDest(const char *name, /* I - Printer name */
const char *info, /* I - Printer description of @code NULL@ */
const char *device_id, /* I - 1284 Device ID or @code NULL@ */
const char *device_uri, /* I - Device URI */
char *uri, /* I - Printer URI buffer */
size_t urisize) /* I - Size of URI buffer */
{
http_t *http; /* Connection to server */
ipp_t *request, /* CUPS-Create-Local-Printer request */
*response; /* CUPS-Create-Local-Printer response */
ipp_attribute_t *attr; /* printer-uri-supported attribute */
ipp_pstate_t state = IPP_PSTATE_STOPPED;
/* printer-state value */
if (!name || !device_uri || !uri || urisize < 32)
return (NULL);
if ((http = httpConnect2(cupsServer(), ippPort(), NULL, AF_UNSPEC, HTTP_ENCRYPTION_IF_REQUESTED, 1, 30000, NULL)) == NULL)
return (NULL);
request = ippNewRequest(IPP_OP_CUPS_CREATE_LOCAL_PRINTER);
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, "ipp://localhost/");
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser());
ippAddString(request, IPP_TAG_PRINTER, IPP_TAG_URI, "device-uri", NULL, device_uri);
ippAddString(request, IPP_TAG_PRINTER, IPP_TAG_NAME, "printer-name", NULL, name);
if (info)
ippAddString(request, IPP_TAG_PRINTER, IPP_TAG_TEXT, "printer-info", NULL, info);
if (device_id)
ippAddString(request, IPP_TAG_PRINTER, IPP_TAG_TEXT, "printer-device-id", NULL, device_id);
response = cupsDoRequest(http, request, "/");
if ((attr = ippFindAttribute(response, "printer-uri-supported", IPP_TAG_URI)) != NULL)
strlcpy(uri, ippGetString(attr, 0, NULL), urisize);
else
{
ippDelete(response);
httpClose(http);
return (NULL);
}
if ((attr = ippFindAttribute(response, "printer-state", IPP_TAG_ENUM)) != NULL)
state = (ipp_pstate_t)ippGetInteger(attr, 0);
while (state == IPP_PSTATE_STOPPED && cupsLastError() == IPP_STATUS_OK)
{
sleep(1);
ippDelete(response);
request = ippNewRequest(IPP_OP_GET_PRINTER_ATTRIBUTES);
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, uri);
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser());
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes", NULL, "printer-state");
response = cupsDoRequest(http, request, "/");
if ((attr = ippFindAttribute(response, "printer-state", IPP_TAG_ENUM)) != NULL)
state = (ipp_pstate_t)ippGetInteger(attr, 0);
}
ippDelete(response);
httpClose(http);
return (uri);
}
/*
* 'cupsEnumDests()' - Enumerate available destinations with a callback function.
*
* Destinations are enumerated from one or more sources. The callback function
* receives the @code user_data@ pointer and the destination pointer which can
* be used as input to the @link cupsCopyDest@ function. The function must
* return 1 to continue enumeration or 0 to stop.
*
* The @code type@ and @code mask@ arguments allow the caller to filter the
* destinations that are enumerated. Passing 0 for both will enumerate all
* printers. The constant @code CUPS_PRINTER_DISCOVERED@ is used to filter on
* destinations that are available but have not yet been added locally.
*
* Enumeration happens on the current thread and does not return until all
* destinations have been enumerated or the callback function returns 0.
*
* Note: The callback function will likely receive multiple updates for the same
* destinations - it is up to the caller to suppress any duplicate destinations.
*
* @since CUPS 1.6/macOS 10.8@
*/
int /* O - 1 on success, 0 on failure */
cupsEnumDests(
unsigned flags, /* I - Enumeration flags */
int msec, /* I - Timeout in milliseconds, -1 for indefinite */
int *cancel, /* I - Pointer to "cancel" variable */
cups_ptype_t type, /* I - Printer type bits */
cups_ptype_t mask, /* I - Mask for printer type bits */
cups_dest_cb_t cb, /* I - Callback function */
void *user_data) /* I - User data */
{
return (cups_enum_dests(CUPS_HTTP_DEFAULT, flags, msec, cancel, type, mask, cb, user_data));
}
# ifdef __BLOCKS__
/*
* 'cupsEnumDestsBlock()' - Enumerate available destinations with a block.
*
* Destinations are enumerated from one or more sources. The block receives the
* @code user_data@ pointer and the destination pointer which can be used as
* input to the @link cupsCopyDest@ function. The block must return 1 to
* continue enumeration or 0 to stop.
*
* The @code type@ and @code mask@ arguments allow the caller to filter the
* destinations that are enumerated. Passing 0 for both will enumerate all
* printers. The constant @code CUPS_PRINTER_DISCOVERED@ is used to filter on
* destinations that are available but have not yet been added locally.
*
* Enumeration happens on the current thread and does not return until all
* destinations have been enumerated or the block returns 0.
*
* Note: The block will likely receive multiple updates for the same
* destinations - it is up to the caller to suppress any duplicate destinations.
*
* @since CUPS 1.6/macOS 10.8@ @exclude all@
*/
int /* O - 1 on success, 0 on failure */
cupsEnumDestsBlock(
unsigned flags, /* I - Enumeration flags */
int timeout, /* I - Timeout in milliseconds, 0 for indefinite */
int *cancel, /* I - Pointer to "cancel" variable */
cups_ptype_t type, /* I - Printer type bits */
cups_ptype_t mask, /* I - Mask for printer type bits */
cups_dest_block_t block) /* I - Block */
{
return (cupsEnumDests(flags, timeout, cancel, type, mask,
(cups_dest_cb_t)cups_block_cb, (void *)block));
}
# endif /* __BLOCKS__ */
/*
* 'cupsFreeDests()' - Free the memory used by the list of destinations.
*/
void
cupsFreeDests(int num_dests, /* I - Number of destinations */
cups_dest_t *dests) /* I - Destinations */
{
int i; /* Looping var */
cups_dest_t *dest; /* Current destination */
if (num_dests == 0 || dests == NULL)
return;
for (i = num_dests, dest = dests; i > 0; i --, dest ++)
{
_cupsStrFree(dest->name);
_cupsStrFree(dest->instance);
cupsFreeOptions(dest->num_options, dest->options);
}
free(dests);
}
/*
* 'cupsGetDest()' - Get the named destination from the list.
*
* Use the @link cupsEnumDests@ or @link cupsGetDests2@ functions to get a
* list of supported destinations for the current user.
*/
cups_dest_t * /* O - Destination pointer or @code NULL@ */
cupsGetDest(const char *name, /* I - Destination name or @code NULL@ for the default destination */
const char *instance, /* I - Instance name or @code NULL@ */
int num_dests, /* I - Number of destinations */
cups_dest_t *dests) /* I - Destinations */
{
int diff, /* Result of comparison */
match; /* Matching index */
if (num_dests <= 0 || !dests)
return (NULL);
if (!name)
{
/*
* NULL name for default printer.
*/
while (num_dests > 0)
{
if (dests->is_default)
return (dests);
num_dests --;
dests ++;
}
}
else
{
/*
* Lookup name and optionally the instance...
*/
match = cups_find_dest(name, instance, num_dests, dests, -1, &diff);
if (!diff)
return (dests + match);
}
return (NULL);
}
/*
* '_cupsGetDestResource()' - Get the resource path and URI for a destination.
*/
const char * /* O - URI */
_cupsGetDestResource(
cups_dest_t *dest, /* I - Destination */
unsigned flags, /* I - Destination flags */
char *resource, /* I - Resource buffer */
size_t resourcesize) /* I - Size of resource buffer */
{
const char *uri, /* URI */
*device_uri, /* Device URI */
*printer_uri; /* Printer URI */
char scheme[32], /* URI scheme */
userpass[256], /* Username and password (unused) */
hostname[256]; /* Hostname */
int port; /* Port number */
DEBUG_printf(("_cupsGetDestResource(dest=%p(%s), flags=%u, resource=%p, resourcesize=%d)", (void *)dest, dest->name, flags, (void *)resource, (int)resourcesize));
/*
* Range check input...
*/
if (!dest || !resource || resourcesize < 1)
{
if (resource)
*resource = '\0';
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
return (NULL);
}
/*
* Grab the printer and device URIs...
*/
device_uri = cupsGetOption("device-uri", dest->num_options, dest->options);
printer_uri = cupsGetOption("printer-uri-supported", dest->num_options, dest->options);
DEBUG_printf(("1_cupsGetDestResource: device-uri=\"%s\", printer-uri-supported=\"%s\".", device_uri, printer_uri));
#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
if (((flags & CUPS_DEST_FLAGS_DEVICE) || !printer_uri) && strstr(device_uri, "._tcp"))
{
if ((device_uri = cups_dnssd_resolve(dest, device_uri, 5000, NULL, NULL, NULL)) != NULL)
{
DEBUG_printf(("1_cupsGetDestResource: Resolved device-uri=\"%s\".", device_uri));
}
else
{
DEBUG_puts("1_cupsGetDestResource: Unable to resolve device.");
if (resource)
*resource = '\0';
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(ENOENT), 0);
return (NULL);
}
}
#endif /* HAVE_DNSSD || HAVE_AVAHI */
if (flags & CUPS_DEST_FLAGS_DEVICE)
{
uri = device_uri;
}
else if (printer_uri)
{
uri = printer_uri;
}
else
{
uri = _cupsCreateDest(dest->name, cupsGetOption("printer-info", dest->num_options, dest->options), NULL, device_uri, resource, resourcesize);
if (uri)
{
DEBUG_printf(("1_cupsGetDestResource: Local printer-uri-supported=\"%s\"", uri));
dest->num_options = cupsAddOption("printer-uri-supported", uri, dest->num_options, &dest->options);
uri = cupsGetOption("printer-uri-supported", dest->num_options, dest->options);
}
}
if (!uri)
{
DEBUG_puts("1_cupsGetDestResource: No printer-uri-supported or device-uri found.");
if (resource)
*resource = '\0';
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(ENOENT), 0);
return (NULL);
}
else if (httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme, sizeof(scheme), userpass, sizeof(userpass), hostname, sizeof(hostname), &port, resource, (int)resourcesize) < HTTP_URI_STATUS_OK)
{
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad URI."), 1);
return (NULL);
}
DEBUG_printf(("1_cupsGetDestResource: resource=\"%s\"", resource));
return (uri);
}
/*
* 'cupsGetDestWithURI()' - Get a destination associated with a URI.
*
* "name" is the desired name for the printer. If @code NULL@, a name will be
* created using the URI.
*
* "uri" is the "ipp" or "ipps" URI for the printer.
*
* @since CUPS 2.0/macOS 10.10@
*/
cups_dest_t * /* O - Destination or @code NULL@ */
cupsGetDestWithURI(const char *name, /* I - Desired printer name or @code NULL@ */
const char *uri) /* I - URI for the printer */
{
cups_dest_t *dest; /* New destination */
char temp[1024], /* Temporary string */
scheme[256], /* Scheme from URI */
userpass[256], /* Username:password from URI */
hostname[256], /* Hostname from URI */
resource[1024], /* Resource path from URI */
*ptr; /* Pointer into string */
const char *info; /* printer-info string */
int port; /* Port number from URI */
/*
* Range check input...
*/
if (!uri)
{
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
return (NULL);
}
if (httpSeparateURI(HTTP_URI_CODING_ALL, uri, scheme, sizeof(scheme), userpass, sizeof(userpass), hostname, sizeof(hostname), &port, resource, sizeof(resource)) < HTTP_URI_STATUS_OK ||
(strncmp(uri, "ipp://", 6) && strncmp(uri, "ipps://", 7)))
{
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad printer-uri."), 1);
return (NULL);
}
if (name)
{
info = name;
}
else
{
/*
* Create the name from the URI...
*/
if (strstr(hostname, "._tcp"))
{
/*
* Use the service instance name...
*/
if ((ptr = strstr(hostname, "._")) != NULL)
*ptr = '\0';
cups_queue_name(temp, hostname, sizeof(temp));
name = temp;
info = hostname;
}
else if (!strncmp(resource, "/classes/", 9))
{
snprintf(temp, sizeof(temp), "%s @ %s", resource + 9, hostname);
name = resource + 9;
info = temp;
}
else if (!strncmp(resource, "/printers/", 10))
{
snprintf(temp, sizeof(temp), "%s @ %s", resource + 10, hostname);
name = resource + 10;
info = temp;
}
else if (!strncmp(resource, "/ipp/print/", 11))
{
snprintf(temp, sizeof(temp), "%s @ %s", resource + 11, hostname);
name = resource + 11;
info = temp;
}
else
{
name = hostname;
info = hostname;
}
}
/*
* Create the destination...
*/
if ((dest = calloc(1, sizeof(cups_dest_t))) == NULL)
{
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), 0);
return (NULL);
}
dest->name = _cupsStrAlloc(name);
dest->num_options = cupsAddOption("device-uri", uri, dest->num_options, &(dest->options));
dest->num_options = cupsAddOption("printer-info", info, dest->num_options, &(dest->options));
return (dest);
}
/*
* '_cupsGetDests()' - Get destinations from a server.
*
* "op" is IPP_OP_CUPS_GET_PRINTERS to get a full list, IPP_OP_CUPS_GET_DEFAULT
* to get the system-wide default printer, or IPP_OP_GET_PRINTER_ATTRIBUTES for
* a known printer.
*
* "name" is the name of an existing printer and is only used when "op" is
* IPP_OP_GET_PRINTER_ATTRIBUTES.
*
* "dest" is initialized to point to the array of destinations.
*
* 0 is returned if there are no printers, no default printer, or the named
* printer does not exist, respectively.
*
* Free the memory used by the destination array using the @link cupsFreeDests@
* function.
*
* Note: On macOS this function also gets the default paper from the system
* preferences (~/L/P/org.cups.PrintingPrefs.plist) and includes it in the
* options array for each destination that supports it.
*/
int /* O - Number of destinations */
_cupsGetDests(http_t *http, /* I - Connection to server or
* @code CUPS_HTTP_DEFAULT@ */
ipp_op_t op, /* I - IPP operation */
const char *name, /* I - Name of destination */
cups_dest_t **dests, /* IO - Destinations */
cups_ptype_t type, /* I - Printer type bits */
cups_ptype_t mask) /* I - Printer type mask */
{
int num_dests = 0; /* Number of destinations */
cups_dest_t *dest; /* Current destination */
ipp_t *request, /* IPP Request */
*response; /* IPP Response */
ipp_attribute_t *attr; /* Current attribute */
const char *printer_name; /* printer-name attribute */
char uri[1024]; /* printer-uri value */
int num_options; /* Number of options */
cups_option_t *options; /* Options */
#ifdef __APPLE__
char media_default[41]; /* Default paper size */
#endif /* __APPLE__ */
char optname[1024], /* Option name */
value[2048], /* Option value */
*ptr; /* Pointer into name/value */
static const char * const pattrs[] = /* Attributes we're interested in */
{
"auth-info-required",
"device-uri",
"job-sheets-default",
"marker-change-time",
"marker-colors",
"marker-high-levels",
"marker-levels",
"marker-low-levels",
"marker-message",
"marker-names",
"marker-types",
#ifdef __APPLE__
"media-supported",
#endif /* __APPLE__ */
"printer-commands",
"printer-defaults",
"printer-info",
"printer-is-accepting-jobs",
"printer-is-shared",
"printer-is-temporary",
"printer-location",
"printer-make-and-model",
"printer-mandatory-job-attributes",
"printer-name",
"printer-state",
"printer-state-change-time",
"printer-state-reasons",
"printer-type",
"printer-uri-supported"
};
DEBUG_printf(("_cupsGetDests(http=%p, op=%x(%s), name=\"%s\", dests=%p, type=%x, mask=%x)", (void *)http, op, ippOpString(op), name, (void *)dests, type, mask));
#ifdef __APPLE__
/*
* Get the default paper size...
*/
appleGetPaperSize(media_default, sizeof(media_default));
DEBUG_printf(("1_cupsGetDests: Default media is '%s'.", media_default));
#endif /* __APPLE__ */
/*
* Build a IPP_OP_CUPS_GET_PRINTERS or IPP_OP_GET_PRINTER_ATTRIBUTES request, which
* require the following attributes:
*
* attributes-charset
* attributes-natural-language
* requesting-user-name
* printer-uri [for IPP_OP_GET_PRINTER_ATTRIBUTES]
*/
request = ippNewRequest(op);
ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD,
"requested-attributes", sizeof(pattrs) / sizeof(pattrs[0]),
NULL, pattrs);
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME,
"requesting-user-name", NULL, cupsUser());
if (name && op != IPP_OP_CUPS_GET_DEFAULT)
{
httpAssembleURIf(HTTP_URI_CODING_ALL, uri, sizeof(uri), "ipp", NULL,
"localhost", ippPort(), "/printers/%s", name);
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL,
uri);
}
else if (mask)
{
ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_ENUM, "printer-type", (int)type);
ippAddInteger(request, IPP_TAG_OPERATION, IPP_TAG_ENUM, "printer-type-mask", (int)mask);
}
/*
* Do the request and get back a response...
*/
if ((response = cupsDoRequest(http, request, "/")) != NULL)
{
for (attr = response->attrs; attr != NULL; attr = attr->next)
{
/*
* Skip leading attributes until we hit a printer...
*/
while (attr != NULL && attr->group_tag != IPP_TAG_PRINTER)
attr = attr->next;
if (attr == NULL)
break;
/*
* Pull the needed attributes from this printer...
*/
printer_name = NULL;
num_options = 0;
options = NULL;
for (; attr && attr->group_tag == IPP_TAG_PRINTER; attr = attr->next)
{
if (attr->value_tag != IPP_TAG_INTEGER &&
attr->value_tag != IPP_TAG_ENUM &&
attr->value_tag != IPP_TAG_BOOLEAN &&
attr->value_tag != IPP_TAG_TEXT &&
attr->value_tag != IPP_TAG_TEXTLANG &&
attr->value_tag != IPP_TAG_NAME &&
attr->value_tag != IPP_TAG_NAMELANG &&
attr->value_tag != IPP_TAG_KEYWORD &&
attr->value_tag != IPP_TAG_RANGE &&
attr->value_tag != IPP_TAG_URI)
continue;
if (!strcmp(attr->name, "auth-info-required") ||
!strcmp(attr->name, "device-uri") ||
!strcmp(attr->name, "marker-change-time") ||
!strcmp(attr->name, "marker-colors") ||
!strcmp(attr->name, "marker-high-levels") ||
!strcmp(attr->name, "marker-levels") ||
!strcmp(attr->name, "marker-low-levels") ||
!strcmp(attr->name, "marker-message") ||
!strcmp(attr->name, "marker-names") ||
!strcmp(attr->name, "marker-types") ||
!strcmp(attr->name, "printer-commands") ||
!strcmp(attr->name, "printer-info") ||
!strcmp(attr->name, "printer-is-shared") ||
!strcmp(attr->name, "printer-is-temporary") ||
!strcmp(attr->name, "printer-make-and-model") ||
!strcmp(attr->name, "printer-mandatory-job-attributes") ||
!strcmp(attr->name, "printer-state") ||
!strcmp(attr->name, "printer-state-change-time") ||
!strcmp(attr->name, "printer-type") ||
!strcmp(attr->name, "printer-is-accepting-jobs") ||
!strcmp(attr->name, "printer-location") ||
!strcmp(attr->name, "printer-state-reasons") ||
!strcmp(attr->name, "printer-uri-supported"))
{
/*
* Add a printer description attribute...
*/
num_options = cupsAddOption(attr->name,
cups_make_string(attr, value,
sizeof(value)),
num_options, &options);
}
#ifdef __APPLE__
else if (!strcmp(attr->name, "media-supported") && media_default[0])
{
/*
* See if we can set a default media size...
*/
int i; /* Looping var */
for (i = 0; i < attr->num_values; i ++)
if (!_cups_strcasecmp(media_default, attr->values[i].string.text))
{
DEBUG_printf(("1_cupsGetDests: Setting media to '%s'.", media_default));
num_options = cupsAddOption("media", media_default, num_options, &options);
break;
}
}
#endif /* __APPLE__ */
else if (!strcmp(attr->name, "printer-name") &&
attr->value_tag == IPP_TAG_NAME)
printer_name = attr->values[0].string.text;
else if (strncmp(attr->name, "notify-", 7) &&
strncmp(attr->name, "print-quality-", 14) &&
(attr->value_tag == IPP_TAG_BOOLEAN ||
attr->value_tag == IPP_TAG_ENUM ||
attr->value_tag == IPP_TAG_INTEGER ||
attr->value_tag == IPP_TAG_KEYWORD ||
attr->value_tag == IPP_TAG_NAME ||
attr->value_tag == IPP_TAG_RANGE) &&
(ptr = strstr(attr->name, "-default")) != NULL)
{
/*
* Add a default option...
*/
strlcpy(optname, attr->name, sizeof(optname));
optname[ptr - attr->name] = '\0';
if (_cups_strcasecmp(optname, "media") || !cupsGetOption("media", num_options, options))
num_options = cupsAddOption(optname, cups_make_string(attr, value, sizeof(value)), num_options, &options);
}
}
/*
* See if we have everything needed...
*/
if (!printer_name)
{
cupsFreeOptions(num_options, options);
if (attr == NULL)
break;
else
continue;
}
if ((dest = cups_add_dest(printer_name, NULL, &num_dests, dests)) != NULL)
{
dest->num_options = num_options;
dest->options = options;
}
else
cupsFreeOptions(num_options, options);
if (attr == NULL)
break;
}
ippDelete(response);
}
/*
* Return the count...
*/
return (num_dests);
}
/*
* 'cupsGetDests()' - Get the list of destinations from the default server.
*
* Starting with CUPS 1.2, the returned list of destinations include the
* "printer-info", "printer-is-accepting-jobs", "printer-is-shared",
* "printer-make-and-model", "printer-state", "printer-state-change-time",
* "printer-state-reasons", "printer-type", and "printer-uri-supported"
* attributes as options.
*
* CUPS 1.4 adds the "marker-change-time", "marker-colors",
* "marker-high-levels", "marker-levels", "marker-low-levels", "marker-message",
* "marker-names", "marker-types", and "printer-commands" attributes as options.
*
* CUPS 2.2 adds accessible IPP printers to the list of destinations that can
* be used. The "printer-uri-supported" option will be present for those IPP
* printers that have been recently used.
*
* Use the @link cupsFreeDests@ function to free the destination list and
* the @link cupsGetDest@ function to find a particular destination.
*
* @exclude all@
*/
int /* O - Number of destinations */
cupsGetDests(cups_dest_t **dests) /* O - Destinations */
{
return (cupsGetDests2(CUPS_HTTP_DEFAULT, dests));
}
/*
* 'cupsGetDests2()' - Get the list of destinations from the specified server.
*
* Starting with CUPS 1.2, the returned list of destinations include the
* "printer-info", "printer-is-accepting-jobs", "printer-is-shared",
* "printer-make-and-model", "printer-state", "printer-state-change-time",
* "printer-state-reasons", "printer-type", and "printer-uri-supported"
* attributes as options.
*
* CUPS 1.4 adds the "marker-change-time", "marker-colors",
* "marker-high-levels", "marker-levels", "marker-low-levels", "marker-message",
* "marker-names", "marker-types", and "printer-commands" attributes as options.
*
* CUPS 2.2 adds accessible IPP printers to the list of destinations that can
* be used. The "printer-uri-supported" option will be present for those IPP
* printers that have been recently used.
*
* Use the @link cupsFreeDests@ function to free the destination list and
* the @link cupsGetDest@ function to find a particular destination.
*
* @since CUPS 1.1.21/macOS 10.4@
*/
int /* O - Number of destinations */
cupsGetDests2(http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
cups_dest_t **dests) /* O - Destinations */
{
_cups_getdata_t data; /* Enumeration data */
DEBUG_printf(("cupsGetDests2(http=%p, dests=%p)", (void *)http, (void *)dests));
/*
* Range check the input...
*/
if (!dests)
{
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Bad NULL dests pointer"), 1);
DEBUG_puts("1cupsGetDests2: NULL dests pointer, returning 0.");
return (0);
}
/*
* Connect to the server as needed...
*/
if (!http)
{
if ((http = _cupsConnect()) == NULL)
{
*dests = NULL;
return (0);
}
}
/*
* Grab the printers and classes...
*/
data.num_dests = 0;
data.dests = NULL;
if (!httpAddrLocalhost(httpGetAddress(http)))
{
/*
* When talking to a remote cupsd, just enumerate printers on the remote
* cupsd.
*/
cups_enum_dests(http, 0, _CUPS_DNSSD_GET_DESTS, NULL, 0, CUPS_PRINTER_DISCOVERED, (cups_dest_cb_t)cups_get_cb, &data);
}
else
{
/*
* When talking to a local cupsd, enumerate both local printers and ones we
* can find on the network...
*/
cups_enum_dests(http, 0, _CUPS_DNSSD_GET_DESTS, NULL, 0, 0, (cups_dest_cb_t)cups_get_cb, &data);
}
/*
* Return the number of destinations...
*/
*dests = data.dests;
if (data.num_dests > 0)
_cupsSetError(IPP_STATUS_OK, NULL, 0);
DEBUG_printf(("1cupsGetDests2: Returning %d destinations.", data.num_dests));
return (data.num_dests);
}
/*
* 'cupsGetNamedDest()' - Get options for the named destination.
*
* This function is optimized for retrieving a single destination and should
* be used instead of @link cupsGetDests2@ and @link cupsGetDest@ when you
* either know the name of the destination or want to print to the default
* destination. If @code NULL@ is returned, the destination does not exist or
* there is no default destination.
*
* If "http" is @code CUPS_HTTP_DEFAULT@, the connection to the default print
* server will be used.
*
* If "name" is @code NULL@, the default printer for the current user will be
* returned.
*
* The returned destination must be freed using @link cupsFreeDests@ with a
* "num_dests" value of 1.
*
* @since CUPS 1.4/macOS 10.6@
*/
cups_dest_t * /* O - Destination or @code NULL@ */
cupsGetNamedDest(http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
const char *name, /* I - Destination name or @code NULL@ for the default destination */
const char *instance) /* I - Instance name or @code NULL@ */
{
const char *dest_name; /* Working destination name */
cups_dest_t *dest; /* Destination */
char filename[1024], /* Path to lpoptions */
defname[256]; /* Default printer name */
int set_as_default = 0; /* Set returned destination as default */
ipp_op_t op = IPP_OP_GET_PRINTER_ATTRIBUTES;
/* IPP operation to get server ops */
_cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
DEBUG_printf(("cupsGetNamedDest(http=%p, name=\"%s\", instance=\"%s\")", (void *)http, name, instance));
/*
* If "name" is NULL, find the default destination...
*/
dest_name = name;
if (!dest_name)
{
set_as_default = 1;
dest_name = _cupsUserDefault(defname, sizeof(defname));
if (dest_name)
{
char *ptr; /* Temporary pointer... */
if ((ptr = strchr(defname, '/')) != NULL)
{
*ptr++ = '\0';
instance = ptr;
}
else
instance = NULL;
}
else if (cg->home)
{
/*
* No default in the environment, try the user's lpoptions files...
*/
snprintf(filename, sizeof(filename), "%s/.cups/lpoptions", cg->home);
dest_name = cups_get_default(filename, defname, sizeof(defname), &instance);
if (dest_name)
set_as_default = 2;
}
if (!dest_name)
{
/*
* Still not there? Try the system lpoptions file...
*/
snprintf(filename, sizeof(filename), "%s/lpoptions", cg->cups_serverroot);
dest_name = cups_get_default(filename, defname, sizeof(defname), &instance);
if (dest_name)
set_as_default = 3;
}
if (!dest_name)
{
/*
* No locally-set default destination, ask the server...
*/
op = IPP_OP_CUPS_GET_DEFAULT;
set_as_default = 4;
DEBUG_puts("1cupsGetNamedDest: Asking server for default printer...");
}
else
DEBUG_printf(("1cupsGetNamedDest: Using name=\"%s\"...", name));
}
/*
* Get the printer's attributes...
*/
if (!_cupsGetDests(http, op, dest_name, &dest, 0, 0))
{
if (name)
{
_cups_namedata_t data; /* Callback data */
DEBUG_puts("1cupsGetNamedDest: No queue found for printer, looking on network...");
data.name = name;
data.dest = NULL;
cupsEnumDests(0, 1000, NULL, 0, 0, (cups_dest_cb_t)cups_name_cb, &data);
if (!data.dest)
{
_cupsSetError(IPP_STATUS_ERROR_NOT_FOUND, _("The printer or class does not exist."), 1);
return (NULL);
}
dest = data.dest;
}
else
{
switch (set_as_default)
{
default :
break;
case 1 : /* Set from env vars */
if (getenv("LPDEST"))
_cupsSetError(IPP_STATUS_ERROR_NOT_FOUND, _("LPDEST environment variable names default destination that does not exist."), 1);
else if (getenv("PRINTER"))
_cupsSetError(IPP_STATUS_ERROR_NOT_FOUND, _("PRINTER environment variable names default destination that does not exist."), 1);
else
_cupsSetError(IPP_STATUS_ERROR_NOT_FOUND, _("No default destination."), 1);
break;
case 2 : /* Set from ~/.cups/lpoptions */
_cupsSetError(IPP_STATUS_ERROR_NOT_FOUND, _("~/.cups/lpoptions file names default destination that does not exist."), 1);
break;
case 3 : /* Set from /etc/cups/lpoptions */
_cupsSetError(IPP_STATUS_ERROR_NOT_FOUND, _("/etc/cups/lpoptions file names default destination that does not exist."), 1);
break;
case 4 : /* Set from server */
_cupsSetError(IPP_STATUS_ERROR_NOT_FOUND, _("No default destination."), 1);
break;
}
return (NULL);
}
}
DEBUG_printf(("1cupsGetNamedDest: Got dest=%p", (void *)dest));
if (instance)
dest->instance = _cupsStrAlloc(instance);
if (set_as_default)
dest->is_default = 1;
/*
* Then add local options...
*/
snprintf(filename, sizeof(filename), "%s/lpoptions", cg->cups_serverroot);
cups_get_dests(filename, dest_name, instance, 0, 1, 1, &dest);
if (cg->home)
{
snprintf(filename, sizeof(filename), "%s/.cups/lpoptions", cg->home);
cups_get_dests(filename, dest_name, instance, 0, 1, 1, &dest);
}
/*
* Return the result...
*/
return (dest);
}
/*
* 'cupsRemoveDest()' - Remove a destination from the destination list.
*
* Removing a destination/instance does not delete the class or printer
* queue, merely the lpoptions for that destination/instance. Use the
* @link cupsSetDests@ or @link cupsSetDests2@ functions to save the new
* options for the user.
*
* @since CUPS 1.3/macOS 10.5@
*/
int /* O - New number of destinations */
cupsRemoveDest(const char *name, /* I - Destination name */
const char *instance, /* I - Instance name or @code NULL@ */
int num_dests, /* I - Number of destinations */
cups_dest_t **dests) /* IO - Destinations */
{
int i; /* Index into destinations */
cups_dest_t *dest; /* Pointer to destination */
/*
* Find the destination...
*/
if ((dest = cupsGetDest(name, instance, num_dests, *dests)) == NULL)
return (num_dests);
/*
* Free memory...
*/
_cupsStrFree(dest->name);
_cupsStrFree(dest->instance);
cupsFreeOptions(dest->num_options, dest->options);
/*
* Remove the destination from the array...
*/
num_dests --;
i = (int)(dest - *dests);
if (i < num_dests)
memmove(dest, dest + 1, (size_t)(num_dests - i) * sizeof(cups_dest_t));
return (num_dests);
}
/*
* 'cupsSetDefaultDest()' - Set the default destination.
*
* @since CUPS 1.3/macOS 10.5@
*/
void
cupsSetDefaultDest(
const char *name, /* I - Destination name */
const char *instance, /* I - Instance name or @code NULL@ */
int num_dests, /* I - Number of destinations */
cups_dest_t *dests) /* I - Destinations */
{
int i; /* Looping var */
cups_dest_t *dest; /* Current destination */
/*
* Range check input...
*/
if (!name || num_dests <= 0 || !dests)
return;
/*
* Loop through the array and set the "is_default" flag for the matching
* destination...
*/
for (i = num_dests, dest = dests; i > 0; i --, dest ++)
dest->is_default = !_cups_strcasecmp(name, dest->name) &&
((!instance && !dest->instance) ||
(instance && dest->instance &&
!_cups_strcasecmp(instance, dest->instance)));
}
/*
* 'cupsSetDests()' - Save the list of destinations for the default server.
*
* This function saves the destinations to /etc/cups/lpoptions when run
* as root and ~/.cups/lpoptions when run as a normal user.
*
* @exclude all@
*/
void
cupsSetDests(int num_dests, /* I - Number of destinations */
cups_dest_t *dests) /* I - Destinations */
{
cupsSetDests2(CUPS_HTTP_DEFAULT, num_dests, dests);
}
/*
* 'cupsSetDests2()' - Save the list of destinations for the specified server.
*
* This function saves the destinations to /etc/cups/lpoptions when run
* as root and ~/.cups/lpoptions when run as a normal user.
*
* @since CUPS 1.1.21/macOS 10.4@
*/
int /* O - 0 on success, -1 on error */
cupsSetDests2(http_t *http, /* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
int num_dests, /* I - Number of destinations */
cups_dest_t *dests) /* I - Destinations */
{
int i, j; /* Looping vars */
int wrote; /* Wrote definition? */
cups_dest_t *dest; /* Current destination */
cups_option_t *option; /* Current option */
_ipp_option_t *match; /* Matching attribute for option */
FILE *fp; /* File pointer */
char filename[1024]; /* lpoptions file */
int num_temps; /* Number of temporary destinations */
cups_dest_t *temps = NULL, /* Temporary destinations */
*temp; /* Current temporary dest */
const char *val; /* Value of temporary option */
_cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
/*
* Range check the input...
*/
if (!num_dests || !dests)
return (-1);
/*
* Get the server destinations...
*/
num_temps = _cupsGetDests(http, IPP_OP_CUPS_GET_PRINTERS, NULL, &temps, 0, 0);
if (cupsLastError() >= IPP_STATUS_REDIRECTION_OTHER_SITE)
{
cupsFreeDests(num_temps, temps);
return (-1);
}
/*
* Figure out which file to write to...
*/
snprintf(filename, sizeof(filename), "%s/lpoptions", cg->cups_serverroot);
if (cg->home)
{
/*
* Create ~/.cups subdirectory...
*/
snprintf(filename, sizeof(filename), "%s/.cups", cg->home);
if (access(filename, 0))
mkdir(filename, 0700);
snprintf(filename, sizeof(filename), "%s/.cups/lpoptions", cg->home);
}
/*
* Try to open the file...
*/
if ((fp = fopen(filename, "w")) == NULL)
{
cupsFreeDests(num_temps, temps);
return (-1);
}
#ifndef _WIN32
/*
* Set the permissions to 0644 when saving to the /etc/cups/lpoptions
* file...
*/
if (!getuid())
fchmod(fileno(fp), 0644);
#endif /* !_WIN32 */
/*
* Write each printer; each line looks like:
*
* Dest name[/instance] options
* Default name[/instance] options
*/
for (i = num_dests, dest = dests; i > 0; i --, dest ++)
if (dest->instance != NULL || dest->num_options != 0 || dest->is_default)
{
if (dest->is_default)
{
fprintf(fp, "Default %s", dest->name);
if (dest->instance)
fprintf(fp, "/%s", dest->instance);
wrote = 1;
}
else
wrote = 0;
temp = cupsGetDest(dest->name, NULL, num_temps, temps);
for (j = dest->num_options, option = dest->options; j > 0; j --, option ++)
{
/*
* See if this option is a printer attribute; if so, skip it...
*/
if ((match = _ippFindOption(option->name)) != NULL && match->group_tag == IPP_TAG_PRINTER)
continue;
/*
* See if the server options match these; if so, don't write 'em.
*/
if (temp && (val = cupsGetOption(option->name, temp->num_options, temp->options)) != NULL && !_cups_strcasecmp(val, option->value))
continue;
/*
* Options don't match, write to the file...
*/
if (!wrote)
{
fprintf(fp, "Dest %s", dest->name);
if (dest->instance)
fprintf(fp, "/%s", dest->instance);
wrote = 1;
}
if (option->value[0])
{
if (strchr(option->value, ' ') || strchr(option->value, '\\') || strchr(option->value, '\"') || strchr(option->value, '\''))
{
/*
* Quote the value...
*/
fprintf(fp, " %s=\"", option->name);
for (val = option->value; *val; val ++)
{
if (strchr("\"\'\\", *val))
putc('\\', fp);
putc(*val, fp);
}
putc('\"', fp);
}
else
{
/*
* Store the literal value...
*/
fprintf(fp, " %s=%s", option->name, option->value);
}
}
else
fprintf(fp, " %s", option->name);
}
if (wrote)
fputs("\n", fp);
}
/*
* Free the temporary destinations and close the file...
*/
cupsFreeDests(num_temps, temps);
fclose(fp);
#ifdef __APPLE__
/*
* Set the default printer for this location - this allows command-line
* and GUI applications to share the same default destination...
*/
if ((dest = cupsGetDest(NULL, NULL, num_dests, dests)) != NULL)
{
CFStringRef name = CFStringCreateWithCString(kCFAllocatorDefault, dest->name, kCFStringEncodingUTF8);
/* Default printer name */
if (name)
{
_cupsAppleSetDefaultPrinter(name);
CFRelease(name);
}
}
#endif /* __APPLE__ */
#ifdef HAVE_NOTIFY_POST
/*
* Send a notification so that macOS applications can know about the
* change, too.
*/
notify_post("com.apple.printerListChange");
#endif /* HAVE_NOTIFY_POST */
return (0);
}
/*
* '_cupsUserDefault()' - Get the user default printer from environment
* variables and location information.
*/
char * /* O - Default printer or NULL */
_cupsUserDefault(char *name, /* I - Name buffer */
size_t namesize) /* I - Size of name buffer */
{
const char *env; /* LPDEST or PRINTER env variable */
#ifdef __APPLE__
CFStringRef locprinter; /* Last printer as this location */
#endif /* __APPLE__ */
if ((env = getenv("LPDEST")) == NULL)
if ((env = getenv("PRINTER")) != NULL && !strcmp(env, "lp"))
env = NULL;
if (env)
{
strlcpy(name, env, namesize);
return (name);
}
#ifdef __APPLE__
/*
* Use location-based defaults if "use last printer" is selected in the
* system preferences...
*/
if (!getenv("CUPS_NO_APPLE_DEFAULT") && (locprinter = _cupsAppleCopyDefaultPrinter()) != NULL)
{
CFStringGetCString(locprinter, name, (CFIndex)namesize, kCFStringEncodingUTF8);
CFRelease(locprinter);
}
else
name[0] = '\0';
DEBUG_printf(("1_cupsUserDefault: Returning \"%s\".", name));
return (*name ? name : NULL);
#else
/*
* No location-based defaults on this platform...
*/
name[0] = '\0';
return (NULL);
#endif /* __APPLE__ */
}
#if _CUPS_LOCATION_DEFAULTS
/*
* 'appleCopyLocations()' - Copy the location history array.
*/
static CFArrayRef /* O - Location array or NULL */
appleCopyLocations(void)
{
CFArrayRef locations; /* Location array */
/*
* Look up the location array in the preferences...
*/
if ((locations = CFPreferencesCopyAppValue(kLastUsedPrintersKey,
kCUPSPrintingPrefs)) == NULL)
return (NULL);
if (CFGetTypeID(locations) != CFArrayGetTypeID())
{
CFRelease(locations);
return (NULL);
}
return (locations);
}
/*
* 'appleCopyNetwork()' - Get the network ID for the current location.
*/
static CFStringRef /* O - Network ID */
appleCopyNetwork(void)
{
SCDynamicStoreRef dynamicStore; /* System configuration data */
CFStringRef key; /* Current network configuration key */
CFDictionaryRef ip_dict; /* Network configuration data */
CFStringRef network = NULL; /* Current network ID */
if ((dynamicStore = SCDynamicStoreCreate(NULL, CFSTR("libcups"), NULL,
NULL)) != NULL)
{
/*
* First use the IPv6 router address, if available, since that will generally
* be a globally-unique link-local address.
*/
if ((key = SCDynamicStoreKeyCreateNetworkGlobalEntity(
NULL, kSCDynamicStoreDomainState, kSCEntNetIPv6)) != NULL)
{
if ((ip_dict = SCDynamicStoreCopyValue(dynamicStore, key)) != NULL)
{
if ((network = CFDictionaryGetValue(ip_dict,
kSCPropNetIPv6Router)) != NULL)
CFRetain(network);
CFRelease(ip_dict);
}
CFRelease(key);
}
/*
* If that doesn't work, try the IPv4 router address. This isn't as unique
* and will likely be a 10.x.y.z or 192.168.y.z address...
*/
if (!network)
{
if ((key = SCDynamicStoreKeyCreateNetworkGlobalEntity(
NULL, kSCDynamicStoreDomainState, kSCEntNetIPv4)) != NULL)
{
if ((ip_dict = SCDynamicStoreCopyValue(dynamicStore, key)) != NULL)
{
if ((network = CFDictionaryGetValue(ip_dict,
kSCPropNetIPv4Router)) != NULL)
CFRetain(network);
CFRelease(ip_dict);
}
CFRelease(key);
}
}
CFRelease(dynamicStore);
}
return (network);
}
#endif /* _CUPS_LOCATION_DEFAULTS */
#ifdef __APPLE__
/*
* 'appleGetPaperSize()' - Get the default paper size.
*/
static char * /* O - Default paper size */
appleGetPaperSize(char *name, /* I - Paper size name buffer */
size_t namesize) /* I - Size of buffer */
{
CFStringRef defaultPaperID; /* Default paper ID */
pwg_media_t *pwgmedia; /* PWG media size */
defaultPaperID = _cupsAppleCopyDefaultPaperID();
if (!defaultPaperID ||
CFGetTypeID(defaultPaperID) != CFStringGetTypeID() ||
!CFStringGetCString(defaultPaperID, name, (CFIndex)namesize, kCFStringEncodingUTF8))
name[0] = '\0';
else if ((pwgmedia = pwgMediaForLegacy(name)) != NULL)
strlcpy(name, pwgmedia->pwg, namesize);
if (defaultPaperID)
CFRelease(defaultPaperID);
return (name);
}
#endif /* __APPLE__ */
#if _CUPS_LOCATION_DEFAULTS
/*
* 'appleGetPrinter()' - Get a printer from the history array.
*/
static CFStringRef /* O - Printer name or NULL */
appleGetPrinter(CFArrayRef locations, /* I - Location array */
CFStringRef network, /* I - Network name */
CFIndex *locindex) /* O - Index in array */
{
CFIndex i, /* Looping var */
count; /* Number of locations */
CFDictionaryRef location; /* Current location */
CFStringRef locnetwork, /* Current network */
locprinter; /* Current printer */
for (i = 0, count = CFArrayGetCount(locations); i < count; i ++)
if ((location = CFArrayGetValueAtIndex(locations, i)) != NULL &&
CFGetTypeID(location) == CFDictionaryGetTypeID())
{
if ((locnetwork = CFDictionaryGetValue(location,
kLocationNetworkKey)) != NULL &&
CFGetTypeID(locnetwork) == CFStringGetTypeID() &&
CFStringCompare(network, locnetwork, 0) == kCFCompareEqualTo &&
(locprinter = CFDictionaryGetValue(location,
kLocationPrinterIDKey)) != NULL &&
CFGetTypeID(locprinter) == CFStringGetTypeID())
{
if (locindex)
*locindex = i;
return (locprinter);
}
}
return (NULL);
}
#endif /* _CUPS_LOCATION_DEFAULTS */
/*
* 'cups_add_dest()' - Add a destination to the array.
*
* Unlike cupsAddDest(), this function does not check for duplicates.
*/
static cups_dest_t * /* O - New destination */
cups_add_dest(const char *name, /* I - Name of destination */
const char *instance, /* I - Instance or NULL */
int *num_dests, /* IO - Number of destinations */
cups_dest_t **dests) /* IO - Destinations */
{
int insert, /* Insertion point */
diff; /* Result of comparison */
cups_dest_t *dest; /* Destination pointer */
/*
* Add new destination...
*/
if (*num_dests == 0)
dest = malloc(sizeof(cups_dest_t));
else
dest = realloc(*dests, sizeof(cups_dest_t) * (size_t)(*num_dests + 1));
if (!dest)
return (NULL);
*dests = dest;
/*
* Find where to insert the destination...
*/
if (*num_dests == 0)
insert = 0;
else
{
insert = cups_find_dest(name, instance, *num_dests, *dests, *num_dests - 1,
&diff);
if (diff > 0)
insert ++;
}
/*
* Move the array elements as needed...
*/
if (insert < *num_dests)
memmove(*dests + insert + 1, *dests + insert, (size_t)(*num_dests - insert) * sizeof(cups_dest_t));
(*num_dests) ++;
/*
* Initialize the destination...
*/
dest = *dests + insert;
dest->name = _cupsStrAlloc(name);
dest->instance = _cupsStrAlloc(instance);
dest->is_default = 0;
dest->num_options = 0;
dest->options = (cups_option_t *)0;
return (dest);
}
# ifdef __BLOCKS__
/*
* 'cups_block_cb()' - Enumeration callback for block API.
*/
static int /* O - 1 to continue, 0 to stop */
cups_block_cb(
cups_dest_block_t block, /* I - Block */
unsigned flags, /* I - Destination flags */
cups_dest_t *dest) /* I - Destination */
{
return ((block)(flags, dest));
}
# endif /* __BLOCKS__ */
/*
* 'cups_compare_dests()' - Compare two destinations.
*/
static int /* O - Result of comparison */
cups_compare_dests(cups_dest_t *a, /* I - First destination */
cups_dest_t *b) /* I - Second destination */
{
int diff; /* Difference */
if ((diff = _cups_strcasecmp(a->name, b->name)) != 0)
return (diff);
else if (a->instance && b->instance)
return (_cups_strcasecmp(a->instance, b->instance));
else
return ((a->instance && !b->instance) - (!a->instance && b->instance));
}
#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
# ifdef HAVE_DNSSD
/*
* 'cups_dnssd_browse_cb()' - Browse for printers.
*/
static void
cups_dnssd_browse_cb(
DNSServiceRef sdRef, /* I - Service reference */
DNSServiceFlags flags, /* I - Option flags */
uint32_t interfaceIndex, /* I - Interface number */
DNSServiceErrorType errorCode, /* I - Error, if any */
const char *serviceName, /* I - Name of service/device */
const char *regtype, /* I - Type of service */
const char *replyDomain, /* I - Service domain */
void *context) /* I - Enumeration data */
{
_cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
/* Enumeration data */
DEBUG_printf(("5cups_dnssd_browse_cb(sdRef=%p, flags=%x, interfaceIndex=%d, errorCode=%d, serviceName=\"%s\", regtype=\"%s\", replyDomain=\"%s\", context=%p)", (void *)sdRef, flags, interfaceIndex, errorCode, serviceName, regtype, replyDomain, context));
/*
* Don't do anything on error...
*/
if (errorCode != kDNSServiceErr_NoError)
return;
/*
* Get the device...
*/
cups_dnssd_get_device(data, serviceName, regtype, replyDomain);
}
# else /* HAVE_AVAHI */
/*
* 'cups_dnssd_browse_cb()' - Browse for printers.
*/
static void
cups_dnssd_browse_cb(
AvahiServiceBrowser *browser, /* I - Browser */
AvahiIfIndex interface, /* I - Interface index (unused) */
AvahiProtocol protocol, /* I - Network protocol (unused) */
AvahiBrowserEvent event, /* I - What happened */
const char *name, /* I - Service name */
const char *type, /* I - Registration type */
const char *domain, /* I - Domain */
AvahiLookupResultFlags flags, /* I - Flags */
void *context) /* I - Devices array */
{
#ifdef DEBUG
AvahiClient *client = avahi_service_browser_get_client(browser);
/* Client information */
#endif /* DEBUG */
_cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
/* Enumeration data */
(void)interface;
(void)protocol;
(void)context;
DEBUG_printf(("cups_dnssd_browse_cb(..., name=\"%s\", type=\"%s\", domain=\"%s\", ...);", name, type, domain));
switch (event)
{
case AVAHI_BROWSER_FAILURE:
DEBUG_printf(("cups_dnssd_browse_cb: %s", avahi_strerror(avahi_client_errno(client))));
avahi_simple_poll_quit(data->simple_poll);
break;
case AVAHI_BROWSER_NEW:
/*
* This object is new on the network.
*/
cups_dnssd_get_device(data, name, type, domain);
break;
case AVAHI_BROWSER_REMOVE :
case AVAHI_BROWSER_CACHE_EXHAUSTED :
break;
case AVAHI_BROWSER_ALL_FOR_NOW :
DEBUG_puts("cups_dnssd_browse_cb: ALL_FOR_NOW");
data->browsers --;
break;
}
}
/*
* 'cups_dnssd_client_cb()' - Avahi client callback function.
*/
static void
cups_dnssd_client_cb(
AvahiClient *client, /* I - Client information (unused) */
AvahiClientState state, /* I - Current state */
void *context) /* I - User data (unused) */
{
_cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
/* Enumeration data */
(void)client;
DEBUG_printf(("cups_dnssd_client_cb(client=%p, state=%d, context=%p)", client, state, context));
/*
* If the connection drops, quit.
*/
if (state == AVAHI_CLIENT_FAILURE)
{
DEBUG_puts("cups_dnssd_client_cb: Avahi connection failed.");
avahi_simple_poll_quit(data->simple_poll);
}
}
# endif /* HAVE_DNSSD */
/*
* 'cups_dnssd_compare_device()' - Compare two devices.
*/
static int /* O - Result of comparison */
cups_dnssd_compare_devices(
_cups_dnssd_device_t *a, /* I - First device */
_cups_dnssd_device_t *b) /* I - Second device */
{
return (strcmp(a->dest.name, b->dest.name));
}
/*
* 'cups_dnssd_free_device()' - Free the memory used by a device.
*/
static void
cups_dnssd_free_device(
_cups_dnssd_device_t *device, /* I - Device */
_cups_dnssd_data_t *data) /* I - Enumeration data */
{
DEBUG_printf(("5cups_dnssd_free_device(device=%p(%s), data=%p)", (void *)device, device->dest.name, (void *)data));
# ifdef HAVE_DNSSD
if (device->ref)
DNSServiceRefDeallocate(device->ref);
# else /* HAVE_AVAHI */
if (device->ref)
avahi_record_browser_free(device->ref);
# endif /* HAVE_DNSSD */
_cupsStrFree(device->domain);
_cupsStrFree(device->fullName);
_cupsStrFree(device->regtype);
_cupsStrFree(device->dest.name);
cupsFreeOptions(device->dest.num_options, device->dest.options);
free(device);
}
/*
* 'cups_dnssd_get_device()' - Lookup a device and create it as needed.
*/
static _cups_dnssd_device_t * /* O - Device */
cups_dnssd_get_device(
_cups_dnssd_data_t *data, /* I - Enumeration data */
const char *serviceName, /* I - Service name */
const char *regtype, /* I - Registration type */
const char *replyDomain) /* I - Domain name */
{
_cups_dnssd_device_t key, /* Search key */
*device; /* Device */
char fullName[kDNSServiceMaxDomainName],
/* Full name for query */
name[128]; /* Queue name */
DEBUG_printf(("5cups_dnssd_get_device(data=%p, serviceName=\"%s\", regtype=\"%s\", replyDomain=\"%s\")", (void *)data, serviceName, regtype, replyDomain));
/*
* See if this is an existing device...
*/
cups_queue_name(name, serviceName, sizeof(name));
key.dest.name = name;
if ((device = cupsArrayFind(data->devices, &key)) != NULL)
{
/*
* Yes, see if we need to do anything with this...
*/
int update = 0; /* Non-zero if we need to update */
if (!_cups_strcasecmp(replyDomain, "local.") &&
_cups_strcasecmp(device->domain, replyDomain))
{
/*
* Update the "global" listing to use the .local domain name instead.
*/
_cupsStrFree(device->domain);
device->domain = _cupsStrAlloc(replyDomain);
DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use local "
"domain.", device->dest.name));
update = 1;
}
if (!_cups_strcasecmp(regtype, "_ipps._tcp") &&
_cups_strcasecmp(device->regtype, regtype))
{
/*
* Prefer IPPS over IPP.
*/
_cupsStrFree(device->regtype);
device->regtype = _cupsStrAlloc(regtype);
DEBUG_printf(("6cups_dnssd_get_device: Updating '%s' to use IPPS.",
device->dest.name));
update = 1;
}
if (!update)
{
DEBUG_printf(("6cups_dnssd_get_device: No changes to '%s'.",
device->dest.name));
return (device);
}
}
else
{
/*
* No, add the device...
*/
DEBUG_printf(("6cups_dnssd_get_device: Adding '%s' for %s with domain "
"'%s'.", serviceName,
!strcmp(regtype, "_ipps._tcp") ? "IPPS" : "IPP",
replyDomain));
device = calloc(sizeof(_cups_dnssd_device_t), 1);
device->dest.name = _cupsStrAlloc(name);
device->domain = _cupsStrAlloc(replyDomain);
device->regtype = _cupsStrAlloc(regtype);
device->dest.num_options = cupsAddOption("printer-info", serviceName, 0, &device->dest.options);
cupsArrayAdd(data->devices, device);
}
/*
* Set the "full name" of this service, which is used for queries...
*/
# ifdef HAVE_DNSSD
DNSServiceConstructFullName(fullName, serviceName, regtype, replyDomain);
# else /* HAVE_AVAHI */
avahi_service_name_join(fullName, kDNSServiceMaxDomainName, serviceName, regtype, replyDomain);
# endif /* HAVE_DNSSD */
_cupsStrFree(device->fullName);
device->fullName = _cupsStrAlloc(fullName);
if (device->ref)
{
# ifdef HAVE_DNSSD
DNSServiceRefDeallocate(device->ref);
# else /* HAVE_AVAHI */
avahi_record_browser_free(device->ref);
# endif /* HAVE_DNSSD */
device->ref = 0;
}
if (device->state == _CUPS_DNSSD_ACTIVE)
{
DEBUG_printf(("6cups_dnssd_get_device: Remove callback for \"%s\".", device->dest.name));
(*data->cb)(data->user_data, CUPS_DEST_FLAGS_REMOVED, &device->dest);
device->state = _CUPS_DNSSD_NEW;
}
return (device);
}
# ifdef HAVE_AVAHI
/*
* 'cups_dnssd_poll_cb()' - Wait for input on the specified file descriptors.
*
* Note: This function is needed because avahi_simple_poll_iterate is broken
* and always uses a timeout of 0 (!) milliseconds.
* (https://github.com/lathiat/avahi/issues/127)
*
* @private@
*/
static int /* O - Number of file descriptors matching */
cups_dnssd_poll_cb(
struct pollfd *pollfds, /* I - File descriptors */
unsigned int num_pollfds, /* I - Number of file descriptors */
int timeout, /* I - Timeout in milliseconds (unused) */
void *context) /* I - User data (unused) */
{
_cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
/* Enumeration data */
int val; /* Return value */
DEBUG_printf(("cups_dnssd_poll_cb(pollfds=%p, num_pollfds=%d, timeout=%d, context=%p)", pollfds, num_pollfds, timeout, context));
(void)timeout;
val = poll(pollfds, num_pollfds, _CUPS_DNSSD_MAXTIME);
DEBUG_printf(("cups_dnssd_poll_cb: poll() returned %d", val));
if (val < 0)
{
DEBUG_printf(("cups_dnssd_poll_cb: %s", strerror(errno)));
}
else if (val > 0)
{
data->got_data = 1;
}
return (val);
}
# endif /* HAVE_AVAHI */
/*
* 'cups_dnssd_query_cb()' - Process query data.
*/
static void
cups_dnssd_query_cb(
# ifdef HAVE_DNSSD
DNSServiceRef sdRef, /* I - Service reference */
DNSServiceFlags flags, /* I - Data flags */
uint32_t interfaceIndex, /* I - Interface */
DNSServiceErrorType errorCode, /* I - Error, if any */
const char *fullName, /* I - Full service name */
uint16_t rrtype, /* I - Record type */
uint16_t rrclass, /* I - Record class */
uint16_t rdlen, /* I - Length of record data */
const void *rdata, /* I - Record data */
uint32_t ttl, /* I - Time-to-live */
# else /* HAVE_AVAHI */
AvahiRecordBrowser *browser, /* I - Record browser */
AvahiIfIndex interfaceIndex,
/* I - Interface index (unused) */
AvahiProtocol protocol, /* I - Network protocol (unused) */
AvahiBrowserEvent event, /* I - What happened? */
const char *fullName, /* I - Service name */
uint16_t rrclass, /* I - Record class */
uint16_t rrtype, /* I - Record type */
const void *rdata, /* I - TXT record */
size_t rdlen, /* I - Length of TXT record */
AvahiLookupResultFlags flags, /* I - Flags */
# endif /* HAVE_DNSSD */
void *context) /* I - Enumeration data */
{
# if defined(DEBUG) && defined(HAVE_AVAHI)
AvahiClient *client = avahi_record_browser_get_client(browser);
/* Client information */
# endif /* DEBUG && HAVE_AVAHI */
_cups_dnssd_data_t *data = (_cups_dnssd_data_t *)context;
/* Enumeration data */
char serviceName[256],/* Service name */
name[128], /* Queue name */
*ptr; /* Pointer into string */
_cups_dnssd_device_t dkey, /* Search key */
*device; /* Device */
# ifdef HAVE_DNSSD
DEBUG_printf(("5cups_dnssd_query_cb(sdRef=%p, flags=%x, interfaceIndex=%d, errorCode=%d, fullName=\"%s\", rrtype=%u, rrclass=%u, rdlen=%u, rdata=%p, ttl=%u, context=%p)", (void *)sdRef, flags, interfaceIndex, errorCode, fullName, rrtype, rrclass, rdlen, rdata, ttl, context));
/*
* Only process "add" data...
*/
if (errorCode != kDNSServiceErr_NoError || !(flags & kDNSServiceFlagsAdd))
return;
# else /* HAVE_AVAHI */
DEBUG_printf(("cups_dnssd_query_cb(browser=%p, interfaceIndex=%d, protocol=%d, event=%d, fullName=\"%s\", rrclass=%u, rrtype=%u, rdata=%p, rdlen=%u, flags=%x, context=%p)", browser, interfaceIndex, protocol, event, fullName, rrclass, rrtype, rdata, (unsigned)rdlen, flags, context));
/*
* Only process "add" data...
*/
if (event != AVAHI_BROWSER_NEW)
{
if (event == AVAHI_BROWSER_FAILURE)
DEBUG_printf(("cups_dnssd_query_cb: %s", avahi_strerror(avahi_client_errno(client))));
return;
}
# endif /* HAVE_DNSSD */
/*
* Lookup the service in the devices array.
*/
cups_dnssd_unquote(serviceName, fullName, sizeof(serviceName));
if ((ptr = strstr(serviceName, "._")) != NULL)
*ptr = '\0';
cups_queue_name(name, serviceName, sizeof(name));
dkey.dest.name = name;
if ((device = cupsArrayFind(data->devices, &dkey)) != NULL && device->state == _CUPS_DNSSD_NEW)
{
/*
* Found it, pull out the make and model from the TXT record and save it...
*/
const uint8_t *txt, /* Pointer into data */
*txtnext, /* Next key/value pair */
*txtend; /* End of entire TXT record */
uint8_t txtlen; /* Length of current key/value pair */
char key[256], /* Key string */
value[256], /* Value string */
make_and_model[512],
/* Manufacturer and model */
model[256], /* Model */
uriname[1024], /* Name for URI */
uri[1024]; /* Printer URI */
cups_ptype_t type = CUPS_PRINTER_DISCOVERED | CUPS_PRINTER_BW;
/* Printer type */
int saw_printer_type = 0;
/* Did we see a printer-type key? */
device->state = _CUPS_DNSSD_PENDING;
make_and_model[0] = '\0';
strlcpy(model, "Unknown", sizeof(model));
for (txt = rdata, txtend = txt + rdlen;
txt < txtend;
txt = txtnext)
{
/*
* Read a key/value pair starting with an 8-bit length. Since the
* length is 8 bits and the size of the key/value buffers is 256, we
* don't need to check for overflow...
*/
txtlen = *txt++;
if (!txtlen || (txt + txtlen) > txtend)
break;
txtnext = txt + txtlen;
for (ptr = key; txt < txtnext && *txt != '='; txt ++)
*ptr++ = (char)*txt;
*ptr = '\0';
if (txt < txtnext && *txt == '=')
{
txt ++;
if (txt < txtnext)
memcpy(value, txt, (size_t)(txtnext - txt));
value[txtnext - txt] = '\0';
DEBUG_printf(("6cups_dnssd_query_cb: %s=%s", key, value));
}
else
{
DEBUG_printf(("6cups_dnssd_query_cb: '%s' with no value.", key));
continue;
}
if (!_cups_strcasecmp(key, "usb_MFG") ||
!_cups_strcasecmp(key, "usb_MANU") ||
!_cups_strcasecmp(key, "usb_MANUFACTURER"))
strlcpy(make_and_model, value, sizeof(make_and_model));
else if (!_cups_strcasecmp(key, "usb_MDL") ||
!_cups_strcasecmp(key, "usb_MODEL"))
strlcpy(model, value, sizeof(model));
else if (!_cups_strcasecmp(key, "product") && !strstr(value, "Ghostscript"))
{
if (value[0] == '(')
{
/*
* Strip parenthesis...
*/
if ((ptr = value + strlen(value) - 1) > value && *ptr == ')')
*ptr = '\0';
strlcpy(model, value + 1, sizeof(model));
}
else
strlcpy(model, value, sizeof(model));
}
else if (!_cups_strcasecmp(key, "ty"))
{
strlcpy(model, value, sizeof(model));
if ((ptr = strchr(model, ',')) != NULL)
*ptr = '\0';
}
else if (!_cups_strcasecmp(key, "note"))
device->dest.num_options = cupsAddOption("printer-location", value,
device->dest.num_options,
&device->dest.options);
else if (!_cups_strcasecmp(key, "pdl"))
{
/*
* Look for PDF-capable printers; only PDF-capable printers are shown.
*/
const char *start, *next; /* Pointer into value */
int have_pdf = 0, /* Have PDF? */
have_raster = 0;/* Have raster format support? */
for (start = value; start && *start; start = next)
{
if (!_cups_strncasecmp(start, "application/pdf", 15) && (!start[15] || start[15] == ','))
{
have_pdf = 1;
break;
}
else if ((!_cups_strncasecmp(start, "image/pwg-raster", 16) && (!start[16] || start[16] == ',')) ||
(!_cups_strncasecmp(start, "image/urf", 9) && (!start[9] || start[9] == ',')))
{
have_raster = 1;
break;
}
if ((next = strchr(start, ',')) != NULL)
next ++;
}
if (!have_pdf && !have_raster)
device->state = _CUPS_DNSSD_INCOMPATIBLE;
}
else if (!_cups_strcasecmp(key, "printer-type"))
{
/*
* Value is either NNNN or 0xXXXX
*/
saw_printer_type = 1;
type = (cups_ptype_t)strtol(value, NULL, 0) | CUPS_PRINTER_DISCOVERED;
}
else if (!saw_printer_type)
{
if (!_cups_strcasecmp(key, "air") &&
!_cups_strcasecmp(value, "t"))
type |= CUPS_PRINTER_AUTHENTICATED;
else if (!_cups_strcasecmp(key, "bind") &&
!_cups_strcasecmp(value, "t"))
type |= CUPS_PRINTER_BIND;
else if (!_cups_strcasecmp(key, "collate") &&
!_cups_strcasecmp(value, "t"))
type |= CUPS_PRINTER_COLLATE;
else if (!_cups_strcasecmp(key, "color") &&
!_cups_strcasecmp(value, "t"))
type |= CUPS_PRINTER_COLOR;
else if (!_cups_strcasecmp(key, "copies") &&
!_cups_strcasecmp(value, "t"))
type |= CUPS_PRINTER_COPIES;
else if (!_cups_strcasecmp(key, "duplex") &&
!_cups_strcasecmp(value, "t"))
type |= CUPS_PRINTER_DUPLEX;
else if (!_cups_strcasecmp(key, "fax") &&
!_cups_strcasecmp(value, "t"))
type |= CUPS_PRINTER_MFP;
else if (!_cups_strcasecmp(key, "papercustom") &&
!_cups_strcasecmp(value, "t"))
type |= CUPS_PRINTER_VARIABLE;
else if (!_cups_strcasecmp(key, "papermax"))
{
if (!_cups_strcasecmp(value, "legal-a4"))
type |= CUPS_PRINTER_SMALL;
else if (!_cups_strcasecmp(value, "isoc-a2"))
type |= CUPS_PRINTER_MEDIUM;
else if (!_cups_strcasecmp(value, ">isoc-a2"))
type |= CUPS_PRINTER_LARGE;
}
else if (!_cups_strcasecmp(key, "punch") &&
!_cups_strcasecmp(value, "t"))
type |= CUPS_PRINTER_PUNCH;
else if (!_cups_strcasecmp(key, "scan") &&
!_cups_strcasecmp(value, "t"))
type |= CUPS_PRINTER_MFP;
else if (!_cups_strcasecmp(key, "sort") &&
!_cups_strcasecmp(value, "t"))
type |= CUPS_PRINTER_SORT;
else if (!_cups_strcasecmp(key, "staple") &&
!_cups_strcasecmp(value, "t"))
type |= CUPS_PRINTER_STAPLE;
}
}
/*
* Save the printer-xxx values...
*/
if (make_and_model[0])
{
strlcat(make_and_model, " ", sizeof(make_and_model));
strlcat(make_and_model, model, sizeof(make_and_model));
device->dest.num_options = cupsAddOption("printer-make-and-model", make_and_model, device->dest.num_options, &device->dest.options);
}
else
device->dest.num_options = cupsAddOption("printer-make-and-model", model, device->dest.num_options, &device->dest.options);
device->type = type;
snprintf(value, sizeof(value), "%u", type);
device->dest.num_options = cupsAddOption("printer-type", value, device->dest.num_options, &device->dest.options);
/*
* Save the URI...
*/
cups_dnssd_unquote(uriname, device->fullName, sizeof(uriname));
httpAssembleURI(HTTP_URI_CODING_ALL, uri, sizeof(uri),
!strcmp(device->regtype, "_ipps._tcp") ? "ipps" : "ipp",
NULL, uriname, 0, saw_printer_type ? "/cups" : "/");
DEBUG_printf(("6cups_dnssd_query: device-uri=\"%s\"", uri));
device->dest.num_options = cupsAddOption("device-uri", uri, device->dest.num_options, &device->dest.options);
}
else
DEBUG_printf(("6cups_dnssd_query: Ignoring TXT record for '%s'.",
fullName));
}
/*
* 'cups_dnssd_resolve()' - Resolve a Bonjour printer URI.
*/
static const char * /* O - Resolved URI or NULL */
cups_dnssd_resolve(
cups_dest_t *dest, /* I - Destination */
const char *uri, /* I - Current printer URI */
int msec, /* I - Time in milliseconds */
int *cancel, /* I - Pointer to "cancel" variable */
cups_dest_cb_t cb, /* I - Callback */
void *user_data) /* I - User data for callback */
{
char tempuri[1024]; /* Temporary URI buffer */
_cups_dnssd_resolve_t resolve; /* Resolve data */
/*
* Resolve the URI...
*/
resolve.cancel = cancel;
gettimeofday(&resolve.end_time, NULL);
if (msec > 0)
{
resolve.end_time.tv_sec += msec / 1000;
resolve.end_time.tv_usec += (msec % 1000) * 1000;
while (resolve.end_time.tv_usec >= 1000000)
{
resolve.end_time.tv_sec ++;
resolve.end_time.tv_usec -= 1000000;
}
}
else
resolve.end_time.tv_sec += 75;
if (cb)
(*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_RESOLVING, dest);
if ((uri = _httpResolveURI(uri, tempuri, sizeof(tempuri), _HTTP_RESOLVE_DEFAULT, cups_dnssd_resolve_cb, &resolve)) == NULL)
{
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unable to resolve printer-uri."), 1);
if (cb)
(*cb)(user_data, CUPS_DEST_FLAGS_UNCONNECTED | CUPS_DEST_FLAGS_ERROR, dest);
return (NULL);
}
/*
* Save the resolved URI...
*/
dest->num_options = cupsAddOption("device-uri", uri, dest->num_options, &dest->options);
return (cupsGetOption("device-uri", dest->num_options, dest->options));
}
/*
* 'cups_dnssd_resolve_cb()' - See if we should continue resolving.
*/
static int /* O - 1 to continue, 0 to stop */
cups_dnssd_resolve_cb(void *context) /* I - Resolve data */
{
_cups_dnssd_resolve_t *resolve = (_cups_dnssd_resolve_t *)context;
/* Resolve data */
struct timeval curtime; /* Current time */
/*
* If the cancel variable is set, return immediately.
*/
if (resolve->cancel && *(resolve->cancel))
{
DEBUG_puts("4cups_dnssd_resolve_cb: Canceled.");
return (0);
}
/*
* Otherwise check the end time...
*/
gettimeofday(&curtime, NULL);
DEBUG_printf(("4cups_dnssd_resolve_cb: curtime=%d.%06d, end_time=%d.%06d", (int)curtime.tv_sec, (int)curtime.tv_usec, (int)resolve->end_time.tv_sec, (int)resolve->end_time.tv_usec));
return (curtime.tv_sec < resolve->end_time.tv_sec ||
(curtime.tv_sec == resolve->end_time.tv_sec &&
curtime.tv_usec < resolve->end_time.tv_usec));
}
/*
* 'cups_dnssd_unquote()' - Unquote a name string.
*/
static void
cups_dnssd_unquote(char *dst, /* I - Destination buffer */
const char *src, /* I - Source string */
size_t dstsize) /* I - Size of destination buffer */
{
char *dstend = dst + dstsize - 1; /* End of destination buffer */
while (*src && dst < dstend)
{
if (*src == '\\')
{
src ++;
if (isdigit(src[0] & 255) && isdigit(src[1] & 255) &&
isdigit(src[2] & 255))
{
*dst++ = ((((src[0] - '0') * 10) + src[1] - '0') * 10) + src[2] - '0';
src += 3;
}
else
*dst++ = *src++;
}
else
*dst++ = *src ++;
}
*dst = '\0';
}
#endif /* HAVE_DNSSD */
#if defined(HAVE_AVAHI) || defined(HAVE_DNSSD)
/*
* 'cups_elapsed()' - Return the elapsed time in milliseconds.
*/
static int /* O - Elapsed time in milliseconds */
cups_elapsed(struct timeval *t) /* IO - Previous time */
{
int msecs; /* Milliseconds */
struct timeval nt; /* New time */
gettimeofday(&nt, NULL);
msecs = (int)(1000 * (nt.tv_sec - t->tv_sec) + (nt.tv_usec - t->tv_usec) / 1000);
*t = nt;
return (msecs);
}
#endif /* HAVE_AVAHI || HAVE_DNSSD */
/*
* 'cups_enum_dests()' - Enumerate destinations from a specific server.
*/
static int /* O - 1 on success, 0 on failure */
cups_enum_dests(
http_t *http, /* I - Connection to scheduler */
unsigned flags, /* I - Enumeration flags */
int msec, /* I - Timeout in milliseconds, -1 for indefinite */
int *cancel, /* I - Pointer to "cancel" variable */
cups_ptype_t type, /* I - Printer type bits */
cups_ptype_t mask, /* I - Mask for printer type bits */
cups_dest_cb_t cb, /* I - Callback function */
void *user_data) /* I - User data */
{
int i, j, /* Looping vars */
num_dests; /* Number of destinations */
cups_dest_t *dests = NULL, /* Destinations */
*dest; /* Current destination */
cups_option_t *option; /* Current option */
const char *user_default; /* Default printer from environment */
#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
int count, /* Number of queries started */
completed, /* Number of completed queries */
remaining; /* Remainder of timeout */
struct timeval curtime; /* Current time */
_cups_dnssd_data_t data; /* Data for callback */
_cups_dnssd_device_t *device; /* Current device */
# ifdef HAVE_DNSSD
int nfds, /* Number of files responded */
main_fd; /* File descriptor for lookups */
DNSServiceRef ipp_ref = NULL; /* IPP browser */
# ifdef HAVE_SSL
DNSServiceRef ipps_ref = NULL; /* IPPS browser */
# endif /* HAVE_SSL */
# ifdef HAVE_POLL
struct pollfd pfd; /* Polling data */
# else
fd_set input; /* Input set for select() */
struct timeval timeout; /* Timeout for select() */
# endif /* HAVE_POLL */
# else /* HAVE_AVAHI */
int error; /* Error value */
AvahiServiceBrowser *ipp_ref = NULL; /* IPP browser */
# ifdef HAVE_SSL
AvahiServiceBrowser *ipps_ref = NULL; /* IPPS browser */
# endif /* HAVE_SSL */
# endif /* HAVE_DNSSD */
#else
_cups_getdata_t data; /* Data for callback */
#endif /* HAVE_DNSSD || HAVE_AVAHI */
char filename[1024]; /* Local lpoptions file */
_cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
DEBUG_printf(("cups_enum_dests(flags=%x, msec=%d, cancel=%p, type=%x, mask=%x, cb=%p, user_data=%p)", flags, msec, (void *)cancel, type, mask, (void *)cb, (void *)user_data));
/*
* Range check input...
*/
(void)flags;
if (!cb)
{
DEBUG_puts("1cups_enum_dests: No callback, returning 0.");
return (0);
}
/*
* Load the /etc/cups/lpoptions and ~/.cups/lpoptions files...
*/
memset(&data, 0, sizeof(data));
user_default = _cupsUserDefault(data.def_name, sizeof(data.def_name));
snprintf(filename, sizeof(filename), "%s/lpoptions", cg->cups_serverroot);
data.num_dests = cups_get_dests(filename, NULL, NULL, 1, user_default != NULL, data.num_dests, &data.dests);
if (cg->home)
{
snprintf(filename, sizeof(filename), "%s/.cups/lpoptions", cg->home);
data.num_dests = cups_get_dests(filename, NULL, NULL, 1, user_default != NULL, data.num_dests, &data.dests);
}
if (!user_default && (dest = cupsGetDest(NULL, NULL, data.num_dests, data.dests)) != NULL)
{
/*
* Use an lpoptions default printer...
*/
if (dest->instance)
snprintf(data.def_name, sizeof(data.def_name), "%s/%s", dest->name, dest->instance);
else
strlcpy(data.def_name, dest->name, sizeof(data.def_name));
}
else
{
const char *default_printer; /* Server default printer */
if ((default_printer = cupsGetDefault2(http)) != NULL)
strlcpy(data.def_name, default_printer, sizeof(data.def_name));
}
if (data.def_name[0])
{
/*
* Separate printer and instance name...
*/
if ((data.def_instance = strchr(data.def_name, '/')) != NULL)
*data.def_instance++ = '\0';
}
DEBUG_printf(("1cups_enum_dests: def_name=\"%s\", def_instance=\"%s\"", data.def_name, data.def_instance));
/*
* Get ready to enumerate...
*/
#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
data.type = type;
data.mask = mask;
data.cb = cb;
data.user_data = user_data;
data.devices = cupsArrayNew3((cups_array_func_t)cups_dnssd_compare_devices, NULL, NULL, 0, NULL, (cups_afree_func_t)cups_dnssd_free_device);
#endif /* HAVE_DNSSD || HAVE_AVAHI */
if (!(mask & CUPS_PRINTER_DISCOVERED) || !(type & CUPS_PRINTER_DISCOVERED))
{
/*
* Get the list of local printers and pass them to the callback function...
*/
num_dests = _cupsGetDests(http, IPP_OP_CUPS_GET_PRINTERS, NULL, &dests, type, mask);
if (data.def_name[0])
{
/*
* Lookup the named default printer and instance and make it the default...
*/
if ((dest = cupsGetDest(data.def_name, data.def_instance, num_dests, dests)) != NULL)
{
DEBUG_printf(("1cups_enum_dests: Setting is_default on \"%s/%s\".", dest->name, dest->instance));
dest->is_default = 1;
}
}
for (i = num_dests, dest = dests;
i > 0 && (!cancel || !*cancel);
i --, dest ++)
{
cups_dest_t *user_dest; /* Destination from lpoptions */
#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
const char *device_uri; /* Device URI */
#endif /* HAVE_DNSSD || HAVE_AVAHI */
if ((user_dest = cupsGetDest(dest->name, dest->instance, data.num_dests, data.dests)) != NULL)
{
/*
* Apply user defaults to this destination...
*/
for (j = user_dest->num_options, option = user_dest->options; j > 0; j --, option ++)
dest->num_options = cupsAddOption(option->name, option->value, dest->num_options, &dest->options);
}
if (!(*cb)(user_data, i > 1 ? CUPS_DEST_FLAGS_MORE : CUPS_DEST_FLAGS_NONE, dest))
break;
#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
if (!dest->instance && (device_uri = cupsGetOption("device-uri", dest->num_options, dest->options)) != NULL && !strncmp(device_uri, "dnssd://", 8))
{
/*
* Add existing queue using service name, etc. so we don't list it again...
*/
char scheme[32], /* URI scheme */
userpass[32], /* Username:password */
serviceName[256], /* Service name (host field) */
resource[256], /* Resource (options) */
*regtype, /* Registration type */
*replyDomain; /* Registration domain */
int port; /* Port number (not used) */
if (httpSeparateURI(HTTP_URI_CODING_ALL, device_uri, scheme, sizeof(scheme), userpass, sizeof(userpass), serviceName, sizeof(serviceName), &port, resource, sizeof(resource)) >= HTTP_URI_STATUS_OK)
{
if ((regtype = strstr(serviceName, "._ipp")) != NULL)
{
*regtype++ = '\0';
if ((replyDomain = strstr(regtype, "._tcp.")) != NULL)
{
replyDomain[5] = '\0';
replyDomain += 6;
if ((device = cups_dnssd_get_device(&data, serviceName, regtype, replyDomain)) != NULL)
device->state = _CUPS_DNSSD_ACTIVE;
}
}
}
}
#endif /* HAVE_DNSSD || HAVE_AVAHI */
}
cupsFreeDests(num_dests, dests);
if (i > 0 || msec == 0)
goto enum_finished;
}
/*
* Return early if the caller doesn't want to do discovery...
*/
if ((mask & CUPS_PRINTER_DISCOVERED) && !(type & CUPS_PRINTER_DISCOVERED))
goto enum_finished;
#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
/*
* Get Bonjour-shared printers...
*/
gettimeofday(&curtime, NULL);
# ifdef HAVE_DNSSD
if (DNSServiceCreateConnection(&data.main_ref) != kDNSServiceErr_NoError)
{
DEBUG_puts("1cups_enum_dests: Unable to create service browser, returning 0.");
cupsFreeDests(data.num_dests, data.dests);
return (0);
}
main_fd = DNSServiceRefSockFD(data.main_ref);
ipp_ref = data.main_ref;
if (DNSServiceBrowse(&ipp_ref, kDNSServiceFlagsShareConnection, 0, "_ipp._tcp", NULL, (DNSServiceBrowseReply)cups_dnssd_browse_cb, &data) != kDNSServiceErr_NoError)
{
DEBUG_puts("1cups_enum_dests: Unable to create IPP browser, returning 0.");
DNSServiceRefDeallocate(data.main_ref);
cupsFreeDests(data.num_dests, data.dests);
return (0);
}
# ifdef HAVE_SSL
ipps_ref = data.main_ref;
if (DNSServiceBrowse(&ipps_ref, kDNSServiceFlagsShareConnection, 0, "_ipps._tcp", NULL, (DNSServiceBrowseReply)cups_dnssd_browse_cb, &data) != kDNSServiceErr_NoError)
{
DEBUG_puts("1cups_enum_dests: Unable to create IPPS browser, returning 0.");
DNSServiceRefDeallocate(data.main_ref);
cupsFreeDests(data.num_dests, data.dests);
return (0);
}
# endif /* HAVE_SSL */
# else /* HAVE_AVAHI */
if ((data.simple_poll = avahi_simple_poll_new()) == NULL)
{
DEBUG_puts("1cups_enum_dests: Unable to create Avahi poll, returning 0.");
cupsFreeDests(data.num_dests, data.dests);
return (0);
}
avahi_simple_poll_set_func(data.simple_poll, cups_dnssd_poll_cb, &data);
data.client = avahi_client_new(avahi_simple_poll_get(data.simple_poll),
0, cups_dnssd_client_cb, &data,
&error);
if (!data.client)
{
DEBUG_puts("1cups_enum_dests: Unable to create Avahi client, returning 0.");
avahi_simple_poll_free(data.simple_poll);
cupsFreeDests(data.num_dests, data.dests);
return (0);
}
data.browsers = 1;
if ((ipp_ref = avahi_service_browser_new(data.client, AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, "_ipp._tcp", NULL, 0, cups_dnssd_browse_cb, &data)) == NULL)
{
DEBUG_puts("1cups_enum_dests: Unable to create Avahi IPP browser, returning 0.");
avahi_client_free(data.client);
avahi_simple_poll_free(data.simple_poll);
cupsFreeDests(data.num_dests, data.dests);
return (0);
}
# ifdef HAVE_SSL
data.browsers ++;
if ((ipps_ref = avahi_service_browser_new(data.client, AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, "_ipps._tcp", NULL, 0, cups_dnssd_browse_cb, &data)) == NULL)
{
DEBUG_puts("1cups_enum_dests: Unable to create Avahi IPPS browser, returning 0.");
avahi_service_browser_free(ipp_ref);
avahi_client_free(data.client);
avahi_simple_poll_free(data.simple_poll);
cupsFreeDests(data.num_dests, data.dests);
return (0);
}
# endif /* HAVE_SSL */
# endif /* HAVE_DNSSD */
if (msec < 0)
remaining = INT_MAX;
else
remaining = msec;
while (remaining > 0 && (!cancel || !*cancel))
{
/*
* Check for input...
*/
DEBUG_printf(("1cups_enum_dests: remaining=%d", remaining));
cups_elapsed(&curtime);
# ifdef HAVE_DNSSD
# ifdef HAVE_POLL
pfd.fd = main_fd;
pfd.events = POLLIN;
nfds = poll(&pfd, 1, remaining > _CUPS_DNSSD_MAXTIME ? _CUPS_DNSSD_MAXTIME : remaining);
# else
FD_ZERO(&input);
FD_SET(main_fd, &input);
timeout.tv_sec = 0;
timeout.tv_usec = 1000 * (remaining > _CUPS_DNSSD_MAXTIME ? _CUPS_DNSSD_MAXTIME : remaining);
nfds = select(main_fd + 1, &input, NULL, NULL, &timeout);
# endif /* HAVE_POLL */
if (nfds > 0)
DNSServiceProcessResult(data.main_ref);
else if (nfds < 0 && errno != EINTR && errno != EAGAIN)
break;
# else /* HAVE_AVAHI */
data.got_data = 0;
if ((error = avahi_simple_poll_iterate(data.simple_poll, _CUPS_DNSSD_MAXTIME)) > 0)
{
/*
* We've been told to exit the loop. Perhaps the connection to
* Avahi failed.
*/
break;
}
DEBUG_printf(("1cups_enum_dests: got_data=%d", data.got_data));
# endif /* HAVE_DNSSD */
remaining -= cups_elapsed(&curtime);
for (device = (_cups_dnssd_device_t *)cupsArrayFirst(data.devices),
count = 0, completed = 0;
device;
device = (_cups_dnssd_device_t *)cupsArrayNext(data.devices))
{
if (device->ref)
count ++;
if (device->state == _CUPS_DNSSD_ACTIVE)
completed ++;
if (!device->ref && device->state == _CUPS_DNSSD_NEW)
{
DEBUG_printf(("1cups_enum_dests: Querying '%s'.", device->fullName));
# ifdef HAVE_DNSSD
device->ref = data.main_ref;
if (DNSServiceQueryRecord(&(device->ref), kDNSServiceFlagsShareConnection, 0, device->fullName, kDNSServiceType_TXT, kDNSServiceClass_IN, (DNSServiceQueryRecordReply)cups_dnssd_query_cb, &data) == kDNSServiceErr_NoError)
{
count ++;
}
else
{
device->ref = 0;
device->state = _CUPS_DNSSD_ERROR;
DEBUG_puts("1cups_enum_dests: Query failed.");
}
# else /* HAVE_AVAHI */
if ((device->ref = avahi_record_browser_new(data.client, AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, device->fullName, AVAHI_DNS_CLASS_IN, AVAHI_DNS_TYPE_TXT, 0, cups_dnssd_query_cb, &data)) != NULL)
{
DEBUG_printf(("1cups_enum_dests: Query ref=%p", device->ref));
count ++;
}
else
{
device->state = _CUPS_DNSSD_ERROR;
DEBUG_printf(("1cups_enum_dests: Query failed: %s", avahi_strerror(avahi_client_errno(data.client))));
}
# endif /* HAVE_DNSSD */
}
else if (device->ref && device->state == _CUPS_DNSSD_PENDING)
{
completed ++;
DEBUG_printf(("1cups_enum_dests: Query for \"%s\" is complete.", device->fullName));
if ((device->type & mask) == type)
{
cups_dest_t *user_dest; /* Destination from lpoptions */
dest = &device->dest;
if ((user_dest = cupsGetDest(dest->name, dest->instance, data.num_dests, data.dests)) != NULL)
{
/*
* Apply user defaults to this destination...
*/
for (j = user_dest->num_options, option = user_dest->options; j > 0; j --, option ++)
dest->num_options = cupsAddOption(option->name, option->value, dest->num_options, &dest->options);
}
if (!strcasecmp(dest->name, data.def_name) && !data.def_instance)
{
DEBUG_printf(("1cups_enum_dests: Setting is_default on discovered \"%s\".", dest->name));
dest->is_default = 1;
}
DEBUG_printf(("1cups_enum_dests: Add callback for \"%s\".", device->dest.name));
if (!(*cb)(user_data, CUPS_DEST_FLAGS_NONE, dest))
{
remaining = -1;
break;
}
}
device->state = _CUPS_DNSSD_ACTIVE;
}
}
# ifdef HAVE_AVAHI
DEBUG_printf(("1cups_enum_dests: remaining=%d, browsers=%d, completed=%d, count=%d, devices count=%d", remaining, data.browsers, completed, count, cupsArrayCount(data.devices)));
if (data.browsers == 0 && completed == cupsArrayCount(data.devices))
break;
# else
DEBUG_printf(("1cups_enum_dests: remaining=%d, completed=%d, count=%d, devices count=%d", remaining, completed, count, cupsArrayCount(data.devices)));
if (completed == cupsArrayCount(data.devices))
break;
# endif /* HAVE_AVAHI */
}
#endif /* HAVE_DNSSD || HAVE_AVAHI */
/*
* Return...
*/
enum_finished:
cupsFreeDests(data.num_dests, data.dests);
#if defined(HAVE_DNSSD) || defined(HAVE_AVAHI)
cupsArrayDelete(data.devices);
# ifdef HAVE_DNSSD
if (ipp_ref)
DNSServiceRefDeallocate(ipp_ref);
# ifdef HAVE_SSL
if (ipps_ref)
DNSServiceRefDeallocate(ipps_ref);
# endif /* HAVE_SSL */
if (data.main_ref)
DNSServiceRefDeallocate(data.main_ref);
# else /* HAVE_AVAHI */
if (ipp_ref)
avahi_service_browser_free(ipp_ref);
# ifdef HAVE_SSL
if (ipps_ref)
avahi_service_browser_free(ipps_ref);
# endif /* HAVE_SSL */
if (data.client)
avahi_client_free(data.client);
if (data.simple_poll)
avahi_simple_poll_free(data.simple_poll);
# endif /* HAVE_DNSSD */
#endif /* HAVE_DNSSD || HAVE_AVAHI */
DEBUG_puts("1cups_enum_dests: Returning 1.");
return (1);
}
/*
* 'cups_find_dest()' - Find a destination using a binary search.
*/
static int /* O - Index of match */
cups_find_dest(const char *name, /* I - Destination name */
const char *instance, /* I - Instance or NULL */
int num_dests, /* I - Number of destinations */
cups_dest_t *dests, /* I - Destinations */
int prev, /* I - Previous index */
int *rdiff) /* O - Difference of match */
{
int left, /* Low mark for binary search */
right, /* High mark for binary search */
current, /* Current index */
diff; /* Result of comparison */
cups_dest_t key; /* Search key */
key.name = (char *)name;
key.instance = (char *)instance;
if (prev >= 0)
{
/*
* Start search on either side of previous...
*/
if ((diff = cups_compare_dests(&key, dests + prev)) == 0 ||
(diff < 0 && prev == 0) ||
(diff > 0 && prev == (num_dests - 1)))
{
*rdiff = diff;
return (prev);
}
else if (diff < 0)
{
/*
* Start with previous on right side...
*/
left = 0;
right = prev;
}
else
{
/*
* Start wih previous on left side...
*/
left = prev;
right = num_dests - 1;
}
}
else
{
/*
* Start search in the middle...
*/
left = 0;
right = num_dests - 1;
}
do
{
current = (left + right) / 2;
diff = cups_compare_dests(&key, dests + current);
if (diff == 0)
break;
else if (diff < 0)
right = current;
else
left = current;
}
while ((right - left) > 1);
if (diff != 0)
{
/*
* Check the last 1 or 2 elements...
*/
if ((diff = cups_compare_dests(&key, dests + left)) <= 0)
current = left;
else
{
diff = cups_compare_dests(&key, dests + right);
current = right;
}
}
/*
* Return the closest destination and the difference...
*/
*rdiff = diff;
return (current);
}
/*
* 'cups_get_cb()' - Collect enumerated destinations.
*/
static int /* O - 1 to continue, 0 to stop */
cups_get_cb(_cups_getdata_t *data, /* I - Data from cupsGetDests */
unsigned flags, /* I - Enumeration flags */
cups_dest_t *dest) /* I - Destination */
{
if (flags & CUPS_DEST_FLAGS_REMOVED)
{
/*
* Remove destination from array...
*/
data->num_dests = cupsRemoveDest(dest->name, dest->instance, data->num_dests, &data->dests);
}
else
{
/*
* Add destination to array...
*/
data->num_dests = cupsCopyDest(dest, data->num_dests, &data->dests);
}
return (1);
}
/*
* 'cups_get_default()' - Get the default destination from an lpoptions file.
*/
static char * /* O - Default destination or NULL */
cups_get_default(const char *filename, /* I - File to read */
char *namebuf, /* I - Name buffer */
size_t namesize, /* I - Size of name buffer */
const char **instance) /* I - Instance */
{
cups_file_t *fp; /* lpoptions file */
char line[8192], /* Line from file */
*value, /* Value for line */
*nameptr; /* Pointer into name */
int linenum; /* Current line */
*namebuf = '\0';
if ((fp = cupsFileOpen(filename, "r")) != NULL)
{
linenum = 0;
while (cupsFileGetConf(fp, line, sizeof(line), &value, &linenum))
{
if (!_cups_strcasecmp(line, "default") && value)
{
strlcpy(namebuf, value, namesize);
if ((nameptr = strchr(namebuf, ' ')) != NULL)
*nameptr = '\0';
if ((nameptr = strchr(namebuf, '\t')) != NULL)
*nameptr = '\0';
if ((nameptr = strchr(namebuf, '/')) != NULL)
*nameptr++ = '\0';
*instance = nameptr;
break;
}
}
cupsFileClose(fp);
}
return (*namebuf ? namebuf : NULL);
}
/*
* 'cups_get_dests()' - Get destinations from a file.
*/
static int /* O - Number of destinations */
cups_get_dests(
const char *filename, /* I - File to read from */
const char *match_name, /* I - Destination name we want */
const char *match_inst, /* I - Instance name we want */
int load_all, /* I - Load all saved destinations? */
int user_default_set, /* I - User default printer set? */
int num_dests, /* I - Number of destinations */
cups_dest_t **dests) /* IO - Destinations */
{
int i; /* Looping var */
cups_dest_t *dest; /* Current destination */
cups_file_t *fp; /* File pointer */
char line[8192], /* Line from file */
*lineptr, /* Pointer into line */
*name, /* Name of destination/option */
*instance; /* Instance of destination */
int linenum; /* Current line number */
DEBUG_printf(("7cups_get_dests(filename=\"%s\", match_name=\"%s\", match_inst=\"%s\", load_all=%d, user_default_set=%d, num_dests=%d, dests=%p)", filename, match_name, match_inst, load_all, user_default_set, num_dests, (void *)dests));
/*
* Try to open the file...
*/
if ((fp = cupsFileOpen(filename, "r")) == NULL)
return (num_dests);
/*
* Read each printer; each line looks like:
*
* Dest name[/instance] options
* Default name[/instance] options
*/
linenum = 0;
while (cupsFileGetConf(fp, line, sizeof(line), &lineptr, &linenum))
{
/*
* See what type of line it is...
*/
DEBUG_printf(("9cups_get_dests: linenum=%d line=\"%s\" lineptr=\"%s\"",
linenum, line, lineptr));
if ((_cups_strcasecmp(line, "dest") && _cups_strcasecmp(line, "default")) || !lineptr)
{
DEBUG_puts("9cups_get_dests: Not a dest or default line...");
continue;
}
name = lineptr;
/*
* Search for an instance...
*/
while (!isspace(*lineptr & 255) && *lineptr && *lineptr != '/')
lineptr ++;
if (*lineptr == '/')
{
/*
* Found an instance...
*/
*lineptr++ = '\0';
instance = lineptr;
/*
* Search for an instance...
*/
while (!isspace(*lineptr & 255) && *lineptr)
lineptr ++;
}
else
instance = NULL;
if (*lineptr)
*lineptr++ = '\0';
DEBUG_printf(("9cups_get_dests: name=\"%s\", instance=\"%s\"", name,
instance));
/*
* Match and/or ignore missing destinations...
*/
if (match_name)
{
if (_cups_strcasecmp(name, match_name) ||
(!instance && match_inst) ||
(instance && !match_inst) ||
(instance && _cups_strcasecmp(instance, match_inst)))
continue;
dest = *dests;
}
else if (!load_all && cupsGetDest(name, NULL, num_dests, *dests) == NULL)
{
DEBUG_puts("9cups_get_dests: Not found!");
continue;
}
else
{
/*
* Add the destination...
*/
num_dests = cupsAddDest(name, instance, num_dests, dests);
if ((dest = cupsGetDest(name, instance, num_dests, *dests)) == NULL)
{
/*
* Out of memory!
*/
DEBUG_puts("9cups_get_dests: Out of memory!");
break;
}
}
/*
* Add options until we hit the end of the line...
*/
dest->num_options = cupsParseOptions(lineptr, dest->num_options, &(dest->options));
/*
* If we found what we were looking for, stop now...
*/
if (match_name)
break;
/*
* Set this as default if needed...
*/
if (!user_default_set && !_cups_strcasecmp(line, "default"))
{
DEBUG_puts("9cups_get_dests: Setting as default...");
for (i = 0; i < num_dests; i ++)
(*dests)[i].is_default = 0;
dest->is_default = 1;
}
}
/*
* Close the file and return...
*/
cupsFileClose(fp);
return (num_dests);
}
/*
* 'cups_make_string()' - Make a comma-separated string of values from an IPP
* attribute.
*/
static char * /* O - New string */
cups_make_string(
ipp_attribute_t *attr, /* I - Attribute to convert */
char *buffer, /* I - Buffer */
size_t bufsize) /* I - Size of buffer */
{
int i; /* Looping var */
char *ptr, /* Pointer into buffer */
*end, /* Pointer to end of buffer */
*valptr; /* Pointer into string attribute */
/*
* Return quickly if we have a single string value...
*/
if (attr->num_values == 1 &&
attr->value_tag != IPP_TAG_INTEGER &&
attr->value_tag != IPP_TAG_ENUM &&
attr->value_tag != IPP_TAG_BOOLEAN &&
attr->value_tag != IPP_TAG_RANGE)
return (attr->values[0].string.text);
/*
* Copy the values to the string, separating with commas and escaping strings
* as needed...
*/
end = buffer + bufsize - 1;
for (i = 0, ptr = buffer; i < attr->num_values && ptr < end; i ++)
{
if (i)
*ptr++ = ',';
switch (attr->value_tag)
{
case IPP_TAG_INTEGER :
case IPP_TAG_ENUM :
snprintf(ptr, (size_t)(end - ptr + 1), "%d", attr->values[i].integer);
break;
case IPP_TAG_BOOLEAN :
if (attr->values[i].boolean)
strlcpy(ptr, "true", (size_t)(end - ptr + 1));
else
strlcpy(ptr, "false", (size_t)(end - ptr + 1));
break;
case IPP_TAG_RANGE :
if (attr->values[i].range.lower == attr->values[i].range.upper)
snprintf(ptr, (size_t)(end - ptr + 1), "%d", attr->values[i].range.lower);
else
snprintf(ptr, (size_t)(end - ptr + 1), "%d-%d", attr->values[i].range.lower, attr->values[i].range.upper);
break;
default :
for (valptr = attr->values[i].string.text;
*valptr && ptr < end;)
{
if (strchr(" \t\n\\\'\"", *valptr))
{
if (ptr >= (end - 1))
break;
*ptr++ = '\\';
}
*ptr++ = *valptr++;
}
*ptr = '\0';
break;
}
ptr += strlen(ptr);
}
*ptr = '\0';
return (buffer);
}
/*
* 'cups_name_cb()' - Find an enumerated destination.
*/
static int /* O - 1 to continue, 0 to stop */
cups_name_cb(_cups_namedata_t *data, /* I - Data from cupsGetNamedDest */
unsigned flags, /* I - Enumeration flags */
cups_dest_t *dest) /* I - Destination */
{
DEBUG_printf(("2cups_name_cb(data=%p(%s), flags=%x, dest=%p(%s)", (void *)data, data->name, flags, (void *)dest, dest->name));
if (!(flags & CUPS_DEST_FLAGS_REMOVED) && !dest->instance && !strcasecmp(data->name, dest->name))
{
/*
* Copy destination and stop enumeration...
*/
cupsCopyDest(dest, 0, &data->dest);
return (0);
}
return (1);
}
/*
* 'cups_queue_name()' - Create a local queue name based on the service name.
*/
static void
cups_queue_name(
char *name, /* I - Name buffer */
const char *serviceName, /* I - Service name */
size_t namesize) /* I - Size of name buffer */
{
const char *ptr; /* Pointer into serviceName */
char *nameptr; /* Pointer into name */
for (nameptr = name, ptr = serviceName; *ptr && nameptr < (name + namesize - 1); ptr ++)
{
/*
* Sanitize the printer name...
*/
if (_cups_isalnum(*ptr))
*nameptr++ = *ptr;
else if (nameptr == name || nameptr[-1] != '_')
*nameptr++ = '_';
}
*nameptr = '\0';
}
|
599325.c | class PluginVariables extends PluginBase
{
void PluginVariables()
{
m_Id = 0;
m_Variables = new map<int, string>;
// ("variable name")
RegisterVariable("varNote");
RegisterVariable("varColor");
}
void ~PluginVariables()
{
}
void RegisterVariable(string name)
{
m_Id++;
m_Variables.Set(m_Id,name);//REWORK.V maybe have 2 maps, one with key
}
int m_Id;
ref map<int, string> m_Variables;
string GetName(int id)
{
return m_Variables.Get(id);
}
int GetID(string name)
{
return m_Variables.GetKeyByValue(name);
}
}
|
1002612.c | /*
* ioctl32.c: Conversion between 32bit and 64bit native ioctls.
* Separated from fs stuff by Arnd Bergmann <[email protected]>
*
* Copyright (C) 1997-2000 Jakub Jelinek ([email protected])
* Copyright (C) 1998 Eddie C. Dost ([email protected])
* Copyright (C) 2001,2002 Andi Kleen, SuSE Labs
* Copyright (C) 2003 Pavel Machek ([email protected])
* Copyright (C) 2005 Philippe De Muyter ([email protected])
* Copyright (C) 2008 Hans Verkuil <[email protected]>
*
* These routines maintain argument size conversion between 32bit and 64bit
* ioctls.
*/
#include <linux/compat.h>
#include <linux/module.h>
#include <linux/videodev2.h>
#include <linux/v4l2-subdev.h>
#include <media/v4l2-dev.h>
#include <media/v4l2-ioctl.h>
static long native_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
long ret = -ENOIOCTLCMD;
if (file->f_op->unlocked_ioctl)
ret = file->f_op->unlocked_ioctl(file, cmd, arg);
return ret;
}
struct v4l2_clip32 {
struct v4l2_rect c;
compat_caddr_t next;
};
struct v4l2_window32 {
struct v4l2_rect w;
__u32 field; /* enum v4l2_field */
__u32 chromakey;
compat_caddr_t clips; /* actually struct v4l2_clip32 * */
__u32 clipcount;
compat_caddr_t bitmap;
};
static int get_v4l2_window32(struct v4l2_window *kp, struct v4l2_window32 __user *up)
{
if (!access_ok(VERIFY_READ, up, sizeof(struct v4l2_window32)) ||
copy_from_user(&kp->w, &up->w, sizeof(up->w)) ||
get_user(kp->field, &up->field) ||
get_user(kp->chromakey, &up->chromakey) ||
get_user(kp->clipcount, &up->clipcount))
return -EFAULT;
if (kp->clipcount > 2048)
return -EINVAL;
if (kp->clipcount) {
struct v4l2_clip32 __user *uclips;
struct v4l2_clip __user *kclips;
int n = kp->clipcount;
compat_caddr_t p;
if (get_user(p, &up->clips))
return -EFAULT;
uclips = compat_ptr(p);
kclips = compat_alloc_user_space(n * sizeof(struct v4l2_clip));
kp->clips = kclips;
while (--n >= 0) {
if (copy_in_user(&kclips->c, &uclips->c, sizeof(uclips->c)))
return -EFAULT;
if (put_user(n ? kclips + 1 : NULL, &kclips->next))
return -EFAULT;
uclips += 1;
kclips += 1;
}
} else
kp->clips = NULL;
return 0;
}
static int put_v4l2_window32(struct v4l2_window *kp, struct v4l2_window32 __user *up)
{
if (copy_to_user(&up->w, &kp->w, sizeof(kp->w)) ||
put_user(kp->field, &up->field) ||
put_user(kp->chromakey, &up->chromakey) ||
put_user(kp->clipcount, &up->clipcount))
return -EFAULT;
return 0;
}
static inline int get_v4l2_pix_format(struct v4l2_pix_format *kp, struct v4l2_pix_format __user *up)
{
if (copy_from_user(kp, up, sizeof(struct v4l2_pix_format)))
return -EFAULT;
return 0;
}
static inline int get_v4l2_pix_format_mplane(struct v4l2_pix_format_mplane *kp,
struct v4l2_pix_format_mplane __user *up)
{
if (copy_from_user(kp, up, sizeof(struct v4l2_pix_format_mplane)))
return -EFAULT;
return 0;
}
static inline int put_v4l2_pix_format(struct v4l2_pix_format *kp, struct v4l2_pix_format __user *up)
{
if (copy_to_user(up, kp, sizeof(struct v4l2_pix_format)))
return -EFAULT;
return 0;
}
static inline int put_v4l2_pix_format_mplane(struct v4l2_pix_format_mplane *kp,
struct v4l2_pix_format_mplane __user *up)
{
if (copy_to_user(up, kp, sizeof(struct v4l2_pix_format_mplane)))
return -EFAULT;
return 0;
}
static inline int get_v4l2_vbi_format(struct v4l2_vbi_format *kp, struct v4l2_vbi_format __user *up)
{
if (copy_from_user(kp, up, sizeof(struct v4l2_vbi_format)))
return -EFAULT;
return 0;
}
static inline int put_v4l2_vbi_format(struct v4l2_vbi_format *kp, struct v4l2_vbi_format __user *up)
{
if (copy_to_user(up, kp, sizeof(struct v4l2_vbi_format)))
return -EFAULT;
return 0;
}
static inline int get_v4l2_sliced_vbi_format(struct v4l2_sliced_vbi_format *kp, struct v4l2_sliced_vbi_format __user *up)
{
if (copy_from_user(kp, up, sizeof(struct v4l2_sliced_vbi_format)))
return -EFAULT;
return 0;
}
static inline int put_v4l2_sliced_vbi_format(struct v4l2_sliced_vbi_format *kp, struct v4l2_sliced_vbi_format __user *up)
{
if (copy_to_user(up, kp, sizeof(struct v4l2_sliced_vbi_format)))
return -EFAULT;
return 0;
}
struct v4l2_format32 {
__u32 type; /* enum v4l2_buf_type */
union {
struct v4l2_pix_format pix;
struct v4l2_pix_format_mplane pix_mp;
struct v4l2_window32 win;
struct v4l2_vbi_format vbi;
struct v4l2_sliced_vbi_format sliced;
__u8 raw_data[200]; /* user-defined */
} fmt;
};
/**
* struct v4l2_create_buffers32 - VIDIOC_CREATE_BUFS32 argument
* @index: on return, index of the first created buffer
* @count: entry: number of requested buffers,
* return: number of created buffers
* @memory: buffer memory type
* @format: frame format, for which buffers are requested
* @reserved: future extensions
*/
struct v4l2_create_buffers32 {
__u32 index;
__u32 count;
__u32 memory; /* enum v4l2_memory */
struct v4l2_format32 format;
__u32 reserved[8];
};
static int __get_v4l2_format32(struct v4l2_format *kp, struct v4l2_format32 __user *up)
{
if (get_user(kp->type, &up->type))
return -EFAULT;
switch (kp->type) {
case V4L2_BUF_TYPE_VIDEO_CAPTURE:
case V4L2_BUF_TYPE_VIDEO_OUTPUT:
return get_v4l2_pix_format(&kp->fmt.pix, &up->fmt.pix);
case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
return get_v4l2_pix_format_mplane(&kp->fmt.pix_mp,
&up->fmt.pix_mp);
case V4L2_BUF_TYPE_VIDEO_OVERLAY:
case V4L2_BUF_TYPE_VIDEO_OUTPUT_OVERLAY:
return get_v4l2_window32(&kp->fmt.win, &up->fmt.win);
case V4L2_BUF_TYPE_VBI_CAPTURE:
case V4L2_BUF_TYPE_VBI_OUTPUT:
return get_v4l2_vbi_format(&kp->fmt.vbi, &up->fmt.vbi);
case V4L2_BUF_TYPE_SLICED_VBI_CAPTURE:
case V4L2_BUF_TYPE_SLICED_VBI_OUTPUT:
return get_v4l2_sliced_vbi_format(&kp->fmt.sliced, &up->fmt.sliced);
default:
printk(KERN_INFO "compat_ioctl32: unexpected VIDIOC_FMT type %d\n",
kp->type);
return -EINVAL;
}
}
static int get_v4l2_format32(struct v4l2_format *kp, struct v4l2_format32 __user *up)
{
if (!access_ok(VERIFY_READ, up, sizeof(struct v4l2_format32)))
return -EFAULT;
return __get_v4l2_format32(kp, up);
}
static int get_v4l2_create32(struct v4l2_create_buffers *kp, struct v4l2_create_buffers32 __user *up)
{
if (!access_ok(VERIFY_READ, up, sizeof(struct v4l2_create_buffers32)) ||
copy_from_user(kp, up, offsetof(struct v4l2_create_buffers32, format)))
return -EFAULT;
return __get_v4l2_format32(&kp->format, &up->format);
}
static int __put_v4l2_format32(struct v4l2_format *kp, struct v4l2_format32 __user *up)
{
switch (kp->type) {
case V4L2_BUF_TYPE_VIDEO_CAPTURE:
case V4L2_BUF_TYPE_VIDEO_OUTPUT:
return put_v4l2_pix_format(&kp->fmt.pix, &up->fmt.pix);
case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
return put_v4l2_pix_format_mplane(&kp->fmt.pix_mp,
&up->fmt.pix_mp);
case V4L2_BUF_TYPE_VIDEO_OVERLAY:
case V4L2_BUF_TYPE_VIDEO_OUTPUT_OVERLAY:
return put_v4l2_window32(&kp->fmt.win, &up->fmt.win);
case V4L2_BUF_TYPE_VBI_CAPTURE:
case V4L2_BUF_TYPE_VBI_OUTPUT:
return put_v4l2_vbi_format(&kp->fmt.vbi, &up->fmt.vbi);
case V4L2_BUF_TYPE_SLICED_VBI_CAPTURE:
case V4L2_BUF_TYPE_SLICED_VBI_OUTPUT:
return put_v4l2_sliced_vbi_format(&kp->fmt.sliced, &up->fmt.sliced);
default:
printk(KERN_INFO "compat_ioctl32: unexpected VIDIOC_FMT type %d\n",
kp->type);
return -EINVAL;
}
}
static int put_v4l2_format32(struct v4l2_format *kp, struct v4l2_format32 __user *up)
{
if (!access_ok(VERIFY_WRITE, up, sizeof(struct v4l2_format32)) ||
put_user(kp->type, &up->type))
return -EFAULT;
return __put_v4l2_format32(kp, up);
}
static int put_v4l2_create32(struct v4l2_create_buffers *kp, struct v4l2_create_buffers32 __user *up)
{
if (!access_ok(VERIFY_WRITE, up, sizeof(struct v4l2_create_buffers32)) ||
copy_to_user(up, kp, offsetof(struct v4l2_create_buffers32, format.fmt)))
return -EFAULT;
return __put_v4l2_format32(&kp->format, &up->format);
}
struct v4l2_standard32 {
__u32 index;
compat_u64 id;
__u8 name[24];
struct v4l2_fract frameperiod; /* Frames, not fields */
__u32 framelines;
__u32 reserved[4];
};
static int get_v4l2_standard32(struct v4l2_standard *kp, struct v4l2_standard32 __user *up)
{
/* other fields are not set by the user, nor used by the driver */
if (!access_ok(VERIFY_READ, up, sizeof(struct v4l2_standard32)) ||
get_user(kp->index, &up->index))
return -EFAULT;
return 0;
}
static int put_v4l2_standard32(struct v4l2_standard *kp, struct v4l2_standard32 __user *up)
{
if (!access_ok(VERIFY_WRITE, up, sizeof(struct v4l2_standard32)) ||
put_user(kp->index, &up->index) ||
put_user(kp->id, &up->id) ||
copy_to_user(up->name, kp->name, 24) ||
copy_to_user(&up->frameperiod, &kp->frameperiod, sizeof(kp->frameperiod)) ||
put_user(kp->framelines, &up->framelines) ||
copy_to_user(up->reserved, kp->reserved, 4 * sizeof(__u32)))
return -EFAULT;
return 0;
}
struct v4l2_plane32 {
__u32 bytesused;
__u32 length;
union {
__u32 mem_offset;
compat_long_t userptr;
__s32 fd;
} m;
__u32 data_offset;
__u32 reserved[11];
};
struct v4l2_buffer32 {
__u32 index;
__u32 type; /* enum v4l2_buf_type */
__u32 bytesused;
__u32 flags;
__u32 field; /* enum v4l2_field */
struct compat_timeval timestamp;
struct v4l2_timecode timecode;
__u32 sequence;
/* memory location */
__u32 memory; /* enum v4l2_memory */
union {
__u32 offset;
compat_long_t userptr;
compat_caddr_t planes;
__s32 fd;
} m;
__u32 length;
__u32 reserved2;
__u32 reserved;
};
static int get_v4l2_plane32(struct v4l2_plane *up, struct v4l2_plane32 *up32,
enum v4l2_memory memory)
{
void __user *up_pln;
compat_long_t p;
if (copy_in_user(up, up32, 2 * sizeof(__u32)) ||
copy_in_user(&up->data_offset, &up32->data_offset,
sizeof(__u32)))
return -EFAULT;
if (memory == V4L2_MEMORY_USERPTR) {
if (get_user(p, &up32->m.userptr))
return -EFAULT;
up_pln = compat_ptr(p);
if (put_user((unsigned long)up_pln, &up->m.userptr))
return -EFAULT;
} else if (memory == V4L2_MEMORY_DMABUF) {
if (copy_in_user(&up->m.fd, &up32->m.fd, sizeof(int)))
return -EFAULT;
} else {
if (copy_in_user(&up->m.mem_offset, &up32->m.mem_offset,
sizeof(__u32)))
return -EFAULT;
}
return 0;
}
static int put_v4l2_plane32(struct v4l2_plane *up, struct v4l2_plane32 *up32,
enum v4l2_memory memory)
{
if (copy_in_user(up32, up, 2 * sizeof(__u32)) ||
copy_in_user(&up32->data_offset, &up->data_offset,
sizeof(__u32)))
return -EFAULT;
/* For MMAP, driver might've set up the offset, so copy it back.
* USERPTR stays the same (was userspace-provided), so no copying. */
if (memory == V4L2_MEMORY_MMAP)
if (copy_in_user(&up32->m.mem_offset, &up->m.mem_offset,
sizeof(__u32)))
return -EFAULT;
/* For DMABUF, driver might've set up the fd, so copy it back. */
if (memory == V4L2_MEMORY_DMABUF)
if (copy_in_user(&up32->m.fd, &up->m.fd,
sizeof(int)))
return -EFAULT;
return 0;
}
static int get_v4l2_buffer32(struct v4l2_buffer *kp, struct v4l2_buffer32 __user *up)
{
struct v4l2_plane32 __user *uplane32;
struct v4l2_plane __user *uplane;
compat_caddr_t p;
int num_planes;
int ret;
if (!access_ok(VERIFY_READ, up, sizeof(struct v4l2_buffer32)) ||
get_user(kp->index, &up->index) ||
get_user(kp->type, &up->type) ||
get_user(kp->flags, &up->flags) ||
get_user(kp->memory, &up->memory))
return -EFAULT;
if (V4L2_TYPE_IS_OUTPUT(kp->type))
if (get_user(kp->bytesused, &up->bytesused) ||
get_user(kp->field, &up->field) ||
get_user(kp->timestamp.tv_sec, &up->timestamp.tv_sec) ||
get_user(kp->timestamp.tv_usec,
&up->timestamp.tv_usec))
return -EFAULT;
if (V4L2_TYPE_IS_MULTIPLANAR(kp->type)) {
if (get_user(kp->length, &up->length))
return -EFAULT;
num_planes = kp->length;
if (num_planes == 0) {
kp->m.planes = NULL;
/* num_planes == 0 is legal, e.g. when userspace doesn't
* need planes array on DQBUF*/
return 0;
}
if (get_user(p, &up->m.planes))
return -EFAULT;
uplane32 = compat_ptr(p);
if (!access_ok(VERIFY_READ, uplane32,
num_planes * sizeof(struct v4l2_plane32)))
return -EFAULT;
/* We don't really care if userspace decides to kill itself
* by passing a very big num_planes value */
uplane = compat_alloc_user_space(num_planes *
sizeof(struct v4l2_plane));
kp->m.planes = uplane;
while (--num_planes >= 0) {
ret = get_v4l2_plane32(uplane, uplane32, kp->memory);
if (ret)
return ret;
++uplane;
++uplane32;
}
} else {
switch (kp->memory) {
case V4L2_MEMORY_MMAP:
if (get_user(kp->length, &up->length) ||
get_user(kp->m.offset, &up->m.offset))
return -EFAULT;
break;
case V4L2_MEMORY_USERPTR:
{
compat_long_t tmp;
if (get_user(kp->length, &up->length) ||
get_user(tmp, &up->m.userptr))
return -EFAULT;
kp->m.userptr = (unsigned long)compat_ptr(tmp);
}
break;
case V4L2_MEMORY_OVERLAY:
if (get_user(kp->m.offset, &up->m.offset))
return -EFAULT;
break;
case V4L2_MEMORY_DMABUF:
if (get_user(kp->m.fd, &up->m.fd))
return -EFAULT;
break;
}
}
return 0;
}
static int put_v4l2_buffer32(struct v4l2_buffer *kp, struct v4l2_buffer32 __user *up)
{
struct v4l2_plane32 __user *uplane32;
struct v4l2_plane __user *uplane;
compat_caddr_t p;
int num_planes;
int ret;
if (!access_ok(VERIFY_WRITE, up, sizeof(struct v4l2_buffer32)) ||
put_user(kp->index, &up->index) ||
put_user(kp->type, &up->type) ||
put_user(kp->flags, &up->flags) ||
put_user(kp->memory, &up->memory))
return -EFAULT;
if (put_user(kp->bytesused, &up->bytesused) ||
put_user(kp->field, &up->field) ||
put_user(kp->timestamp.tv_sec, &up->timestamp.tv_sec) ||
put_user(kp->timestamp.tv_usec, &up->timestamp.tv_usec) ||
copy_to_user(&up->timecode, &kp->timecode, sizeof(struct v4l2_timecode)) ||
put_user(kp->sequence, &up->sequence) ||
put_user(kp->reserved2, &up->reserved2) ||
put_user(kp->reserved, &up->reserved))
return -EFAULT;
if (V4L2_TYPE_IS_MULTIPLANAR(kp->type)) {
num_planes = kp->length;
if (num_planes == 0)
return 0;
uplane = kp->m.planes;
if (get_user(p, &up->m.planes))
return -EFAULT;
uplane32 = compat_ptr(p);
while (--num_planes >= 0) {
ret = put_v4l2_plane32(uplane, uplane32, kp->memory);
if (ret)
return ret;
++uplane;
++uplane32;
}
} else {
switch (kp->memory) {
case V4L2_MEMORY_MMAP:
if (put_user(kp->length, &up->length) ||
put_user(kp->m.offset, &up->m.offset))
return -EFAULT;
break;
case V4L2_MEMORY_USERPTR:
if (put_user(kp->length, &up->length) ||
put_user(kp->m.userptr, &up->m.userptr))
return -EFAULT;
break;
case V4L2_MEMORY_OVERLAY:
if (put_user(kp->m.offset, &up->m.offset))
return -EFAULT;
break;
case V4L2_MEMORY_DMABUF:
if (put_user(kp->m.fd, &up->m.fd))
return -EFAULT;
break;
}
}
return 0;
}
struct v4l2_framebuffer32 {
__u32 capability;
__u32 flags;
compat_caddr_t base;
struct v4l2_pix_format fmt;
};
static int get_v4l2_framebuffer32(struct v4l2_framebuffer *kp, struct v4l2_framebuffer32 __user *up)
{
u32 tmp;
if (!access_ok(VERIFY_READ, up, sizeof(struct v4l2_framebuffer32)) ||
get_user(tmp, &up->base) ||
get_user(kp->capability, &up->capability) ||
get_user(kp->flags, &up->flags))
return -EFAULT;
kp->base = compat_ptr(tmp);
get_v4l2_pix_format(&kp->fmt, &up->fmt);
return 0;
}
static int put_v4l2_framebuffer32(struct v4l2_framebuffer *kp, struct v4l2_framebuffer32 __user *up)
{
u32 tmp = (u32)((unsigned long)kp->base);
if (!access_ok(VERIFY_WRITE, up, sizeof(struct v4l2_framebuffer32)) ||
put_user(tmp, &up->base) ||
put_user(kp->capability, &up->capability) ||
put_user(kp->flags, &up->flags))
return -EFAULT;
put_v4l2_pix_format(&kp->fmt, &up->fmt);
return 0;
}
struct v4l2_input32 {
__u32 index; /* Which input */
__u8 name[32]; /* Label */
__u32 type; /* Type of input */
__u32 audioset; /* Associated audios (bitfield) */
__u32 tuner; /* Associated tuner */
compat_u64 std;
__u32 status;
__u32 reserved[4];
};
/* The 64-bit v4l2_input struct has extra padding at the end of the struct.
Otherwise it is identical to the 32-bit version. */
static inline int get_v4l2_input32(struct v4l2_input *kp, struct v4l2_input32 __user *up)
{
if (copy_from_user(kp, up, sizeof(struct v4l2_input32)))
return -EFAULT;
return 0;
}
static inline int put_v4l2_input32(struct v4l2_input *kp, struct v4l2_input32 __user *up)
{
if (copy_to_user(up, kp, sizeof(struct v4l2_input32)))
return -EFAULT;
return 0;
}
struct v4l2_ext_controls32 {
__u32 ctrl_class;
__u32 count;
__u32 error_idx;
__u32 reserved[2];
compat_caddr_t controls; /* actually struct v4l2_ext_control32 * */
};
struct v4l2_ext_control32 {
__u32 id;
__u32 size;
__u32 reserved2[1];
union {
__s32 value;
__s64 value64;
compat_caddr_t string; /* actually char * */
};
} __attribute__ ((packed));
/* The following function really belong in v4l2-common, but that causes
a circular dependency between modules. We need to think about this, but
for now this will do. */
/* Return non-zero if this control is a pointer type. Currently only
type STRING is a pointer type. */
static inline int ctrl_is_pointer(u32 id)
{
switch (id) {
case V4L2_CID_RDS_TX_PS_NAME:
case V4L2_CID_RDS_TX_RADIO_TEXT:
return 1;
default:
return 0;
}
}
static int get_v4l2_ext_controls32(struct v4l2_ext_controls *kp, struct v4l2_ext_controls32 __user *up)
{
struct v4l2_ext_control32 __user *ucontrols;
struct v4l2_ext_control __user *kcontrols;
int n;
compat_caddr_t p;
if (!access_ok(VERIFY_READ, up, sizeof(struct v4l2_ext_controls32)) ||
get_user(kp->ctrl_class, &up->ctrl_class) ||
get_user(kp->count, &up->count) ||
get_user(kp->error_idx, &up->error_idx) ||
copy_from_user(kp->reserved, up->reserved, sizeof(kp->reserved)))
return -EFAULT;
n = kp->count;
if (n == 0) {
kp->controls = NULL;
return 0;
}
if (get_user(p, &up->controls))
return -EFAULT;
ucontrols = compat_ptr(p);
if (!access_ok(VERIFY_READ, ucontrols,
n * sizeof(struct v4l2_ext_control32)))
return -EFAULT;
kcontrols = compat_alloc_user_space(n * sizeof(struct v4l2_ext_control));
kp->controls = kcontrols;
while (--n >= 0) {
if (copy_in_user(kcontrols, ucontrols, sizeof(*ucontrols)))
return -EFAULT;
if (ctrl_is_pointer(kcontrols->id)) {
void __user *s;
if (get_user(p, &ucontrols->string))
return -EFAULT;
s = compat_ptr(p);
if (put_user(s, &kcontrols->string))
return -EFAULT;
}
ucontrols++;
kcontrols++;
}
return 0;
}
static int put_v4l2_ext_controls32(struct v4l2_ext_controls *kp, struct v4l2_ext_controls32 __user *up)
{
struct v4l2_ext_control32 __user *ucontrols;
struct v4l2_ext_control __user *kcontrols = kp->controls;
int n = kp->count;
compat_caddr_t p;
if (!access_ok(VERIFY_WRITE, up, sizeof(struct v4l2_ext_controls32)) ||
put_user(kp->ctrl_class, &up->ctrl_class) ||
put_user(kp->count, &up->count) ||
put_user(kp->error_idx, &up->error_idx) ||
copy_to_user(up->reserved, kp->reserved, sizeof(up->reserved)))
return -EFAULT;
if (!kp->count)
return 0;
if (get_user(p, &up->controls))
return -EFAULT;
ucontrols = compat_ptr(p);
if (!access_ok(VERIFY_WRITE, ucontrols,
n * sizeof(struct v4l2_ext_control32)))
return -EFAULT;
while (--n >= 0) {
unsigned size = sizeof(*ucontrols);
/* Do not modify the pointer when copying a pointer control.
The contents of the pointer was changed, not the pointer
itself. */
if (ctrl_is_pointer(kcontrols->id))
size -= sizeof(ucontrols->value64);
if (copy_in_user(ucontrols, kcontrols, size))
return -EFAULT;
ucontrols++;
kcontrols++;
}
return 0;
}
struct v4l2_event32 {
__u32 type;
union {
compat_s64 value64;
__u8 data[64];
} u;
__u32 pending;
__u32 sequence;
struct compat_timespec timestamp;
__u32 id;
__u32 reserved[8];
};
static int put_v4l2_event32(struct v4l2_event *kp, struct v4l2_event32 __user *up)
{
if (!access_ok(VERIFY_WRITE, up, sizeof(struct v4l2_event32)) ||
put_user(kp->type, &up->type) ||
copy_to_user(&up->u, &kp->u, sizeof(kp->u)) ||
put_user(kp->pending, &up->pending) ||
put_user(kp->sequence, &up->sequence) ||
put_compat_timespec(&kp->timestamp, &up->timestamp) ||
put_user(kp->id, &up->id) ||
copy_to_user(up->reserved, kp->reserved, 8 * sizeof(__u32)))
return -EFAULT;
return 0;
}
struct v4l2_subdev_edid32 {
__u32 pad;
__u32 start_block;
__u32 blocks;
__u32 reserved[5];
compat_caddr_t edid;
};
static int get_v4l2_subdev_edid32(struct v4l2_subdev_edid *kp, struct v4l2_subdev_edid32 __user *up)
{
u32 tmp;
if (!access_ok(VERIFY_READ, up, sizeof(struct v4l2_subdev_edid32)) ||
get_user(kp->pad, &up->pad) ||
get_user(kp->start_block, &up->start_block) ||
get_user(kp->blocks, &up->blocks) ||
get_user(tmp, &up->edid) ||
copy_from_user(kp->reserved, up->reserved, sizeof(kp->reserved)))
return -EFAULT;
kp->edid = compat_ptr(tmp);
return 0;
}
static int put_v4l2_subdev_edid32(struct v4l2_subdev_edid *kp, struct v4l2_subdev_edid32 __user *up)
{
u32 tmp = (u32)((unsigned long)kp->edid);
if (!access_ok(VERIFY_WRITE, up, sizeof(struct v4l2_subdev_edid32)) ||
put_user(kp->pad, &up->pad) ||
put_user(kp->start_block, &up->start_block) ||
put_user(kp->blocks, &up->blocks) ||
put_user(tmp, &up->edid) ||
copy_to_user(kp->reserved, up->reserved, sizeof(kp->reserved)))
return -EFAULT;
return 0;
}
#define VIDIOC_G_FMT32 _IOWR('V', 4, struct v4l2_format32)
#define VIDIOC_S_FMT32 _IOWR('V', 5, struct v4l2_format32)
#define VIDIOC_QUERYBUF32 _IOWR('V', 9, struct v4l2_buffer32)
#define VIDIOC_G_FBUF32 _IOR ('V', 10, struct v4l2_framebuffer32)
#define VIDIOC_S_FBUF32 _IOW ('V', 11, struct v4l2_framebuffer32)
#define VIDIOC_QBUF32 _IOWR('V', 15, struct v4l2_buffer32)
#define VIDIOC_DQBUF32 _IOWR('V', 17, struct v4l2_buffer32)
#define VIDIOC_ENUMSTD32 _IOWR('V', 25, struct v4l2_standard32)
#define VIDIOC_ENUMINPUT32 _IOWR('V', 26, struct v4l2_input32)
#define VIDIOC_SUBDEV_G_EDID32 _IOWR('V', 40, struct v4l2_subdev_edid32)
#define VIDIOC_SUBDEV_S_EDID32 _IOWR('V', 41, struct v4l2_subdev_edid32)
#define VIDIOC_TRY_FMT32 _IOWR('V', 64, struct v4l2_format32)
#define VIDIOC_G_EXT_CTRLS32 _IOWR('V', 71, struct v4l2_ext_controls32)
#define VIDIOC_S_EXT_CTRLS32 _IOWR('V', 72, struct v4l2_ext_controls32)
#define VIDIOC_TRY_EXT_CTRLS32 _IOWR('V', 73, struct v4l2_ext_controls32)
#define VIDIOC_DQEVENT32 _IOR ('V', 89, struct v4l2_event32)
#define VIDIOC_CREATE_BUFS32 _IOWR('V', 92, struct v4l2_create_buffers32)
#define VIDIOC_PREPARE_BUF32 _IOWR('V', 93, struct v4l2_buffer32)
#define VIDIOC_OVERLAY32 _IOW ('V', 14, s32)
#define VIDIOC_STREAMON32 _IOW ('V', 18, s32)
#define VIDIOC_STREAMOFF32 _IOW ('V', 19, s32)
#define VIDIOC_G_INPUT32 _IOR ('V', 38, s32)
#define VIDIOC_S_INPUT32 _IOWR('V', 39, s32)
#define VIDIOC_G_OUTPUT32 _IOR ('V', 46, s32)
#define VIDIOC_S_OUTPUT32 _IOWR('V', 47, s32)
static long do_video_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
union {
struct v4l2_format v2f;
struct v4l2_buffer v2b;
struct v4l2_framebuffer v2fb;
struct v4l2_input v2i;
struct v4l2_standard v2s;
struct v4l2_ext_controls v2ecs;
struct v4l2_event v2ev;
struct v4l2_create_buffers v2crt;
struct v4l2_subdev_edid v2edid;
unsigned long vx;
int vi;
} karg;
void __user *up = compat_ptr(arg);
int compatible_arg = 1;
long err = 0;
/* First, convert the command. */
switch (cmd) {
case VIDIOC_G_FMT32: cmd = VIDIOC_G_FMT; break;
case VIDIOC_S_FMT32: cmd = VIDIOC_S_FMT; break;
case VIDIOC_QUERYBUF32: cmd = VIDIOC_QUERYBUF; break;
case VIDIOC_G_FBUF32: cmd = VIDIOC_G_FBUF; break;
case VIDIOC_S_FBUF32: cmd = VIDIOC_S_FBUF; break;
case VIDIOC_QBUF32: cmd = VIDIOC_QBUF; break;
case VIDIOC_DQBUF32: cmd = VIDIOC_DQBUF; break;
case VIDIOC_ENUMSTD32: cmd = VIDIOC_ENUMSTD; break;
case VIDIOC_ENUMINPUT32: cmd = VIDIOC_ENUMINPUT; break;
case VIDIOC_TRY_FMT32: cmd = VIDIOC_TRY_FMT; break;
case VIDIOC_G_EXT_CTRLS32: cmd = VIDIOC_G_EXT_CTRLS; break;
case VIDIOC_S_EXT_CTRLS32: cmd = VIDIOC_S_EXT_CTRLS; break;
case VIDIOC_TRY_EXT_CTRLS32: cmd = VIDIOC_TRY_EXT_CTRLS; break;
case VIDIOC_DQEVENT32: cmd = VIDIOC_DQEVENT; break;
case VIDIOC_OVERLAY32: cmd = VIDIOC_OVERLAY; break;
case VIDIOC_STREAMON32: cmd = VIDIOC_STREAMON; break;
case VIDIOC_STREAMOFF32: cmd = VIDIOC_STREAMOFF; break;
case VIDIOC_G_INPUT32: cmd = VIDIOC_G_INPUT; break;
case VIDIOC_S_INPUT32: cmd = VIDIOC_S_INPUT; break;
case VIDIOC_G_OUTPUT32: cmd = VIDIOC_G_OUTPUT; break;
case VIDIOC_S_OUTPUT32: cmd = VIDIOC_S_OUTPUT; break;
case VIDIOC_CREATE_BUFS32: cmd = VIDIOC_CREATE_BUFS; break;
case VIDIOC_PREPARE_BUF32: cmd = VIDIOC_PREPARE_BUF; break;
case VIDIOC_SUBDEV_G_EDID32: cmd = VIDIOC_SUBDEV_G_EDID; break;
case VIDIOC_SUBDEV_S_EDID32: cmd = VIDIOC_SUBDEV_S_EDID; break;
}
switch (cmd) {
case VIDIOC_OVERLAY:
case VIDIOC_STREAMON:
case VIDIOC_STREAMOFF:
case VIDIOC_S_INPUT:
case VIDIOC_S_OUTPUT:
err = get_user(karg.vi, (s32 __user *)up);
compatible_arg = 0;
break;
case VIDIOC_G_INPUT:
case VIDIOC_G_OUTPUT:
compatible_arg = 0;
break;
case VIDIOC_SUBDEV_G_EDID:
case VIDIOC_SUBDEV_S_EDID:
err = get_v4l2_subdev_edid32(&karg.v2edid, up);
compatible_arg = 0;
break;
case VIDIOC_G_FMT:
case VIDIOC_S_FMT:
case VIDIOC_TRY_FMT:
err = get_v4l2_format32(&karg.v2f, up);
compatible_arg = 0;
break;
case VIDIOC_CREATE_BUFS:
err = get_v4l2_create32(&karg.v2crt, up);
compatible_arg = 0;
break;
case VIDIOC_PREPARE_BUF:
case VIDIOC_QUERYBUF:
case VIDIOC_QBUF:
case VIDIOC_DQBUF:
err = get_v4l2_buffer32(&karg.v2b, up);
compatible_arg = 0;
break;
case VIDIOC_S_FBUF:
err = get_v4l2_framebuffer32(&karg.v2fb, up);
compatible_arg = 0;
break;
case VIDIOC_G_FBUF:
compatible_arg = 0;
break;
case VIDIOC_ENUMSTD:
err = get_v4l2_standard32(&karg.v2s, up);
compatible_arg = 0;
break;
case VIDIOC_ENUMINPUT:
err = get_v4l2_input32(&karg.v2i, up);
compatible_arg = 0;
break;
case VIDIOC_G_EXT_CTRLS:
case VIDIOC_S_EXT_CTRLS:
case VIDIOC_TRY_EXT_CTRLS:
err = get_v4l2_ext_controls32(&karg.v2ecs, up);
compatible_arg = 0;
break;
case VIDIOC_DQEVENT:
compatible_arg = 0;
break;
}
if (err)
return err;
if (compatible_arg)
err = native_ioctl(file, cmd, (unsigned long)up);
else {
mm_segment_t old_fs = get_fs();
set_fs(KERNEL_DS);
err = native_ioctl(file, cmd, (unsigned long)&karg);
set_fs(old_fs);
}
/* Special case: even after an error we need to put the
results back for these ioctls since the error_idx will
contain information on which control failed. */
switch (cmd) {
case VIDIOC_G_EXT_CTRLS:
case VIDIOC_S_EXT_CTRLS:
case VIDIOC_TRY_EXT_CTRLS:
if (put_v4l2_ext_controls32(&karg.v2ecs, up))
err = -EFAULT;
break;
}
if (err)
return err;
switch (cmd) {
case VIDIOC_S_INPUT:
case VIDIOC_S_OUTPUT:
case VIDIOC_G_INPUT:
case VIDIOC_G_OUTPUT:
err = put_user(((s32)karg.vi), (s32 __user *)up);
break;
case VIDIOC_G_FBUF:
err = put_v4l2_framebuffer32(&karg.v2fb, up);
break;
case VIDIOC_DQEVENT:
err = put_v4l2_event32(&karg.v2ev, up);
break;
case VIDIOC_SUBDEV_G_EDID:
case VIDIOC_SUBDEV_S_EDID:
err = put_v4l2_subdev_edid32(&karg.v2edid, up);
break;
case VIDIOC_G_FMT:
case VIDIOC_S_FMT:
case VIDIOC_TRY_FMT:
err = put_v4l2_format32(&karg.v2f, up);
break;
case VIDIOC_CREATE_BUFS:
err = put_v4l2_create32(&karg.v2crt, up);
break;
case VIDIOC_QUERYBUF:
case VIDIOC_QBUF:
case VIDIOC_DQBUF:
err = put_v4l2_buffer32(&karg.v2b, up);
break;
case VIDIOC_ENUMSTD:
err = put_v4l2_standard32(&karg.v2s, up);
break;
case VIDIOC_ENUMINPUT:
err = put_v4l2_input32(&karg.v2i, up);
break;
}
return err;
}
long v4l2_compat_ioctl32(struct file *file, unsigned int cmd, unsigned long arg)
{
struct video_device *vdev = video_devdata(file);
long ret = -ENOIOCTLCMD;
if (!file->f_op->unlocked_ioctl)
return ret;
switch (cmd) {
case VIDIOC_QUERYCAP:
case VIDIOC_RESERVED:
case VIDIOC_ENUM_FMT:
case VIDIOC_G_FMT32:
case VIDIOC_S_FMT32:
case VIDIOC_REQBUFS:
case VIDIOC_QUERYBUF32:
case VIDIOC_G_FBUF32:
case VIDIOC_S_FBUF32:
case VIDIOC_OVERLAY32:
case VIDIOC_QBUF32:
case VIDIOC_EXPBUF:
case VIDIOC_DQBUF32:
case VIDIOC_STREAMON32:
case VIDIOC_STREAMOFF32:
case VIDIOC_G_PARM:
case VIDIOC_S_PARM:
case VIDIOC_G_STD:
case VIDIOC_S_STD:
case VIDIOC_ENUMSTD32:
case VIDIOC_ENUMINPUT32:
case VIDIOC_G_CTRL:
case VIDIOC_S_CTRL:
case VIDIOC_G_TUNER:
case VIDIOC_S_TUNER:
case VIDIOC_G_AUDIO:
case VIDIOC_S_AUDIO:
case VIDIOC_QUERYCTRL:
case VIDIOC_QUERYMENU:
case VIDIOC_G_INPUT32:
case VIDIOC_S_INPUT32:
case VIDIOC_G_OUTPUT32:
case VIDIOC_S_OUTPUT32:
case VIDIOC_ENUMOUTPUT:
case VIDIOC_G_AUDOUT:
case VIDIOC_S_AUDOUT:
case VIDIOC_G_MODULATOR:
case VIDIOC_S_MODULATOR:
case VIDIOC_S_FREQUENCY:
case VIDIOC_G_FREQUENCY:
case VIDIOC_CROPCAP:
case VIDIOC_G_CROP:
case VIDIOC_S_CROP:
case VIDIOC_G_SELECTION:
case VIDIOC_S_SELECTION:
case VIDIOC_G_JPEGCOMP:
case VIDIOC_S_JPEGCOMP:
case VIDIOC_QUERYSTD:
case VIDIOC_TRY_FMT32:
case VIDIOC_ENUMAUDIO:
case VIDIOC_ENUMAUDOUT:
case VIDIOC_G_PRIORITY:
case VIDIOC_S_PRIORITY:
case VIDIOC_G_SLICED_VBI_CAP:
case VIDIOC_LOG_STATUS:
case VIDIOC_G_EXT_CTRLS32:
case VIDIOC_S_EXT_CTRLS32:
case VIDIOC_TRY_EXT_CTRLS32:
case VIDIOC_ENUM_FRAMESIZES:
case VIDIOC_ENUM_FRAMEINTERVALS:
case VIDIOC_G_ENC_INDEX:
case VIDIOC_ENCODER_CMD:
case VIDIOC_TRY_ENCODER_CMD:
case VIDIOC_DECODER_CMD:
case VIDIOC_TRY_DECODER_CMD:
case VIDIOC_DBG_S_REGISTER:
case VIDIOC_DBG_G_REGISTER:
case VIDIOC_DBG_G_CHIP_IDENT:
case VIDIOC_S_HW_FREQ_SEEK:
case VIDIOC_S_DV_TIMINGS:
case VIDIOC_G_DV_TIMINGS:
case VIDIOC_DQEVENT:
case VIDIOC_DQEVENT32:
case VIDIOC_SUBSCRIBE_EVENT:
case VIDIOC_UNSUBSCRIBE_EVENT:
case VIDIOC_CREATE_BUFS32:
case VIDIOC_PREPARE_BUF32:
case VIDIOC_ENUM_DV_TIMINGS:
case VIDIOC_QUERY_DV_TIMINGS:
case VIDIOC_DV_TIMINGS_CAP:
case VIDIOC_ENUM_FREQ_BANDS:
case VIDIOC_SUBDEV_G_EDID32:
case VIDIOC_SUBDEV_S_EDID32:
ret = do_video_ioctl(file, cmd, arg);
break;
default:
if (vdev->fops->compat_ioctl32)
ret = vdev->fops->compat_ioctl32(file, cmd, arg);
if (ret == -ENOIOCTLCMD)
printk(KERN_WARNING "compat_ioctl32: "
"unknown ioctl '%c', dir=%d, #%d (0x%08x)\n",
_IOC_TYPE(cmd), _IOC_DIR(cmd), _IOC_NR(cmd),
cmd);
break;
}
return ret;
}
EXPORT_SYMBOL_GPL(v4l2_compat_ioctl32);
|
776935.c | /* $OpenBSD: strtold.c,v 1.1 2008/09/07 20:36:08 martynas Exp $ */
/*-
* Copyright (c) 2003 David Schultz <[email protected]>
* 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.
*/
/*
* Machine-dependent glue to integrate David Gay's gdtoa
* package into libc for architectures where a long double
* is the same as a double, such as the Alpha.
*/
#include "gdtoaimp.h"
long double
strtold(const char * __restrict s, char ** __restrict sp)
{
return strtod(s, sp);
}
|
119781.c | /******************************************************************************
* drivers/wireless/spirit/lib/spirit_gpio.c
* This file provides all the low level API to manage SPIRIT GPIO.
*
* Copyright(c) 2015 STMicroelectronics
* Author: VMA division - AMS
* Version 3.2.2 08-July-2015
*
* Adapted for NuttX by:
* Author: Gregory Nutt <[email protected]>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics 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 HOLDER 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.
*
******************************************************************************/
/******************************************************************************
* Included Files
******************************************************************************/
#include <stdint.h>
#include <assert.h>
#include "spirit_gpio.h"
#include "spirit_spi.h"
/******************************************************************************
* Public Functions
******************************************************************************/
/******************************************************************************
* Name: spirit_gpio_initialize
*
* Description:
* Initializes the Spirit GPIOx according to the specified parameters in
* the gpioinit parameter.
*
* Input Parameters:
* spirit - Reference to a Spirit library state structure instance
* gpioinit - A pointer to a struct spirit_gpio_init_s structure that
* contains the configuration information for the specified
* SPIRIT GPIO.
*
* Returned Value:
* Zero (OK) on success; a negated errno value on failure.
*
******************************************************************************/
int spirit_gpio_initialize(FAR struct spirit_library_s *spirit,
FAR const struct spirit_gpio_init_s *gpioinit)
{
uint8_t regval = 0x00;
/* Check the parameters */
DEBUGASSERT(IS_SPIRIT_GPIO(gpioinit->gpiopin));
DEBUGASSERT(IS_SPIRIT_GPIO_MODE(gpioinit->gpiomode));
DEBUGASSERT(IS_SPIRIT_GPIO_IO(gpioinit->gpioio));
regval = ((uint8_t)(gpioinit->gpiomode) | (uint8_t)(gpioinit->gpioio));
return spirit_reg_write(spirit, gpioinit->gpiopin, ®val, 1);
}
/******************************************************************************
* Name: spirit_gpio_enable_tempsensor
*
* Description:
* Enables or Disables the output of temperature sensor on SPIRIT GPIO_0.
*
* Input Parameters:
* spirit - Reference to a Spirit library state structure instance
* newstate - Bew state for temperature sensor.
*
* Returned Value:
* Zero (OK) on success; a negated errno value on failure.
*
******************************************************************************/
int spirit_gpio_enable_tempsensor(FAR struct spirit_library_s *spirit,
enum spirit_functional_state_e newstate)
{
uint8_t regval = 0;
uint8_t gpio0regval = 0;
int ret;
/* Check the parameters */
DEBUGASSERT(IS_SPIRIT_FUNCTIONAL_STATE(newstate));
/* Reads the ANA_FUNC_CONF0 register and mask the result to enable or disable
* the temperature sensor */
ret = spirit_reg_read(spirit, ANA_FUNC_CONF0_BASE, ®val, 1);
if (ret >= 0)
{
if (newstate == S_ENABLE)
{
regval |= TEMPERATURE_SENSOR_MASK;
}
else
{
regval &= (~TEMPERATURE_SENSOR_MASK);
gpio0regval = 0x0a; /* Default value */
}
ret = spirit_reg_write(spirit, ANA_FUNC_CONF0_BASE, ®val, 1);
if (ret >= 0)
{
/* Sets the SPIRIT GPIO_0 according to input request */
ret = spirit_reg_write(spirit, GPIO0_CONF_BASE, &gpio0regval, 1);
}
}
return ret;
}
/******************************************************************************
* Name: spirit_gpio_set_outputlevel
*
* Description:
* Forces SPIRIT GPIO_x configured as digital output, to VDD or GND.
*
* Input Parameters:
* spirit - Reference to a Spirit library state structure instance
* gpio - Specifies the GPIO to be configured. This parameter can be one
* of following values:
*
* SPIRIT_GPIO_0: SPIRIT GPIO_0
* SPIRIT_GPIO_1: SPIRIT GPIO_1
* SPIRIT_GPIO_2: SPIRIT GPIO_2
* SPIRIT_GPIO_3: SPIRIT GPIO_3
*
* level - Specifies the level. This parameter can be: HIGH or LOW.
*
* Returned Value:
* Zero (OK) on success; a negated errno value on failure.
*
******************************************************************************/
int spirit_gpio_set_outputlevel(FAR struct spirit_library_s *spirit,
enum spirit_gpio_pin_e gpio,
enum spirit_outputlevel_e level)
{
uint8_t regval = 0;
int ret;
/* Check the parameters */
DEBUGASSERT(IS_SPIRIT_GPIO(gpio));
DEBUGASSERT(IS_SPIRIT_GPIO_LEVEL(level));
/* Reads the SPIRIT_GPIOx register and mask the GPIO_SELECT field */
ret = spirit_reg_read(spirit, gpio, ®val, 1);
if (ret >= 0)
{
regval &= 0x04;
/* Sets the value of the SPIRIT GPIO register according to the
* specified level.
*/
if (level == HIGH)
{
regval |= (uint8_t)SPIRIT_GPIO_DIG_OUT_VDD |
(uint8_t)SPIRIT_GPIO_MODE_DIGITAL_OUTPUT_HP;
}
else
{
regval |= (uint8_t)SPIRIT_GPIO_DIG_OUT_GND |
(uint8_t)SPIRIT_GPIO_MODE_DIGITAL_OUTPUT_HP;
}
/* Write to the SPIRIT GPIO register */
ret = spirit_reg_write(spirit, gpio, ®val, 1);
}
return ret;
}
/******************************************************************************
* Name: spirit_gpio_get_outputlevel
*
* Description:
* Returns output value (VDD or GND) of SPIRIT GPIO_x, when it is configured
* as digital output.
*
* Input Parameters:
* spirit - Reference to a Spirit library state structure instance
* gpio - Specifies the GPIO to be read. This parameter can be one of
* following values:
*
* SPIRIT_GPIO_0: SPIRIT GPIO_0
* SPIRIT_GPIO_1: SPIRIT GPIO_1
* SPIRIT_GPIO_2: SPIRIT GPIO_2
* SPIRIT_GPIO_3: SPIRIT GPIO_3
*
* Returned Value:
* Logical level of selected GPIO configured as digital output. This
* parameter can be: HIGH or LOW.
*
******************************************************************************/
enum spirit_outputlevel_e
spirit_gpio_get_outputlevel(FAR struct spirit_library_s *spirit,
enum spirit_gpio_pin_e gpio)
{
enum spirit_outputlevel_e level;
uint8_t regval = 0;
/* Check the parameters */
DEBUGASSERT(IS_SPIRIT_GPIO(gpio));
/* Reads the SPIRIT_GPIOx register */
(void)spirit_reg_read(spirit, gpio, ®val, 1);
/* Mask the GPIO_SELECT field and returns the value according */
regval &= 0xf8;
if (regval == SPIRIT_GPIO_DIG_OUT_VDD)
{
level = HIGH;
}
else
{
level = LOW;
}
return level;
}
/******************************************************************************
* Name: spirit_gpio_enable_clockoutput
*
* Description:
* Enables or Disables the MCU clock output.
*
* Input Parameters:
* spirit - Reference to a Spirit library state structure instance
* newstate - New state for the MCU clock output. This parameter can be:
* S_ENABLE or S_DISABLE.
*
* Returned Value:
* Zero (OK) on success; a negated errno value on failure.
*
******************************************************************************/
int spirit_gpio_enable_clockoutput(FAR struct spirit_library_s *spirit,
enum spirit_functional_state_e newstate)
{
uint8_t regval;
int ret;
/* Check the parameters */
DEBUGASSERT(IS_SPIRIT_FUNCTIONAL_STATE(newstate));
/* Reads the MCU_CK_CONF register and mask the result to enable or disable
* the clock output */
ret = spirit_reg_read(spirit, MCU_CK_CONF_BASE, ®val, 1);
if (ret >= 0)
{
if (newstate)
{
regval |= MCU_CK_ENABLE;
}
else
{
regval &= (~MCU_CK_ENABLE);
}
/* Write to the MCU_CK_CONF register */
ret = spirit_reg_write(spirit, MCU_CK_CONF_BASE, ®val, 1);
}
return ret;
}
/******************************************************************************
* Name: spirit_gpio_clockoutput_initialize
*
* Description:
* Initializes the SPIRIT Clock Output according to the specified parameters
* in the xClockOutputInitStruct.
*
* NOTE: The function spirit_gpio_enable_clockoutput() must be called in order to
* enable or disable the MCU clock dividers.
*
* Input Parameters:
* spirit - Reference to a Spirit library state structure instance
* clockoutput - Pointer to a struct spirit_clockoutput_init_s structure
* that contains the configuration information for the SPIRIT
* Clock Output.
*
* Returned Value:
* Zero (OK) on success; a negated errno value on failure.
*
******************************************************************************/
int spirit_gpio_clockoutput_initialize(FAR struct spirit_library_s *spirit,
FAR const struct spirit_clockoutput_init_s *clockoutput)
{
uint8_t regval = 0;
/* Check the parameters */
DEBUGASSERT(IS_SPIRIT_CLOCK_OUTPUT_XO(clockoutput->xoprescaler));
DEBUGASSERT(IS_SPIRIT_CLOCK_OUTPUT_RCO(clockoutput->rcoprescaler));
DEBUGASSERT(IS_SPIRIT_CLOCK_OUTPUT_EXTRA_CYCLES(clockoutput->xtracycles));
/* Calculates the register value to write according to the specified
* configuration */
regval = ((uint8_t)(clockoutput->xoprescaler) |
(uint8_t)(clockoutput->rcoprescaler) |
(uint8_t)(clockoutput->xtracycles));
/* Write to the the MCU_CLOCK register */
return spirit_reg_write(spirit, MCU_CK_CONF_BASE, ®val, 1);
}
/******************************************************************************
* Name: spirit_gpio_set_xoprescaler
*
* Description:
* Sets the XO ratio as clock output.
*
* Input Parameters:
* spirit - Reference to a Spirit library state structure instance
* xoprescaler - the XO prescaler to be used as clock output. This
* parameter can be any value from enum
* spirit_clockoutput_xoprescaler_e .
*
* Returned Value:
* Zero (OK) on success; a negated errno value on failure.
*
******************************************************************************/
int spirit_gpio_set_xoprescaler(FAR struct spirit_library_s *spirit,
enum spirit_clockoutput_xoprescaler_e xoprescaler)
{
uint8_t regval = 0;
int ret;
/* Check the parameters */
DEBUGASSERT(IS_SPIRIT_CLOCK_OUTPUT_XO(xoprescaler));
/* Reads the MCU_CLK_CONFIG register */
ret = spirit_reg_read(spirit, MCU_CK_CONF_BASE, ®val, 1);
if (ret >= 0)
{
/* Mask the XO_RATIO field and writes the new value */
regval &= 0x61;
regval |= (uint8_t)xoprescaler;
/* Write to the new XO prescaler in the MCU_CLOCK register */
ret = spirit_reg_write(spirit, MCU_CK_CONF_BASE, ®val, 1);
}
return ret;
}
/******************************************************************************
* Name: spirit_gpio_get_xoprescaler
*
* Description:
* Returns the settled XO prescaler as clock output.
*
* Input Parameters:
* spirit - Reference to a Spirit library state structure instance
*
* Returned Value:
* Settled XO prescaler used for clock output.
*
******************************************************************************/
enum spirit_clockoutput_xoprescaler_e
spirit_gpio_get_xoprescaler(FAR struct spirit_library_s *spirit)
{
uint8_t regval = 0x00;
/* Reads the MCU_CLK_CONFIG register */
(void)spirit_reg_read(spirit, MCU_CK_CONF_BASE, ®val, 1);
/* Mask the XO_RATIO field and return the value */
return ((enum spirit_clockoutput_xoprescaler_e)(regval & 0x1e));
}
/******************************************************************************
* Name: spirit_gpio_set_rcoprescaler
*
* Description:
* Sets the RCO ratio as clock output
*
* Input Parameters:
* spirit - Reference to a Spirit library state structure instance
* rcoprescaler - The RCO prescaler to be used as clock output. This
* parameter can be any value from enum
* spirit_clockoutput_rcoprescaler_e .
*
* Returned Value:
* Zero (OK) on success; a negated errno value on failure.
*
******************************************************************************/
int spirit_gpio_set_rcoprescaler(FAR struct spirit_library_s *spirit,
enum spirit_clockoutput_rcoprescaler_e rcoprescaler)
{
uint8_t regval = 0;
int ret;
/* Check the parameters */
DEBUGASSERT(IS_SPIRIT_CLOCK_OUTPUT_RCO(rcoprescaler));
/* Reads the MCU_CLK_CONFIG register */
ret = spirit_reg_read(spirit, MCU_CK_CONF_BASE, ®val, 1);
if (ret >= 0)
{
/* Mask the RCO_RATIO field and writes the new value */
regval &= 0xfe;
regval |= (uint8_t)rcoprescaler;
/* Write to the new RCO prescaler in the MCU_CLOCK register */
ret = spirit_reg_write(spirit, MCU_CK_CONF_BASE, ®val, 1);
}
return ret;
}
/******************************************************************************
* Name: spirit_gpio_get_rcoprescaler
*
* Description:
* Returns the settled RCO prescaler as clock output.
*
* Input Parameters:
* spirit - Reference to a Spirit library state structure instance
*
* Returned Value:
* Settled RCO prescaler used for clock output.
*
******************************************************************************/
enum spirit_clockoutput_rcoprescaler_e
spirit_gpio_get_rcoprescaler(FAR struct spirit_library_s *spirit)
{
uint8_t regval = 0;
/* Reads the MCU_CLK_CONFIG register */
(void)spirit_reg_read(spirit, MCU_CK_CONF_BASE, ®val, 1);
/* Mask the RCO_RATIO field and returns the value */
return ((enum spirit_clockoutput_rcoprescaler_e)(regval & 0x01));
}
/******************************************************************************
* Name: spirit_gpio_set_extracycles
*
* Description:
* Sets the RCO ratio as clock output.
*
* Input Parameters:
* spirit - Reference to a Spirit library state structure instance
* xtracycles - The number of extra clock cycles provided before switching
* to STANDBY state. This parameter can be any value of enum
* spirit_extra_clockcycles_e.
*
* Returned Value:
* Zero (OK) on success; a negated errno value on failure.
*
******************************************************************************/
int spirit_gpio_set_extracycles(FAR struct spirit_library_s *spirit,
enum spirit_extra_clockcycles_e xtracycles)
{
uint8_t regval = 0;
int ret;
/* Check the parameters */
DEBUGASSERT(IS_SPIRIT_CLOCK_OUTPUT_EXTRA_CYCLES(xtracycles));
/* Reads the MCU_CLK_CONFIG register */
ret = spirit_reg_read(spirit, MCU_CK_CONF_BASE, ®val, 1);
if (ret >= 0)
{
/* Mask the CLOCK_TAIL field and writes the new value */
regval &= 0x9f;
regval |= (uint8_t)xtracycles;
/* Write to the new number of extra clock cycles in the MCU_CLOCK
* register.
*/
ret = spirit_reg_write(spirit, MCU_CK_CONF_BASE, ®val, 1);
}
return ret;
}
/******************************************************************************
* Name: spirit_gpio_get_extracycles
*
* Description:
* Returns the settled RCO prescaler as clock output.
*
* Input Parameters:
* spirit - Reference to a Spirit library state structure instance
*
* Returned Value:
* Settled number of extra clock cycles provided before switching to STANDBY
* state.
*
******************************************************************************/
enum spirit_extra_clockcycles_e
spirit_gpio_get_extracycles(FAR struct spirit_library_s *spirit)
{
uint8_t regval = 0;
/* Reads the MCU_CLK_CONFIG register */
(void)spirit_reg_read(spirit, MCU_CK_CONF_BASE, ®val, 1);
/* Mask the CLOCK_TAIL field and returns the value */
return ((enum spirit_extra_clockcycles_e)(regval & 0x60));
}
|
905728.c | /****************************************************************************
* config/flipnclick-pic32mz/src/pic32mz_appinit.c
*
* Copyright (C) 2018 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name NuttX 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.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <nuttx/board.h>
#include "flipnclick-pic32mz.h"
#ifdef CONFIG_LIB_BOARDCTL
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: board_app_initialize
*
* Description:
* Perform application specific initialization. This function is never
* called directly from application code, but only indirectly via the
* (non-standard) boardctl() interface using the command BOARDIOC_INIT.
*
* Input Parameters:
* arg - The boardctl() argument is passed to the board_app_initialize()
* implementation without modification. The argument has no
* meaning to NuttX; the meaning of the argument is a contract
* between the board-specific initalization logic and the
* matching application logic. The value cold be such things as a
* mode enumeration value, a set of DIP switch switch settings, a
* pointer to configuration data read from a file or serial FLASH,
* or whatever you would like to do with it. Every implementation
* should accept zero/NULL as a default configuration.
*
* Returned Value:
* Zero (OK) is returned on success; a negated errno value is returned on
* any failure to indicate the nature of the failure.
*
****************************************************************************/
int board_app_initialize(uintptr_t arg)
{
/* If CONFIG_BOARD_LATE_INITIALIZE is selected then board initialization was
* already performed in board_late_initialize.
*/
#ifndef CONFIG_BOARD_LATE_INITIALIZE
return pic32mz_bringup();
#else
return OK;
#endif
}
#endif /* CONFIG_LIB_BOARDCTL */
|
191885.c | /* thread.c
* Copyright 1984-2017 Cisco Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "system.h"
static thread_gc *free_thread_gcs;
/* locally defined functions */
#ifdef PTHREADS
static s_thread_rv_t start_thread PROTO((void *tc));
static IBOOL destroy_thread PROTO((ptr tc));
#endif
void S_thread_init() {
if (S_boot_time) {
S_protect(&S_G.threadno);
S_G.threadno = FIX(0);
#ifdef PTHREADS
/* this is also reset in scheme.c after heap restoration */
s_thread_mutex_init(&S_tc_mutex.pmutex);
S_tc_mutex.owner = s_thread_self();
S_tc_mutex.count = 0;
s_thread_cond_init(&S_collect_cond);
s_thread_cond_init(&S_collect_thread0_cond);
s_thread_mutex_init(&S_alloc_mutex.pmutex);
s_thread_cond_init(&S_terminated_cond);
S_alloc_mutex.owner = 0;
S_alloc_mutex.count = 0;
# ifdef IMPLICIT_ATOMIC_AS_EXPLICIT
s_thread_mutex_init(&S_implicit_mutex);
# endif
#endif /* PTHREADS */
}
}
/* this needs to be reworked. currently, S_create_thread_object is
called from main to create the base thread, from fork_thread when
there is already an active current thread, and from S_activate_thread
when there is no current thread. scheme.c does part of the initialization of the
base thread (e.g., parameters, current input/output ports) in one
or more places. */
ptr S_create_thread_object(who, p_tc) const char *who; ptr p_tc; {
ptr thread, tc;
thread_gc *tgc;
INT i;
tc_mutex_acquire();
if (S_threads == Snil) {
tc = TO_PTR(S_G.thread_context);
tgc = &S_G.main_thread_gc;
GCDATA(tc) = TO_PTR(tgc);
tgc->tc = tc;
} else { /* clone parent */
ptr p_v = PARAMETERS(p_tc);
iptr i, n = Svector_length(p_v);
ptr v;
tc = TO_PTR(malloc(size_tc));
if (free_thread_gcs) {
tgc = free_thread_gcs;
free_thread_gcs = tgc->next;
} else
tgc = malloc(sizeof(thread_gc));
if (tc == (ptr)0)
S_error(who, "unable to malloc thread data structure");
memcpy(TO_VOIDP(tc), TO_VOIDP(p_tc), size_tc);
GCDATA(tc) = TO_PTR(tgc);
tgc->tc = tc;
{
IGEN g; ISPC s;
for (g = 0; g <= static_generation; g++) {
for (s = 0; s <= max_real_space; s++) {
tgc->base_loc[g][s] = (ptr)0;
tgc->next_loc[g][s] = (ptr)0;
tgc->bytes_left[g][s] = 0;
tgc->sweep_loc[g][s] = (ptr)0;
tgc->sweep_next[g][s] = NULL;
}
tgc->bitmask_overhead[g] = 0;
}
}
tgc->during_alloc = 0;
tgc->pending_ephemerons = (ptr)0;
for (i = 0; i < (int)DIRTY_SEGMENT_LISTS; i++)
tgc->dirty_segments[i] = NULL;
tgc->queued_fire = 0;
tgc->preserve_ownership = 0;
v = S_vector_in(tc, space_new, 0, n);
for (i = 0; i < n; i += 1)
INITVECTIT(v, i) = Svector_ref(p_v, i);
PARAMETERS(tc) = v;
CODERANGESTOFLUSH(tc) = Snil;
}
tgc->sweeper = main_sweeper_index;
/* override nonclonable tc fields */
THREADNO(tc) = S_G.threadno;
S_G.threadno = S_add(S_G.threadno, FIX(1));
CCHAIN(tc) = Snil;
WINDERS(tc) = Snil;
ATTACHMENTS(tc) = Snil;
CACHEDFRAME(tc) = Sfalse;
STACKLINK(tc) = SYMVAL(S_G.null_continuation_id);
STACKCACHE(tc) = Snil;
/* S_reset_scheme_stack initializes stack, size, esp, and sfp */
S_reset_scheme_stack(tc, stack_slop);
FRAME(tc,0) = TO_PTR(&CODEIT(S_G.dummy_code_object,size_rp_header));
/* S_reset_allocation_pointer initializes ap and eap */
alloc_mutex_acquire();
S_reset_allocation_pointer(tc);
alloc_mutex_release();
S_maybe_fire_collector(tgc);
RANDOMSEED(tc) = most_positive_fixnum < 0xffffffff ? most_positive_fixnum : 0xffffffff;
X(tc) = Y(tc) = U(tc) = V(tc) = W(tc) = FIX(0);
TIMERTICKS(tc) = Sfalse;
DISABLECOUNT(tc) = Sfixnum(0);
SIGNALINTERRUPTPENDING(tc) = Sfalse;
SIGNALINTERRUPTQUEUE(tc) = S_allocate_scheme_signal_queue();
KEYBOARDINTERRUPTPENDING(tc) = Sfalse;
TARGETMACHINE(tc) = S_intern((const unsigned char *)MACHINE_TYPE);
/* choosing not to clone virtual registers */
for (i = 0 ; i < virtual_register_count ; i += 1) {
VIRTREG(tc, i) = FIX(0);
}
DSTBV(tc) = SRCBV(tc) = Sfalse;
thread = S_thread(tc);
S_threads = S_cons_in(tc, space_new, 0, thread, S_threads);
S_nthreads += 1;
SETSYMVAL(S_G.active_threads_id,
FIX(UNFIX(SYMVAL(S_G.active_threads_id)) + 1));
ACTIVE(tc) = 1;
/* collect request is only thing that can be pending for new thread.
must do this after we're on the thread list in case the cons
adding us onto the thread list set collect-request-pending */
SOMETHINGPENDING(tc) = SYMVAL(S_G.collect_request_pending_id);
GUARDIANENTRIES(tc) = Snil;
LZ4OUTBUFFER(tc) = 0;
CP(tc) = 0;
tc_mutex_release();
return thread;
}
#ifdef PTHREADS
IBOOL Sactivate_thread() { /* create or reactivate current thread */
ptr tc = get_thread_context();
if (tc == (ptr)0) { /* thread created by someone else */
ptr thread;
/* borrow base thread to clone */
thread = S_create_thread_object("Sactivate_thread", TO_PTR(S_G.thread_context));
s_thread_setspecific(S_tc_key, TO_VOIDP(THREADTC(thread)));
return 1;
} else {
reactivate_thread(tc)
return 0;
}
}
int S_activate_thread() { /* Like Sactivate_thread(), but returns a mode to revert the effect */
ptr tc = get_thread_context();
if (tc == (ptr)0) {
Sactivate_thread();
return unactivate_mode_destroy;
} else if (!ACTIVE(tc)) {
reactivate_thread(tc);
return unactivate_mode_deactivate;
} else
return unactivate_mode_noop;
}
void S_unactivate_thread(int mode) { /* Reverts a previous S_activate_thread() effect */
switch (mode) {
case unactivate_mode_deactivate:
Sdeactivate_thread();
break;
case unactivate_mode_destroy:
Sdestroy_thread();
break;
case unactivate_mode_noop:
default:
break;
}
}
void Sdeactivate_thread() { /* deactivate current thread */
ptr tc = get_thread_context();
if (tc != (ptr)0) deactivate_thread(tc)
}
int Sdestroy_thread() { /* destroy current thread */
ptr tc = get_thread_context();
if (tc != (ptr)0 && destroy_thread(tc)) {
s_thread_setspecific(S_tc_key, 0);
return 1;
}
return 0;
}
static IBOOL destroy_thread(tc) ptr tc; {
ptr *ls; IBOOL status;
status = 0;
tc_mutex_acquire();
ls = &S_threads;
while (*ls != Snil) {
ptr thread = Scar(*ls);
if (THREADTC(thread) == (uptr)tc) {
*ls = Scdr(*ls);
S_nthreads -= 1;
alloc_mutex_acquire();
/* process remembered set before dropping allocation area */
S_scan_dirty((ptr *)EAP(tc), (ptr *)REAL_EAP(tc));
/* close off thread-local allocation */
S_thread_start_code_write(tc, static_generation, 0, NULL, 0);
{
ISPC s; IGEN g;
thread_gc *tgc = THREAD_GC(tc);
for (g = 0; g <= static_generation; g++)
for (s = 0; s <= max_real_space; s++)
if (tgc->next_loc[g][s])
S_close_off_thread_local_segment(tc, s, g);
}
S_thread_end_code_write(tc, static_generation, 0, NULL, 0);
alloc_mutex_release();
/* process guardian entries */
{
ptr target, ges, obj, next; seginfo *si;
target = S_G.guardians[0];
for (ges = GUARDIANENTRIES(tc); ges != Snil; ges = next) {
obj = GUARDIANOBJ(ges);
next = GUARDIANNEXT(ges);
if (!FIXMEDIATE(obj) && (si = MaybeSegInfo(ptr_get_segment(obj))) != NULL && si->generation != static_generation) {
INITGUARDIANNEXT(ges) = target;
target = ges;
}
}
S_G.guardians[0] = target;
}
/* deactivate thread */
if (ACTIVE(tc)) {
SETSYMVAL(S_G.active_threads_id,
FIX(UNFIX(SYMVAL(S_G.active_threads_id)) - 1));
if (Sboolean_value(SYMVAL(S_G.collect_request_pending_id))
&& SYMVAL(S_G.active_threads_id) == FIX(0)) {
s_thread_cond_signal(&S_collect_cond);
s_thread_cond_signal(&S_collect_thread0_cond);
}
}
if (LZ4OUTBUFFER(tc) != (ptr)0) free(TO_VOIDP(LZ4OUTBUFFER(tc)));
if (SIGNALINTERRUPTQUEUE(tc) != (ptr)0) free(TO_VOIDP(SIGNALINTERRUPTQUEUE(tc)));
if (THREAD_GC(tc)->preserve_ownership)
--S_num_preserve_ownership_threads;
/* Never free a thread_gc, since it may be recorded in a segment
as the segment's creator. Recycle manually, instead. */
THREAD_GC(tc)->sweeper = main_sweeper_index;
THREAD_GC(tc)->tc = (ptr)0;
THREAD_GC(tc)->next = free_thread_gcs;
free_thread_gcs = THREAD_GC(tc);
free((void *)tc);
THREADTC(thread) = 0; /* mark it dead */
status = 1;
s_thread_cond_broadcast(&S_terminated_cond);
break;
}
ls = &Scdr(*ls);
}
tc_mutex_release();
return status;
}
ptr S_fork_thread(thunk) ptr thunk; {
ptr thread;
int status;
/* pass the current thread's context as the parent thread */
thread = S_create_thread_object("fork-thread", get_thread_context());
CP(THREADTC(thread)) = thunk;
if ((status = s_thread_create(start_thread, TO_VOIDP(THREADTC(thread)))) != 0) {
destroy_thread((ptr)THREADTC(thread));
S_error1("fork-thread", "failed: ~a", S_strerror(status));
}
return thread;
}
static s_thread_rv_t start_thread(p) void *p; {
ptr tc = (ptr)p; ptr cp;
s_thread_setspecific(S_tc_key, TO_VOIDP(tc));
cp = CP(tc);
CP(tc) = Svoid; /* should hold calling code object, which we don't have */
TRAP(tc) = (ptr)default_timer_ticks;
Scall0(cp);
/* caution: calling into Scheme may result into a collection, so we
can't access any Scheme objects, e.g., cp, after this point. But tc
is static, so we can access it. */
/* find and destroy our thread */
destroy_thread(tc);
s_thread_setspecific(S_tc_key, NULL);
s_thread_return;
}
scheme_mutex_t *S_make_mutex() {
scheme_mutex_t *m;
m = (scheme_mutex_t *)malloc(sizeof(scheme_mutex_t));
if (m == (scheme_mutex_t *)0)
S_error("make-mutex", "unable to malloc mutex");
s_thread_mutex_init(&m->pmutex);
m->owner = s_thread_self();
m->count = 0;
return m;
}
void S_mutex_free(m) scheme_mutex_t *m; {
s_thread_mutex_destroy(&m->pmutex);
free(m);
}
void S_mutex_acquire(scheme_mutex_t *m) NO_THREAD_SANITIZE {
s_thread_t self = s_thread_self();
iptr count;
INT status;
if ((count = m->count) > 0 && s_thread_equal(m->owner, self)) {
if (count == most_positive_fixnum)
S_error1("mutex-acquire", "recursion limit exceeded for ~s", TO_PTR(m));
m->count = count + 1;
return;
}
if ((status = s_thread_mutex_lock(&m->pmutex)) != 0)
S_error1("mutex-acquire", "failed: ~a", S_strerror(status));
m->owner = self;
m->count = 1;
}
INT S_mutex_tryacquire(scheme_mutex_t *m) NO_THREAD_SANITIZE {
s_thread_t self = s_thread_self();
iptr count;
INT status;
if ((count = m->count) > 0 && s_thread_equal(m->owner, self)) {
if (count == most_positive_fixnum)
S_error1("mutex-acquire", "recursion limit exceeded for ~s", TO_PTR(m));
m->count = count + 1;
return 0;
}
status = s_thread_mutex_trylock(&m->pmutex);
if (status == 0) {
m->owner = self;
m->count = 1;
} else if (status != EBUSY) {
S_error1("mutex-acquire", "failed: ~a", S_strerror(status));
}
return status;
}
IBOOL S_mutex_is_owner(scheme_mutex_t *m) NO_THREAD_SANITIZE {
s_thread_t self = s_thread_self();
return ((m->count > 0) && s_thread_equal(m->owner, self));
}
void S_mutex_release(scheme_mutex_t *m) NO_THREAD_SANITIZE {
s_thread_t self = s_thread_self();
iptr count;
INT status;
if ((count = m->count) == 0 || !s_thread_equal(m->owner, self))
S_error1("mutex-release", "thread does not own mutex ~s", TO_PTR(m));
if ((m->count = count - 1) == 0) {
m->owner = 0; /* needed for a memory model like ARM, for example */
if ((status = s_thread_mutex_unlock(&m->pmutex)) != 0)
S_error1("mutex-release", "failed: ~a", S_strerror(status));
}
}
s_thread_cond_t *S_make_condition() {
s_thread_cond_t *c;
c = (s_thread_cond_t *)malloc(sizeof(s_thread_cond_t));
if (c == (s_thread_cond_t *)0)
S_error("make-condition", "unable to malloc condition");
s_thread_cond_init(c);
return c;
}
void S_condition_free(c) s_thread_cond_t *c; {
s_thread_cond_destroy(c);
free(c);
}
#ifdef FEATURE_WINDOWS
static inline int s_thread_cond_timedwait(s_thread_cond_t *cond, s_thread_mutex_t *mutex, int typeno, I64 sec, long nsec) {
if (typeno == time_utc) {
struct timespec now;
S_gettime(time_utc, &now);
sec -= now.tv_sec;
nsec -= now.tv_nsec;
if (nsec < 0) {
sec -= 1;
nsec += 1000000000;
}
}
if (sec < 0) {
sec = 0;
nsec = 0;
}
if (SleepConditionVariableCS(cond, mutex, (DWORD)(sec*1000 + (nsec+500000)/1000000))) {
return 0;
} else if (GetLastError() == ERROR_TIMEOUT) {
return ETIMEDOUT;
} else {
return EINVAL;
}
}
#else /* FEATURE_WINDOWS */
static inline int s_thread_cond_timedwait(s_thread_cond_t *cond, s_thread_mutex_t *mutex, int typeno, I64 sec, long nsec) {
struct timespec t;
if (typeno == time_duration) {
struct timespec now;
S_gettime(time_utc, &now);
t.tv_sec = (time_t)(now.tv_sec + sec);
t.tv_nsec = now.tv_nsec + nsec;
if (t.tv_nsec >= 1000000000) {
t.tv_sec += 1;
t.tv_nsec -= 1000000000;
}
} else {
t.tv_sec = sec;
t.tv_nsec = nsec;
}
return pthread_cond_timedwait(cond, mutex, &t);
}
#endif /* FEATURE_WINDOWS */
#define Srecord_ref(x,i) (((ptr *)((uptr)(x)+record_data_disp))[i])
IBOOL S_condition_wait(c, m, t) s_thread_cond_t *c; scheme_mutex_t *m; ptr t; {
ptr tc = get_thread_context();
s_thread_t self = s_thread_self();
iptr count;
INT typeno;
I64 sec;
long nsec;
INT status;
IBOOL is_collect;
iptr collect_index = 0;
if ((count = m->count) == 0 || !s_thread_equal(m->owner, self))
S_error1("condition-wait", "thread does not own mutex ~s", TO_PTR(m));
if (count != 1)
S_error1("condition-wait", "mutex ~s is recursively locked", TO_PTR(m));
if (t != Sfalse) {
/* Keep in sync with ts record in s/date.ss */
typeno = Sinteger32_value(Srecord_ref(t,0));
sec = Sinteger64_value(Scar(Srecord_ref(t,1)));
nsec = Sinteger32_value(Scdr(Srecord_ref(t,1)));
} else {
typeno = 0;
sec = 0;
nsec = 0;
}
is_collect = (c == &S_collect_cond || c == &S_collect_thread0_cond);
if (is_collect) {
/* Remember the index where we record this tc, because a thread
might temporarily wait for collection, but then get woken
up (e.g., to make the main thread drive the collection) before
a collection actually happens. */
int i;
S_collect_waiting_threads++;
collect_index = maximum_parallel_collect_threads;
if (S_collect_waiting_threads <= maximum_parallel_collect_threads) {
/* look for an open slot in `S_collect_waiting_tcs` */
for (i = 0; i < maximum_parallel_collect_threads; i++) {
if (S_collect_waiting_tcs[i] == (ptr)0) {
collect_index = i;
S_collect_waiting_tcs[collect_index] = tc;
break;
}
}
}
}
if (is_collect || DISABLECOUNT(tc) == 0) {
deactivate_thread_signal_collect(tc, !is_collect)
}
m->count = 0;
status = (t == Sfalse) ? s_thread_cond_wait(c, &m->pmutex) :
s_thread_cond_timedwait(c, &m->pmutex, typeno, sec, nsec);
m->owner = self;
m->count = 1;
if (is_collect || DISABLECOUNT(tc) == 0) {
reactivate_thread(tc)
}
if (is_collect) {
--S_collect_waiting_threads;
if (collect_index < maximum_parallel_collect_threads)
S_collect_waiting_tcs[collect_index] = (ptr)0;
}
if (status == 0) {
return 1;
} else if (status == ETIMEDOUT) {
return 0;
} else {
S_error1("condition-wait", "failed: ~a", S_strerror(status));
return 0;
}
}
#endif /* PTHREADS */
|
490350.c | /***************************************************************************/
/* */
/* pfrgload.c */
/* */
/* FreeType PFR glyph loader (body). */
/* */
/* Copyright 2002, 2003, 2005, 2007, 2010, 2013 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#include "pfrgload.h"
#include "pfrsbit.h"
#include "pfrload.h" /* for macro definitions */
#include FT_INTERNAL_DEBUG_H
#include "pfrerror.h"
#undef FT_COMPONENT
#define FT_COMPONENT trace_pfr
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** PFR GLYPH BUILDER *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_LOCAL_DEF( void )
pfr_glyph_init( PFR_Glyph glyph,
FT_GlyphLoader loader )
{
FT_ZERO( glyph );
glyph->loader = loader;
glyph->path_begun = 0;
FT_GlyphLoader_Rewind( loader );
}
FT_LOCAL_DEF( void )
pfr_glyph_done( PFR_Glyph glyph )
{
FT_Memory memory = glyph->loader->memory;
FT_FREE( glyph->x_control );
glyph->y_control = NULL;
glyph->max_xy_control = 0;
#if 0
glyph->num_x_control = 0;
glyph->num_y_control = 0;
#endif
FT_FREE( glyph->subs );
glyph->max_subs = 0;
glyph->num_subs = 0;
glyph->loader = NULL;
glyph->path_begun = 0;
}
/* close current contour, if any */
static void
pfr_glyph_close_contour( PFR_Glyph glyph )
{
FT_GlyphLoader loader = glyph->loader;
FT_Outline* outline = &loader->current.outline;
FT_Int last, first;
if ( !glyph->path_begun )
return;
/* compute first and last point indices in current glyph outline */
last = outline->n_points - 1;
first = 0;
if ( outline->n_contours > 0 )
first = outline->contours[outline->n_contours - 1];
/* if the last point falls on the same location than the first one */
/* we need to delete it */
if ( last > first )
{
FT_Vector* p1 = outline->points + first;
FT_Vector* p2 = outline->points + last;
if ( p1->x == p2->x && p1->y == p2->y )
{
outline->n_points--;
last--;
}
}
/* don't add empty contours */
if ( last >= first )
outline->contours[outline->n_contours++] = (short)last;
glyph->path_begun = 0;
}
/* reset glyph to start the loading of a new glyph */
static void
pfr_glyph_start( PFR_Glyph glyph )
{
glyph->path_begun = 0;
}
static FT_Error
pfr_glyph_line_to( PFR_Glyph glyph,
FT_Vector* to )
{
FT_GlyphLoader loader = glyph->loader;
FT_Outline* outline = &loader->current.outline;
FT_Error error;
/* check that we have begun a new path */
if ( !glyph->path_begun )
{
error = FT_THROW( Invalid_Table );
FT_ERROR(( "pfr_glyph_line_to: invalid glyph data\n" ));
goto Exit;
}
error = FT_GLYPHLOADER_CHECK_POINTS( loader, 1, 0 );
if ( !error )
{
FT_UInt n = outline->n_points;
outline->points[n] = *to;
outline->tags [n] = FT_CURVE_TAG_ON;
outline->n_points++;
}
Exit:
return error;
}
static FT_Error
pfr_glyph_curve_to( PFR_Glyph glyph,
FT_Vector* control1,
FT_Vector* control2,
FT_Vector* to )
{
FT_GlyphLoader loader = glyph->loader;
FT_Outline* outline = &loader->current.outline;
FT_Error error;
/* check that we have begun a new path */
if ( !glyph->path_begun )
{
error = FT_THROW( Invalid_Table );
FT_ERROR(( "pfr_glyph_line_to: invalid glyph data\n" ));
goto Exit;
}
error = FT_GLYPHLOADER_CHECK_POINTS( loader, 3, 0 );
if ( !error )
{
FT_Vector* vec = outline->points + outline->n_points;
FT_Byte* tag = (FT_Byte*)outline->tags + outline->n_points;
vec[0] = *control1;
vec[1] = *control2;
vec[2] = *to;
tag[0] = FT_CURVE_TAG_CUBIC;
tag[1] = FT_CURVE_TAG_CUBIC;
tag[2] = FT_CURVE_TAG_ON;
outline->n_points = (FT_Short)( outline->n_points + 3 );
}
Exit:
return error;
}
static FT_Error
pfr_glyph_move_to( PFR_Glyph glyph,
FT_Vector* to )
{
FT_GlyphLoader loader = glyph->loader;
FT_Error error;
/* close current contour if any */
pfr_glyph_close_contour( glyph );
/* indicate that a new contour has started */
glyph->path_begun = 1;
/* check that there is space for a new contour and a new point */
error = FT_GLYPHLOADER_CHECK_POINTS( loader, 1, 1 );
if ( !error )
/* add new start point */
error = pfr_glyph_line_to( glyph, to );
return error;
}
static void
pfr_glyph_end( PFR_Glyph glyph )
{
/* close current contour if any */
pfr_glyph_close_contour( glyph );
/* merge the current glyph into the stack */
FT_GlyphLoader_Add( glyph->loader );
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** PFR GLYPH LOADER *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* load a simple glyph */
static FT_Error
pfr_glyph_load_simple( PFR_Glyph glyph,
FT_Byte* p,
FT_Byte* limit )
{
FT_Error error = FT_Err_Ok;
FT_Memory memory = glyph->loader->memory;
FT_UInt flags, x_count, y_count, i, count, mask;
FT_Int x;
PFR_CHECK( 1 );
flags = PFR_NEXT_BYTE( p );
/* test for composite glyphs */
if ( flags & PFR_GLYPH_IS_COMPOUND )
goto Failure;
x_count = 0;
y_count = 0;
if ( flags & PFR_GLYPH_1BYTE_XYCOUNT )
{
PFR_CHECK( 1 );
count = PFR_NEXT_BYTE( p );
x_count = count & 15;
y_count = count >> 4;
}
else
{
if ( flags & PFR_GLYPH_XCOUNT )
{
PFR_CHECK( 1 );
x_count = PFR_NEXT_BYTE( p );
}
if ( flags & PFR_GLYPH_YCOUNT )
{
PFR_CHECK( 1 );
y_count = PFR_NEXT_BYTE( p );
}
}
count = x_count + y_count;
/* re-allocate array when necessary */
if ( count > glyph->max_xy_control )
{
FT_UInt new_max = FT_PAD_CEIL( count, 8 );
if ( FT_RENEW_ARRAY( glyph->x_control,
glyph->max_xy_control,
new_max ) )
goto Exit;
glyph->max_xy_control = new_max;
}
glyph->y_control = glyph->x_control + x_count;
mask = 0;
x = 0;
for ( i = 0; i < count; i++ )
{
if ( ( i & 7 ) == 0 )
{
PFR_CHECK( 1 );
mask = PFR_NEXT_BYTE( p );
}
if ( mask & 1 )
{
PFR_CHECK( 2 );
x = PFR_NEXT_SHORT( p );
}
else
{
PFR_CHECK( 1 );
x += PFR_NEXT_BYTE( p );
}
glyph->x_control[i] = x;
mask >>= 1;
}
/* XXX: for now we ignore the secondary stroke and edge definitions */
/* since we don't want to support native PFR hinting */
/* */
if ( flags & PFR_GLYPH_EXTRA_ITEMS )
{
error = pfr_extra_items_skip( &p, limit );
if ( error )
goto Exit;
}
pfr_glyph_start( glyph );
/* now load a simple glyph */
{
FT_Vector pos[4];
FT_Vector* cur;
pos[0].x = pos[0].y = 0;
pos[3] = pos[0];
for (;;)
{
FT_UInt format, format_low, args_format = 0, args_count, n;
/***************************************************************/
/* read instruction */
/* */
PFR_CHECK( 1 );
format = PFR_NEXT_BYTE( p );
format_low = format & 15;
switch ( format >> 4 )
{
case 0: /* end glyph */
FT_TRACE6(( "- end glyph" ));
args_count = 0;
break;
case 1: /* general line operation */
FT_TRACE6(( "- general line" ));
goto Line1;
case 4: /* move to inside contour */
FT_TRACE6(( "- move to inside" ));
goto Line1;
case 5: /* move to outside contour */
FT_TRACE6(( "- move to outside" ));
Line1:
args_format = format_low;
args_count = 1;
break;
case 2: /* horizontal line to */
FT_TRACE6(( "- horizontal line to cx.%d", format_low ));
if ( format_low >= x_count )
goto Failure;
pos[0].x = glyph->x_control[format_low];
pos[0].y = pos[3].y;
pos[3] = pos[0];
args_count = 0;
break;
case 3: /* vertical line to */
FT_TRACE6(( "- vertical line to cy.%d", format_low ));
if ( format_low >= y_count )
goto Failure;
pos[0].x = pos[3].x;
pos[0].y = glyph->y_control[format_low];
pos[3] = pos[0];
args_count = 0;
break;
case 6: /* horizontal to vertical curve */
FT_TRACE6(( "- hv curve " ));
args_format = 0xB8E;
args_count = 3;
break;
case 7: /* vertical to horizontal curve */
FT_TRACE6(( "- vh curve" ));
args_format = 0xE2B;
args_count = 3;
break;
default: /* general curve to */
FT_TRACE6(( "- general curve" ));
args_count = 4;
args_format = format_low;
}
/***********************************************************/
/* now read arguments */
/* */
cur = pos;
for ( n = 0; n < args_count; n++ )
{
FT_UInt idx;
FT_Int delta;
/* read the X argument */
switch ( args_format & 3 )
{
case 0: /* 8-bit index */
PFR_CHECK( 1 );
idx = PFR_NEXT_BYTE( p );
if ( idx >= x_count )
goto Failure;
cur->x = glyph->x_control[idx];
FT_TRACE7(( " cx#%d", idx ));
break;
case 1: /* 16-bit value */
PFR_CHECK( 2 );
cur->x = PFR_NEXT_SHORT( p );
FT_TRACE7(( " x.%d", cur->x ));
break;
case 2: /* 8-bit delta */
PFR_CHECK( 1 );
delta = PFR_NEXT_INT8( p );
cur->x = pos[3].x + delta;
FT_TRACE7(( " dx.%d", delta ));
break;
default:
FT_TRACE7(( " |" ));
cur->x = pos[3].x;
}
/* read the Y argument */
switch ( ( args_format >> 2 ) & 3 )
{
case 0: /* 8-bit index */
PFR_CHECK( 1 );
idx = PFR_NEXT_BYTE( p );
if ( idx >= y_count )
goto Failure;
cur->y = glyph->y_control[idx];
FT_TRACE7(( " cy#%d", idx ));
break;
case 1: /* 16-bit absolute value */
PFR_CHECK( 2 );
cur->y = PFR_NEXT_SHORT( p );
FT_TRACE7(( " y.%d", cur->y ));
break;
case 2: /* 8-bit delta */
PFR_CHECK( 1 );
delta = PFR_NEXT_INT8( p );
cur->y = pos[3].y + delta;
FT_TRACE7(( " dy.%d", delta ));
break;
default:
FT_TRACE7(( " -" ));
cur->y = pos[3].y;
}
/* read the additional format flag for the general curve */
if ( n == 0 && args_count == 4 )
{
PFR_CHECK( 1 );
args_format = PFR_NEXT_BYTE( p );
args_count--;
}
else
args_format >>= 4;
/* save the previous point */
pos[3] = cur[0];
cur++;
}
FT_TRACE7(( "\n" ));
/***********************************************************/
/* finally, execute instruction */
/* */
switch ( format >> 4 )
{
case 0: /* end glyph => EXIT */
pfr_glyph_end( glyph );
goto Exit;
case 1: /* line operations */
case 2:
case 3:
error = pfr_glyph_line_to( glyph, pos );
goto Test_Error;
case 4: /* move to inside contour */
case 5: /* move to outside contour */
error = pfr_glyph_move_to( glyph, pos );
goto Test_Error;
default: /* curve operations */
error = pfr_glyph_curve_to( glyph, pos, pos + 1, pos + 2 );
Test_Error: /* test error condition */
if ( error )
goto Exit;
}
} /* for (;;) */
}
Exit:
return error;
Failure:
Too_Short:
error = FT_THROW( Invalid_Table );
FT_ERROR(( "pfr_glyph_load_simple: invalid glyph data\n" ));
goto Exit;
}
/* load a composite/compound glyph */
static FT_Error
pfr_glyph_load_compound( PFR_Glyph glyph,
FT_Byte* p,
FT_Byte* limit )
{
FT_Error error = FT_Err_Ok;
FT_GlyphLoader loader = glyph->loader;
FT_Memory memory = loader->memory;
PFR_SubGlyph subglyph;
FT_UInt flags, i, count, org_count;
FT_Int x_pos, y_pos;
PFR_CHECK( 1 );
flags = PFR_NEXT_BYTE( p );
/* test for composite glyphs */
if ( !( flags & PFR_GLYPH_IS_COMPOUND ) )
goto Failure;
count = flags & 0x3F;
/* ignore extra items when present */
/* */
if ( flags & PFR_GLYPH_EXTRA_ITEMS )
{
error = pfr_extra_items_skip( &p, limit );
if (error) goto Exit;
}
/* we can't rely on the FT_GlyphLoader to load sub-glyphs, because */
/* the PFR format is dumb, using direct file offsets to point to the */
/* sub-glyphs (instead of glyph indices). Sigh. */
/* */
/* For now, we load the list of sub-glyphs into a different array */
/* but this will prevent us from using the auto-hinter at its best */
/* quality. */
/* */
org_count = glyph->num_subs;
if ( org_count + count > glyph->max_subs )
{
FT_UInt new_max = ( org_count + count + 3 ) & (FT_UInt)-4;
/* we arbitrarily limit the number of subglyphs */
/* to avoid endless recursion */
if ( new_max > 64 )
{
error = FT_THROW( Invalid_Table );
FT_ERROR(( "pfr_glyph_load_compound:"
" too many compound glyphs components\n" ));
goto Exit;
}
if ( FT_RENEW_ARRAY( glyph->subs, glyph->max_subs, new_max ) )
goto Exit;
glyph->max_subs = new_max;
}
subglyph = glyph->subs + org_count;
for ( i = 0; i < count; i++, subglyph++ )
{
FT_UInt format;
x_pos = 0;
y_pos = 0;
PFR_CHECK( 1 );
format = PFR_NEXT_BYTE( p );
/* read scale when available */
subglyph->x_scale = 0x10000L;
if ( format & PFR_SUBGLYPH_XSCALE )
{
PFR_CHECK( 2 );
subglyph->x_scale = PFR_NEXT_SHORT( p ) << 4;
}
subglyph->y_scale = 0x10000L;
if ( format & PFR_SUBGLYPH_YSCALE )
{
PFR_CHECK( 2 );
subglyph->y_scale = PFR_NEXT_SHORT( p ) << 4;
}
/* read offset */
switch ( format & 3 )
{
case 1:
PFR_CHECK( 2 );
x_pos = PFR_NEXT_SHORT( p );
break;
case 2:
PFR_CHECK( 1 );
x_pos += PFR_NEXT_INT8( p );
break;
default:
;
}
switch ( ( format >> 2 ) & 3 )
{
case 1:
PFR_CHECK( 2 );
y_pos = PFR_NEXT_SHORT( p );
break;
case 2:
PFR_CHECK( 1 );
y_pos += PFR_NEXT_INT8( p );
break;
default:
;
}
subglyph->x_delta = x_pos;
subglyph->y_delta = y_pos;
/* read glyph position and size now */
if ( format & PFR_SUBGLYPH_2BYTE_SIZE )
{
PFR_CHECK( 2 );
subglyph->gps_size = PFR_NEXT_USHORT( p );
}
else
{
PFR_CHECK( 1 );
subglyph->gps_size = PFR_NEXT_BYTE( p );
}
if ( format & PFR_SUBGLYPH_3BYTE_OFFSET )
{
PFR_CHECK( 3 );
subglyph->gps_offset = PFR_NEXT_LONG( p );
}
else
{
PFR_CHECK( 2 );
subglyph->gps_offset = PFR_NEXT_USHORT( p );
}
glyph->num_subs++;
}
Exit:
return error;
Failure:
Too_Short:
error = FT_THROW( Invalid_Table );
FT_ERROR(( "pfr_glyph_load_compound: invalid glyph data\n" ));
goto Exit;
}
static FT_Error
pfr_glyph_load_rec( PFR_Glyph glyph,
FT_Stream stream,
FT_ULong gps_offset,
FT_ULong offset,
FT_ULong size )
{
FT_Error error;
FT_Byte* p;
FT_Byte* limit;
if ( FT_STREAM_SEEK( gps_offset + offset ) ||
FT_FRAME_ENTER( size ) )
goto Exit;
p = (FT_Byte*)stream->cursor;
limit = p + size;
if ( size > 0 && *p & PFR_GLYPH_IS_COMPOUND )
{
FT_Int n, old_count, count;
FT_GlyphLoader loader = glyph->loader;
FT_Outline* base = &loader->base.outline;
old_count = glyph->num_subs;
/* this is a compound glyph - load it */
error = pfr_glyph_load_compound( glyph, p, limit );
FT_FRAME_EXIT();
if ( error )
goto Exit;
count = glyph->num_subs - old_count;
FT_TRACE4(( "compound glyph with %d elements (offset %lu):\n",
count, offset ));
/* now, load each individual glyph */
for ( n = 0; n < count; n++ )
{
FT_Int i, old_points, num_points;
PFR_SubGlyph subglyph;
FT_TRACE4(( " subglyph %d:\n", n ));
subglyph = glyph->subs + old_count + n;
old_points = base->n_points;
error = pfr_glyph_load_rec( glyph, stream, gps_offset,
subglyph->gps_offset,
subglyph->gps_size );
if ( error )
break;
/* note that `glyph->subs' might have been re-allocated */
subglyph = glyph->subs + old_count + n;
num_points = base->n_points - old_points;
/* translate and eventually scale the new glyph points */
if ( subglyph->x_scale != 0x10000L || subglyph->y_scale != 0x10000L )
{
FT_Vector* vec = base->points + old_points;
for ( i = 0; i < num_points; i++, vec++ )
{
vec->x = FT_MulFix( vec->x, subglyph->x_scale ) +
subglyph->x_delta;
vec->y = FT_MulFix( vec->y, subglyph->y_scale ) +
subglyph->y_delta;
}
}
else
{
FT_Vector* vec = loader->base.outline.points + old_points;
for ( i = 0; i < num_points; i++, vec++ )
{
vec->x += subglyph->x_delta;
vec->y += subglyph->y_delta;
}
}
/* proceed to next sub-glyph */
}
FT_TRACE4(( "end compound glyph with %d elements\n", count ));
}
else
{
FT_TRACE4(( "simple glyph (offset %lu)\n", offset ));
/* load a simple glyph */
error = pfr_glyph_load_simple( glyph, p, limit );
FT_FRAME_EXIT();
}
Exit:
return error;
}
FT_LOCAL_DEF( FT_Error )
pfr_glyph_load( PFR_Glyph glyph,
FT_Stream stream,
FT_ULong gps_offset,
FT_ULong offset,
FT_ULong size )
{
/* initialize glyph loader */
FT_GlyphLoader_Rewind( glyph->loader );
glyph->num_subs = 0;
/* load the glyph, recursively when needed */
return pfr_glyph_load_rec( glyph, stream, gps_offset, offset, size );
}
/* END */
|
86917.c | void load(int to[2],int from[2]) {
to[0]=from[0];
to[1]=from[1];
}
void store(int to[2],int from[2]) {
to[0]=from[0];
to[1]=from[1];
}
|
29155.c | /*
* Copyright (c) 1996-2001 Lucent Technologies.
* See README file for details.
*/
#include "local.h"
int lf_maxit = 20;
int lf_debug = 0;
static double s0, s1, tol;
static lfdata *lf_lfd;
static design *lf_des;
static smpar *lf_sp;
int lf_status;
int ident=0;
int (*like)();
extern double robscale;
void lfdata_init(lfd)
lfdata *lfd;
{ int i;
for (i=0; i<MXDIM; i++)
{ lfd->sty[i] = 0;
lfd->sca[i] = 1.0;
lfd->xl[i] = lfd->xl[i+MXDIM] = 0.0;
}
lfd->y = lfd->w = lfd->c = lfd->b = NULL;
lfd->d = lfd->n = 0;
}
void smpar_init(sp,lfd)
smpar *sp;
lfdata *lfd;
{ nn(sp) = 0.7;
fixh(sp)= 0.0;
pen(sp) = 0.0;
acri(sp)= ANONE;
deg(sp) = deg0(sp) = 2;
ubas(sp) = 0;
kt(sp) = KSPH;
ker(sp) = WTCUB;
fam(sp) = 64+TGAUS;
link(sp)= LDEFAU;
npar(sp) = calcp(sp,lfd->d);
}
void deriv_init(dv)
deriv *dv;
{ dv->nd = 0;
}
int des_reqd(n,p)
int n, p;
{
return(n*(p+5)+2*p*p+4*p + jac_reqd(p));
}
int des_reqi(n,p)
int n, p;
{ return(n+p);
}
void des_init(des,n,p)
design *des;
int n, p;
{ double *z;
int k;
if (n<=0) WARN(("des_init: n <= 0"));
if (p<=0) WARN(("des_init: p <= 0"));
if (des->des_init_id != DES_INIT_ID)
{ des->lwk = des->lind = 0;
des->des_init_id = DES_INIT_ID;
}
k = des_reqd(n,p);
if (k>des->lwk)
{ des->wk = (double *)calloc(k,sizeof(double));
des->lwk = k;
}
z = des->wk;
des->X = z; z += n*p;
des->w = z; z += n;
des->res=z; z += n;
des->di =z; z += n;
des->th =z; z += n;
des->wd =z; z += n;
des->V =z; z += p*p;
des->P =z; z += p*p;
des->f1 =z; z += p;
des->ss =z; z += p;
des->oc =z; z += p;
des->cf =z; z += p;
z = jac_alloc(&des->xtwx,p,z);
k = des_reqi(n,p);
if (k>des->lind)
{
des->ind = (Sint *)calloc(k,sizeof(Sint));
des->lind = k;
}
des->fix = &des->ind[n];
for (k=0; k<p; k++) des->fix[k] = 0;
des->n = n; des->p = p;
des->smwt = n;
des->xtwx.p = p;
}
void deschk(des,n,p)
design *des;
int n, p;
{ WARN(("deschk deprecated - use des_init()"));
des_init(des,n,p);
}
int likereg(coef, lk0, f1, Z)
double *coef, *lk0, *f1, *Z;
{ int i, ii, j, p;
double lk, ww, link[LLEN], *X;
if (lf_debug>2) printf(" likereg: %8.5f\n",coef[0]);
lf_status = LF_OK;
lk = 0.0; p = lf_des->p;
setzero(Z,p*p);
setzero(f1,p);
for (i=0; i<lf_des->n; i++)
{
ii = lf_des->ind[i];
X = d_xi(lf_des,i);
lf_des->th[i] = base(lf_lfd,ii)+innerprod(coef,X,p);
lf_status = stdlinks(link,lf_lfd,lf_sp,ii,lf_des->th[i],robscale);
if (lf_status == LF_BADP)
{ *lk0 = -1.0e300;
return(NR_REDUCE);
}
if (lf_error) lf_status = LF_ERR;
if (lf_status != LF_OK) return(NR_BREAK);
ww = lf_des->w[i];
lk += ww*link[ZLIK];
for (j=0; j<p; j++)
f1[j] += X[j]*ww*link[ZDLL];
addouter(Z, X, X, p, ww*link[ZDDLL]);
}
for (i=0; i<p; i++) if (lf_des->fix[i])
{ for (j=0; j<p; j++) Z[i*p+j] = Z[j*p+i] = 0.0;
Z[i*p+i] = 1.0;
f1[i] = 0.0;
}
if (lf_debug>4) prresp(coef,Z,p);
if (lf_debug>3) printf(" likelihood: %8.5f\n",lk);
*lk0 = lf_des->llk = lk;
switch (fam(lf_sp)&63) /* parameter checks */
{ case TGAUS: /* prevent iterations! */
if ((link(lf_sp)==LIDENT)&((fam(lf_sp)&128)==0)) return(NR_BREAK);
break;
case TPOIS:
case TGEOM:
case TWEIB:
case TGAMM:
if ((link(lf_sp)==LLOG) && (fabs(coef[0])>700))
{ lf_status = LF_OOB;
return(NR_REDUCE);
}
if (lk > -1.0e-5*s0)
{ lf_status = LF_PF;
return(NR_REDUCE);
}
break;
case TRBIN:
case TLOGT:
if (lk > -1.0e-5*s0)
{ lf_status = LF_PF;
return(NR_REDUCE);
}
if (fabs(coef[0])>700)
{ lf_status = LF_OOB;
return(NR_REDUCE);
}
break;
}
return(NR_OK);
}
int robustinit(lfd,des)
lfdata *lfd;
design *des;
{ int i;
for (i=0; i<des->n; i++)
des->res[i] = resp(lfd,(int)des->ind[i]) - base(lfd,(int)des->ind[i]);
des->cf[0] = median(des->res,des->n);
for (i=1; i<des->p; i++) des->cf[i] = 0.0;
tol = 1.0e-6;
return(LF_OK);
}
int circinit(lfd,des)
lfdata *lfd;
design *des;
{ int i, ii;
double s0, s1;
s0 = s1 = 0.0;
for (i=0; i<des->n; i++)
{ ii = des->ind[i];
s0 += des->w[i]*prwt(lfd,ii)*sin(resp(lfd,ii)-base(lfd,ii));
s1 += des->w[i]*prwt(lfd,ii)*cos(resp(lfd,ii)-base(lfd,ii));
}
des->cf[0] = atan2(s0,s1);
for (i=1; i<des->p; i++) des->cf[i] = 0.0;
tol = 1.0e-6;
return(LF_OK);
}
int reginit(lfd,des)
lfdata *lfd;
design *des;
{ int i, ii;
double sb, link[LLEN];
s0 = s1 = sb = 0;
for (i=0; i<des->n; i++)
{ ii = des->ind[i];
links(base(lfd,ii),resp(lfd,ii),fam(lf_sp),LINIT,link,cens(lfd,ii),prwt(lfd,ii),1.0);
s1 += des->w[i]*link[ZDLL];
s0 += des->w[i]*prwt(lfd,ii);
sb += des->w[i]*prwt(lfd,ii)*base(lfd,ii);
}
if (s0==0) return(LF_NOPT); /* no observations with W>0 */
setzero(des->cf,des->p);
tol = 1.0e-6*s0;
switch(link(lf_sp))
{ case LIDENT:
des->cf[0] = (s1-sb)/s0;
return(LF_OK);
case LLOG:
if (s1<=0.0)
{ des->cf[0] = -1000;
return(LF_INFA);
}
des->cf[0] = log(s1/s0) - sb/s0;
return(LF_OK);
case LLOGIT:
if (s1<=0.0)
{ des->cf[0] = -1000;
return(LF_INFA);
}
if (s1>=s0)
{ des->cf[0] = 1000;
return(LF_INFA);
}
des->cf[0] = logit(s1/s0)-sb/s0;
return(LF_OK);
case LINVER:
if (s1<=0.0)
{ des->cf[0] = 1000;
return(LF_INFA);
}
des->cf[0] = s0/s1-sb/s0;
return(LF_OK);
case LSQRT:
des->cf[0] = sqrt(s1/s0)-sb/s0;
return(LF_OK);
case LASIN:
des->cf[0] = asin(sqrt(s1/s0))-sb/s0;
return(LF_OK);
default:
ERROR(("reginit: invalid link %d",link(lf_sp)));
return(LF_ERR);
}
}
int lfinit(lfd,sp,des)
lfdata *lfd;
smpar *sp;
design *des;
{
des->xtwx.sm = (deg0(sp)<deg(sp)) ? JAC_CHOL : JAC_EIGD;
designmatrix(lfd,sp,des);
like = likereg;
link(sp) = defaultlink(link(sp),fam(sp));
switch(fam(sp)&63)
{ case TDEN:
case TRAT:
case THAZ:
like = likeden;
tol = (link(sp)==LLOG) ? 1.0e-6 : 0.0;
return(densinit(lfd,des,sp,des->cf));
case TCAUC:
case TROBT:
return(robustinit(lfd,des));
case TCIRC:
return(circinit(lfd,des));
default:
return(reginit(lfd,des));
}
}
void lfiter(des,maxit)
design *des;
int maxit;
{ int err;
if (lf_debug>1) printf(" lfiter: %8.5f\n",des->cf[0]);
max_nr(like, des->cf, des->oc, des->res, des->f1,
&des->xtwx, des->p, maxit, tol, &err);
switch(err)
{ case NR_OK: return;
case NR_NCON:
WARN(("max_nr not converged"));
return;
case NR_NDIV:
WARN(("max_nr reduction problem"));
return;
}
WARN(("max_nr return status %d",err));
}
int use_robust_scale(int tg)
{ if ((tg&64)==0) return(0); /* not quasi - no scale */
if (((tg&128)==0) & (((tg&63)!=TROBT) & ((tg&63)!=TCAUC))) return(0);
return(1);
}
int locfit(lfd,des,sp,noit,nb,cv)
lfdata *lfd;
design *des;
smpar *sp;
int noit, nb, cv;
{ int i;
if (des->xev==NULL)
{ ERROR(("locfit: NULL evaluation point?"));
return(246);
}
if (lf_debug>0)
{ printf("locfit: ");
for (i=0; i<lfd->d; i++) printf(" %10.6f",des->xev[i]);
printf("\n");
}
lf_des = des;
lf_lfd = lfd;
lf_sp = sp;
/* the 1e-12 avoids problems that can occur with roundoff */
if (nb) nbhd(lfd,des,(int)(lfd->n*nn(sp)+1e-12),0,sp);
lf_status = lfinit(lfd,sp,des);
if (lf_status != LF_OK) return(lf_status);
if (use_robust_scale(fam(sp)))
lf_robust(lfd,sp,des,lf_maxit);
else
{ robscale = 1.0;
lfiter(des,lf_maxit);
}
if (lf_status == LF_OOB) setzero(des->cf,des->p);
if ((fam(sp)&63)==TDEN) /* convert from rate to density */
{ switch(link(sp))
{ case LLOG:
des->cf[0] -= log(des->smwt);
break;
case LIDENT:
multmatscal(des->cf,1.0/des->smwt,des->p);
break;
default: ERROR(("Density adjustment; invalid link"));
}
}
/* variance calculations, if requested */
if (cv)
lf_vcov(lfd,sp,des);
return(lf_status);
}
|
276168.c | /*-------------------------------------------------------------------------
*
* lwlock.c
* Lightweight lock manager
*
* Lightweight locks are intended primarily to provide mutual exclusion of
* access to shared-memory data structures. Therefore, they offer both
* exclusive and shared lock modes (to support read/write and read-only
* access to a shared object). There are few other frammishes. User-level
* locking should be done with the full lock manager --- which depends on
* LWLocks to protect its shared state.
*
* In addition to exclusive and shared modes, lightweight locks can be used to
* wait until a variable changes value. The variable is initially not set
* when the lock is acquired with LWLockAcquire, i.e. it remains set to the
* value it was set to when the lock was released last, and can be updated
* without releasing the lock by calling LWLockUpdateVar. LWLockWaitForVar
* waits for the variable to be updated, or until the lock is free. When
* releasing the lock with LWLockReleaseClearVar() the value can be set to an
* appropriate value for a free lock. The meaning of the variable is up to
* the caller, the lightweight lock code just assigns and compares it.
*
* Portions Copyright (c) 1996-2018, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* IDENTIFICATION
* src/backend/storage/lmgr/lwlock.c
*
* NOTES:
*
* This used to be a pretty straight forward reader-writer lock
* implementation, in which the internal state was protected by a
* spinlock. Unfortunately the overhead of taking the spinlock proved to be
* too high for workloads/locks that were taken in shared mode very
* frequently. Often we were spinning in the (obviously exclusive) spinlock,
* while trying to acquire a shared lock that was actually free.
*
* Thus a new implementation was devised that provides wait-free shared lock
* acquisition for locks that aren't exclusively locked.
*
* The basic idea is to have a single atomic variable 'lockcount' instead of
* the formerly separate shared and exclusive counters and to use atomic
* operations to acquire the lock. That's fairly easy to do for plain
* rw-spinlocks, but a lot harder for something like LWLocks that want to wait
* in the OS.
*
* For lock acquisition we use an atomic compare-and-exchange on the lockcount
* variable. For exclusive lock we swap in a sentinel value
* (LW_VAL_EXCLUSIVE), for shared locks we count the number of holders.
*
* To release the lock we use an atomic decrement to release the lock. If the
* new value is zero (we get that atomically), we know we can/have to release
* waiters.
*
* Obviously it is important that the sentinel value for exclusive locks
* doesn't conflict with the maximum number of possible share lockers -
* luckily MAX_BACKENDS makes that easily possible.
*
*
* The attentive reader might have noticed that naively doing the above has a
* glaring race condition: We try to lock using the atomic operations and
* notice that we have to wait. Unfortunately by the time we have finished
* queuing, the former locker very well might have already finished it's
* work. That's problematic because we're now stuck waiting inside the OS.
* To mitigate those races we use a two phased attempt at locking:
* Phase 1: Try to do it atomically, if we succeed, nice
* Phase 2: Add ourselves to the waitqueue of the lock
* Phase 3: Try to grab the lock again, if we succeed, remove ourselves from
* the queue
* Phase 4: Sleep till wake-up, goto Phase 1
*
* This protects us against the problem from above as nobody can release too
* quick, before we're queued, since after Phase 2 we're already queued.
* -------------------------------------------------------------------------
*/
#include "postgres.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "pg_trace.h"
#include "postmaster/postmaster.h"
#include "replication/slot.h"
#include "storage/ipc.h"
#include "storage/predicate.h"
#include "storage/proc.h"
#include "storage/proclist.h"
#include "storage/spin.h"
#include "utils/memutils.h"
#ifdef LWLOCK_STATS
#include "utils/hsearch.h"
#endif
/* POLAR */
#include "storage/polar_lock_stats.h"
#include "utils/guc.h"
/* POLAR end */
/* We use the ShmemLock spinlock to protect LWLockCounter */
extern slock_t *ShmemLock;
#define LW_FLAG_HAS_WAITERS ((uint32) 1 << 30)
#define LW_FLAG_RELEASE_OK ((uint32) 1 << 29)
#define LW_FLAG_LOCKED ((uint32) 1 << 28)
#define LW_VAL_EXCLUSIVE ((uint32) 1 << 24)
#define LW_VAL_SHARED 1
#define LW_LOCK_MASK ((uint32) ((1 << 25)-1))
/* Must be greater than MAX_BACKENDS - which is 2^23-1, so we're fine. */
#define LW_SHARED_MASK ((uint32) ((1 << 24)-1))
/*
* This is indexed by tranche ID and stores the names of all tranches known
* to the current backend.
*/
static const char **LWLockTrancheArray = NULL;
static int LWLockTranchesAllocated = 0;
#define T_NAME(lock) \
(LWLockTrancheArray[(lock)->tranche])
/*
* This points to the main array of LWLocks in shared memory. Backends inherit
* the pointer by fork from the postmaster (except in the EXEC_BACKEND case,
* where we have special measures to pass it down).
*/
LWLockPadded *MainLWLockArray = NULL;
LWLockPadded *SysLoggerWriterLWLockArray = NULL;
/*
* We use this structure to keep track of locked LWLocks for release
* during error recovery. Normally, only a few will be held at once, but
* occasionally the number can be much higher; for example, the pg_buffercache
* extension locks all buffer partitions simultaneously.
*/
#define MAX_SIMUL_LWLOCKS 200
/* struct representing the LWLocks we're holding */
typedef struct LWLockHandle
{
LWLock *lock;
LWLockMode mode;
} LWLockHandle;
static int num_held_lwlocks = 0;
static LWLockHandle held_lwlocks[MAX_SIMUL_LWLOCKS];
/* struct representing the LWLock tranche request for named tranche */
typedef struct NamedLWLockTrancheRequest
{
char tranche_name[NAMEDATALEN];
int num_lwlocks;
} NamedLWLockTrancheRequest;
NamedLWLockTrancheRequest *NamedLWLockTrancheRequestArray = NULL;
static int NamedLWLockTrancheRequestsAllocated = 0;
int NamedLWLockTrancheRequests = 0;
NamedLWLockTranche *NamedLWLockTrancheArray = NULL;
static bool lock_named_request_allowed = true;
static void InitializeLWLocks(void);
static void RegisterLWLockTranches(void);
static inline void LWLockReportWaitStart(LWLock *lock);
static inline void LWLockReportWaitEnd(void);
#ifdef LWLOCK_STATS
typedef struct lwlock_stats_key
{
int tranche;
void *instance;
} lwlock_stats_key;
typedef struct lwlock_stats
{
lwlock_stats_key key;
int sh_acquire_count;
int ex_acquire_count;
int block_count;
int dequeue_self_count;
int spin_delay_count;
} lwlock_stats;
static HTAB *lwlock_stats_htab;
static lwlock_stats lwlock_stats_dummy;
#endif
#ifdef LWLOCK_DEBUG
bool Trace_lwlocks = false;
inline static void
PRINT_LWDEBUG(const char *where, LWLock *lock, LWLockMode mode)
{
/* hide statement & context here, otherwise the log is just too verbose */
if (Trace_lwlocks)
{
uint32 state = pg_atomic_read_u32(&lock->state);
ereport(LOG,
(errhidestmt(true),
errhidecontext(true),
errmsg_internal("%d: %s(%s %p): excl %u shared %u haswaiters %u waiters %u rOK %d",
MyProcPid,
where, T_NAME(lock), lock,
(state & LW_VAL_EXCLUSIVE) != 0,
state & LW_SHARED_MASK,
(state & LW_FLAG_HAS_WAITERS) != 0,
pg_atomic_read_u32(&lock->nwaiters),
(state & LW_FLAG_RELEASE_OK) != 0)));
}
}
inline static void
LOG_LWDEBUG(const char *where, LWLock *lock, const char *msg)
{
/* hide statement & context here, otherwise the log is just too verbose */
if (Trace_lwlocks)
{
ereport(LOG,
(errhidestmt(true),
errhidecontext(true),
errmsg_internal("%s(%s %p): %s", where,
T_NAME(lock), lock, msg)));
}
}
#else /* not LWLOCK_DEBUG */
#define PRINT_LWDEBUG(a,b,c) ((void)0)
#define LOG_LWDEBUG(a,b,c) ((void)0)
#endif /* LWLOCK_DEBUG */
#ifdef LWLOCK_STATS
static void init_lwlock_stats(void);
static void print_lwlock_stats(int code, Datum arg);
static lwlock_stats * get_lwlock_stats_entry(LWLock *lockid);
static void
init_lwlock_stats(void)
{
HASHCTL ctl;
static MemoryContext lwlock_stats_cxt = NULL;
static bool exit_registered = false;
if (lwlock_stats_cxt != NULL)
MemoryContextDelete(lwlock_stats_cxt);
/*
* The LWLock stats will be updated within a critical section, which
* requires allocating new hash entries. Allocations within a critical
* section are normally not allowed because running out of memory would
* lead to a PANIC, but LWLOCK_STATS is debugging code that's not normally
* turned on in production, so that's an acceptable risk. The hash entries
* are small, so the risk of running out of memory is minimal in practice.
*/
lwlock_stats_cxt = AllocSetContextCreate(TopMemoryContext,
"LWLock stats",
ALLOCSET_DEFAULT_SIZES);
MemoryContextAllowInCriticalSection(lwlock_stats_cxt, true);
MemSet(&ctl, 0, sizeof(ctl));
ctl.keysize = sizeof(lwlock_stats_key);
ctl.entrysize = sizeof(lwlock_stats);
ctl.hcxt = lwlock_stats_cxt;
lwlock_stats_htab = hash_create("lwlock stats", 16384, &ctl,
HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
if (!exit_registered)
{
on_shmem_exit(print_lwlock_stats, 0);
exit_registered = true;
}
}
static void
print_lwlock_stats(int code, Datum arg)
{
HASH_SEQ_STATUS scan;
lwlock_stats *lwstats;
hash_seq_init(&scan, lwlock_stats_htab);
/* Grab an LWLock to keep different backends from mixing reports */
LWLockAcquire(&MainLWLockArray[0].lock, LW_EXCLUSIVE);
while ((lwstats = (lwlock_stats *) hash_seq_search(&scan)) != NULL)
{
fprintf(stderr,
"PID %d lwlock %s %p: shacq %u exacq %u blk %u spindelay %u dequeue self %u\n",
MyProcPid, LWLockTrancheArray[lwstats->key.tranche],
lwstats->key.instance, lwstats->sh_acquire_count,
lwstats->ex_acquire_count, lwstats->block_count,
lwstats->spin_delay_count, lwstats->dequeue_self_count);
}
LWLockRelease(&MainLWLockArray[0].lock);
}
static lwlock_stats *
get_lwlock_stats_entry(LWLock *lock)
{
lwlock_stats_key key;
lwlock_stats *lwstats;
bool found;
/*
* During shared memory initialization, the hash table doesn't exist yet.
* Stats of that phase aren't very interesting, so just collect operations
* on all locks in a single dummy entry.
*/
if (lwlock_stats_htab == NULL)
return &lwlock_stats_dummy;
/* Fetch or create the entry. */
MemSet(&key, 0, sizeof(key));
key.tranche = lock->tranche;
key.instance = lock;
lwstats = hash_search(lwlock_stats_htab, &key, HASH_ENTER, &found);
if (!found)
{
lwstats->sh_acquire_count = 0;
lwstats->ex_acquire_count = 0;
lwstats->block_count = 0;
lwstats->dequeue_self_count = 0;
lwstats->spin_delay_count = 0;
}
return lwstats;
}
#endif /* LWLOCK_STATS */
/*
* Compute number of LWLocks required by named tranches. These will be
* allocated in the main array.
*/
static int
NumLWLocksByNamedTranches(void)
{
int numLocks = 0;
int i;
for (i = 0; i < NamedLWLockTrancheRequests; i++)
numLocks += NamedLWLockTrancheRequestArray[i].num_lwlocks;
return numLocks;
}
/*
* Compute shmem space needed for LWLocks and named tranches.
*/
Size
LWLockShmemSize(void)
{
Size size;
int i;
int numLocks = NUM_FIXED_LWLOCKS;
numLocks += NumLWLocksByNamedTranches();
/* Space for the LWLock array. */
size = mul_size(numLocks, sizeof(LWLockPadded));
/* Space for dynamic allocation counter, plus room for alignment. */
size = add_size(size, sizeof(int) + LWLOCK_PADDED_SIZE);
/* space for named tranches. */
size = add_size(size, mul_size(NamedLWLockTrancheRequests, sizeof(NamedLWLockTranche)));
/* space for name of each tranche. */
for (i = 0; i < NamedLWLockTrancheRequests; i++)
size = add_size(size, strlen(NamedLWLockTrancheRequestArray[i].tranche_name) + 1);
/* Disallow named LWLocks' requests after startup */
lock_named_request_allowed = false;
return size;
}
/*
* Allocate shmem space for the main LWLock array and all tranches and
* initialize it. We also register all the LWLock tranches here.
*/
void
CreateLWLocks(void)
{
StaticAssertStmt(LW_VAL_EXCLUSIVE > (uint32) MAX_BACKENDS,
"MAX_BACKENDS too big for lwlock.c");
StaticAssertStmt(sizeof(LWLock) <= LWLOCK_MINIMAL_SIZE &&
sizeof(LWLock) <= LWLOCK_PADDED_SIZE,
"Miscalculated LWLock padding");
if (!IsUnderPostmaster)
{
Size spaceLocks = LWLockShmemSize();
int *LWLockCounter;
char *ptr;
/* Allocate space */
ptr = (char *) ShmemAlloc(spaceLocks);
/* Leave room for dynamic allocation of tranches */
ptr += sizeof(int);
/* Ensure desired alignment of LWLock array */
ptr += LWLOCK_PADDED_SIZE - ((uintptr_t) ptr) % LWLOCK_PADDED_SIZE;
MainLWLockArray = (LWLockPadded *) ptr;
/*
* Initialize the dynamic-allocation counter for tranches, which is
* stored just before the first LWLock.
*/
LWLockCounter = (int *) ((char *) MainLWLockArray - sizeof(int));
*LWLockCounter = LWTRANCHE_FIRST_USER_DEFINED;
/* Initialize all LWLocks */
InitializeLWLocks();
}
/* Register all LWLock tranches */
RegisterLWLockTranches();
}
/*
* Initialize LWLocks that are fixed and those belonging to named tranches.
*/
static void
InitializeLWLocks(void)
{
int numNamedLocks = NumLWLocksByNamedTranches();
int id;
int i;
int j;
LWLockPadded *lock;
/* Initialize all individual LWLocks in main array */
for (id = 0, lock = MainLWLockArray; id < NUM_INDIVIDUAL_LWLOCKS; id++, lock++)
LWLockInitialize(&lock->lock, id);
/* Initialize buffer mapping LWLocks in main array */
lock = MainLWLockArray + NUM_INDIVIDUAL_LWLOCKS;
for (id = 0; id < NUM_BUFFER_PARTITIONS; id++, lock++)
LWLockInitialize(&lock->lock, LWTRANCHE_BUFFER_MAPPING);
/* Initialize lmgrs' LWLocks in main array */
lock = MainLWLockArray + NUM_INDIVIDUAL_LWLOCKS + NUM_BUFFER_PARTITIONS;
for (id = 0; id < NUM_LOCK_PARTITIONS; id++, lock++)
LWLockInitialize(&lock->lock, LWTRANCHE_LOCK_MANAGER);
/* Initialize predicate lmgrs' LWLocks in main array */
lock = MainLWLockArray + NUM_INDIVIDUAL_LWLOCKS +
NUM_BUFFER_PARTITIONS + NUM_LOCK_PARTITIONS;
for (id = 0; id < NUM_PREDICATELOCK_PARTITIONS; id++, lock++)
LWLockInitialize(&lock->lock, LWTRANCHE_PREDICATE_LOCK_MANAGER);
/* Initialize syslogger write LWLocks */
lock = MainLWLockArray + NUM_INDIVIDUAL_LWLOCKS +
NUM_BUFFER_PARTITIONS + NUM_LOCK_PARTITIONS + NUM_PREDICATELOCK_PARTITIONS;
for (id = 0; id < MAX_SYSLOGGER_LOCK_NUM; id++, lock++)
LWLockInitialize(&lock->lock, LWTRANCHE_SYSLOGGER_WRITER_MAPPING);
SysLoggerWriterLWLockArray = MainLWLockArray + NUM_INDIVIDUAL_LWLOCKS +
NUM_BUFFER_PARTITIONS + NUM_LOCK_PARTITIONS + NUM_PREDICATELOCK_PARTITIONS;
/* POLAR end */
lock = MainLWLockArray + NUM_INDIVIDUAL_LWLOCKS +
NUM_BUFFER_PARTITIONS + NUM_LOCK_PARTITIONS + NUM_PREDICATELOCK_PARTITIONS +
MAX_SYSLOGGER_LOCK_NUM;
for (id = 0; id < SR_PARTITIONS; id++, lock++)
LWLockInitialize(&lock->lock, LWTRANCHE_SR_LOCKS);
/* Initialize named tranches. */
if (NamedLWLockTrancheRequests > 0)
{
char *trancheNames;
NamedLWLockTrancheArray = (NamedLWLockTranche *)
&MainLWLockArray[NUM_FIXED_LWLOCKS + numNamedLocks];
trancheNames = (char *) NamedLWLockTrancheArray +
(NamedLWLockTrancheRequests * sizeof(NamedLWLockTranche));
lock = &MainLWLockArray[NUM_FIXED_LWLOCKS];
for (i = 0; i < NamedLWLockTrancheRequests; i++)
{
NamedLWLockTrancheRequest *request;
NamedLWLockTranche *tranche;
char *name;
request = &NamedLWLockTrancheRequestArray[i];
tranche = &NamedLWLockTrancheArray[i];
name = trancheNames;
trancheNames += strlen(request->tranche_name) + 1;
strcpy(name, request->tranche_name);
tranche->trancheId = LWLockNewTrancheId();
tranche->trancheName = name;
for (j = 0; j < request->num_lwlocks; j++, lock++)
LWLockInitialize(&lock->lock, tranche->trancheId);
}
}
}
/*
* Register named tranches and tranches for fixed LWLocks.
*/
static void
RegisterLWLockTranches(void)
{
int i;
if (LWLockTrancheArray == NULL)
{
LWLockTranchesAllocated = 128;
LWLockTrancheArray = (const char **)
MemoryContextAllocZero(TopMemoryContext,
LWLockTranchesAllocated * sizeof(char *));
Assert(LWLockTranchesAllocated >= LWTRANCHE_FIRST_USER_DEFINED);
}
for (i = 0; i < NUM_INDIVIDUAL_LWLOCKS; ++i)
LWLockRegisterTranche(i, MainLWLockNames[i]);
LWLockRegisterTranche(LWTRANCHE_BUFFER_MAPPING, "buffer_mapping");
/* POLAR: register syslog_write tranche */
LWLockRegisterTranche(LWTRANCHE_SYSLOGGER_WRITER_MAPPING, "syslog_write");
/* POLAR end */
LWLockRegisterTranche(LWTRANCHE_SR_LOCKS, "sr_locks");
LWLockRegisterTranche(LWTRANCHE_LOCK_MANAGER, "lock_manager");
LWLockRegisterTranche(LWTRANCHE_PREDICATE_LOCK_MANAGER,
"predicate_lock_manager");
LWLockRegisterTranche(LWTRANCHE_PARALLEL_QUERY_DSA,
"parallel_query_dsa");
LWLockRegisterTranche(LWTRANCHE_SESSION_DSA,
"session_dsa");
LWLockRegisterTranche(LWTRANCHE_SESSION_RECORD_TABLE,
"session_record_table");
LWLockRegisterTranche(LWTRANCHE_SESSION_TYPMOD_TABLE,
"session_typmod_table");
LWLockRegisterTranche(LWTRANCHE_SHARED_TUPLESTORE,
"shared_tuplestore");
LWLockRegisterTranche(LWTRANCHE_TBM, "tbm");
LWLockRegisterTranche(LWTRANCHE_PARALLEL_APPEND, "parallel_append");
LWLockRegisterTranche(LWTRANCHE_PARALLEL_HASH_JOIN, "parallel_hash_join");
/* Register named tranches. */
for (i = 0; i < NamedLWLockTrancheRequests; i++)
LWLockRegisterTranche(NamedLWLockTrancheArray[i].trancheId,
NamedLWLockTrancheArray[i].trancheName);
}
/*
* InitLWLockAccess - initialize backend-local state needed to hold LWLocks
*/
void
InitLWLockAccess(void)
{
#ifdef LWLOCK_STATS
init_lwlock_stats();
#endif
/* POLAR: init lwlock local stats */
polar_init_lwlock_local_stats();
/* POLAR end */
}
/*
* GetNamedLWLockTranche - returns the base address of LWLock from the
* specified tranche.
*
* Caller needs to retrieve the requested number of LWLocks starting from
* the base lock address returned by this API. This can be used for
* tranches that are requested by using RequestNamedLWLockTranche() API.
*/
LWLockPadded *
GetNamedLWLockTranche(const char *tranche_name)
{
int lock_pos;
int i;
/*
* Obtain the position of base address of LWLock belonging to requested
* tranche_name in MainLWLockArray. LWLocks for named tranches are placed
* in MainLWLockArray after fixed locks.
*/
lock_pos = NUM_FIXED_LWLOCKS;
for (i = 0; i < NamedLWLockTrancheRequests; i++)
{
if (strcmp(NamedLWLockTrancheRequestArray[i].tranche_name,
tranche_name) == 0)
return &MainLWLockArray[lock_pos];
lock_pos += NamedLWLockTrancheRequestArray[i].num_lwlocks;
}
if (i >= NamedLWLockTrancheRequests)
elog(ERROR, "requested tranche is not registered");
/* just to keep compiler quiet */
return NULL;
}
/*
* Allocate a new tranche ID.
*/
int
LWLockNewTrancheId(void)
{
int result;
int *LWLockCounter;
LWLockCounter = (int *) ((char *) MainLWLockArray - sizeof(int));
SpinLockAcquire(ShmemLock);
result = (*LWLockCounter)++;
SpinLockRelease(ShmemLock);
return result;
}
/*
* Register a tranche ID in the lookup table for the current process. This
* routine will save a pointer to the tranche name passed as an argument,
* so the name should be allocated in a backend-lifetime context
* (TopMemoryContext, static variable, or similar).
*/
void
LWLockRegisterTranche(int tranche_id, const char *tranche_name)
{
Assert(LWLockTrancheArray != NULL);
if (tranche_id >= LWLockTranchesAllocated)
{
int i = LWLockTranchesAllocated;
int j = LWLockTranchesAllocated;
while (i <= tranche_id)
i *= 2;
LWLockTrancheArray = (const char **)
repalloc(LWLockTrancheArray, i * sizeof(char *));
LWLockTranchesAllocated = i;
while (j < LWLockTranchesAllocated)
LWLockTrancheArray[j++] = NULL;
}
LWLockTrancheArray[tranche_id] = tranche_name;
}
/*
* RequestNamedLWLockTranche
* Request that extra LWLocks be allocated during postmaster
* startup.
*
* This is only useful for extensions if called from the _PG_init hook
* of a library that is loaded into the postmaster via
* shared_preload_libraries. Once shared memory has been allocated, calls
* will be ignored. (We could raise an error, but it seems better to make
* it a no-op, so that libraries containing such calls can be reloaded if
* needed.)
*/
void
RequestNamedLWLockTranche(const char *tranche_name, int num_lwlocks)
{
NamedLWLockTrancheRequest *request;
if (IsUnderPostmaster || !lock_named_request_allowed)
return; /* too late */
if (NamedLWLockTrancheRequestArray == NULL)
{
NamedLWLockTrancheRequestsAllocated = 16;
NamedLWLockTrancheRequestArray = (NamedLWLockTrancheRequest *)
MemoryContextAlloc(TopMemoryContext,
NamedLWLockTrancheRequestsAllocated
* sizeof(NamedLWLockTrancheRequest));
}
if (NamedLWLockTrancheRequests >= NamedLWLockTrancheRequestsAllocated)
{
int i = NamedLWLockTrancheRequestsAllocated;
while (i <= NamedLWLockTrancheRequests)
i *= 2;
NamedLWLockTrancheRequestArray = (NamedLWLockTrancheRequest *)
repalloc(NamedLWLockTrancheRequestArray,
i * sizeof(NamedLWLockTrancheRequest));
NamedLWLockTrancheRequestsAllocated = i;
}
request = &NamedLWLockTrancheRequestArray[NamedLWLockTrancheRequests];
Assert(strlen(tranche_name) + 1 < NAMEDATALEN);
StrNCpy(request->tranche_name, tranche_name, NAMEDATALEN);
request->num_lwlocks = num_lwlocks;
NamedLWLockTrancheRequests++;
}
/*
* LWLockInitialize - initialize a new lwlock; it's initially unlocked
*/
void
LWLockInitialize(LWLock *lock, int tranche_id)
{
pg_atomic_init_u32(&lock->state, LW_FLAG_RELEASE_OK);
pg_atomic_init_u32(&lock->nwaiters, 0);
pg_atomic_init_u32(&lock->x_pid, 0);
lock->tranche = tranche_id;
proclist_init(&lock->waiters);
}
/*
* Report start of wait event for light-weight locks.
*
* This function will be used by all the light-weight lock calls which
* needs to wait to acquire the lock. This function distinguishes wait
* event based on tranche and lock id.
*/
static inline void
LWLockReportWaitStart(LWLock *lock)
{
pgstat_report_wait_start(PG_WAIT_LWLOCK | lock->tranche);
}
/*
* Report end of wait event for light-weight locks.
*/
static inline void
LWLockReportWaitEnd(void)
{
pgstat_report_wait_end();
}
/*
* Return an identifier for an LWLock based on the wait class and event.
*/
const char *
GetLWLockIdentifier(uint32 classId, uint16 eventId)
{
Assert(classId == PG_WAIT_LWLOCK);
/*
* It is quite possible that user has registered tranche in one of the
* backends (e.g. by allocating lwlocks in dynamic shared memory) but not
* all of them, so we can't assume the tranche is registered here.
*/
if (eventId >= LWLockTranchesAllocated ||
LWLockTrancheArray[eventId] == NULL)
return "extension";
return LWLockTrancheArray[eventId];
}
/*
* Internal function that tries to atomically acquire the lwlock in the passed
* in mode.
*
* This function will not block waiting for a lock to become free - that's the
* callers job.
*
* Returns true if the lock isn't free and we need to wait.
*/
static bool
LWLockAttemptLock(LWLock *lock, LWLockMode mode)
{
uint32 old_state;
AssertArg(mode == LW_EXCLUSIVE || mode == LW_SHARED);
/*
* Read once outside the loop, later iterations will get the newer value
* via compare & exchange.
*/
old_state = pg_atomic_read_u32(&lock->state);
/* loop until we've determined whether we could acquire the lock or not */
while (true)
{
uint32 desired_state;
bool lock_free;
desired_state = old_state;
if (mode == LW_EXCLUSIVE)
{
lock_free = (old_state & LW_LOCK_MASK) == 0;
if (lock_free)
desired_state += LW_VAL_EXCLUSIVE;
}
else
{
lock_free = (old_state & LW_VAL_EXCLUSIVE) == 0;
if (lock_free)
desired_state += LW_VAL_SHARED;
}
/*
* Attempt to swap in the state we are expecting. If we didn't see
* lock to be free, that's just the old value. If we saw it as free,
* we'll attempt to mark it acquired. The reason that we always swap
* in the value is that this doubles as a memory barrier. We could try
* to be smarter and only swap in values if we saw the lock as free,
* but benchmark haven't shown it as beneficial so far.
*
* Retry if the value changed since we last looked at it.
*/
if (pg_atomic_compare_exchange_u32(&lock->state,
&old_state, desired_state))
{
if (lock_free)
{
/* Great! Got the lock. */
if (mode == LW_EXCLUSIVE)
{
#ifdef LWLOCK_DEBUG
lock->owner = MyProc;
#endif
/*
* POLAR: We only record the last exclusive lock.
*/
if (MyProc)
pg_atomic_write_u32(&lock->x_pid, MyProc->pid);
}
return false;
}
else
return true; /* somebody else has the lock */
}
}
pg_unreachable();
}
/*
* Lock the LWLock's wait list against concurrent activity.
*
* NB: even though the wait list is locked, non-conflicting lock operations
* may still happen concurrently.
*
* Time spent holding mutex should be short!
*/
static void
LWLockWaitListLock(LWLock *lock)
{
uint32 old_state;
#ifdef LWLOCK_STATS
lwlock_stats *lwstats;
uint32 delays = 0;
lwstats = get_lwlock_stats_entry(lock);
#endif
while (true)
{
/* always try once to acquire lock directly */
old_state = pg_atomic_fetch_or_u32(&lock->state, LW_FLAG_LOCKED);
if (!(old_state & LW_FLAG_LOCKED))
break; /* got lock */
/* and then spin without atomic operations until lock is released */
{
SpinDelayStatus delayStatus;
init_local_spin_delay(&delayStatus);
while (old_state & LW_FLAG_LOCKED)
{
perform_spin_delay(&delayStatus);
old_state = pg_atomic_read_u32(&lock->state);
}
#ifdef LWLOCK_STATS
delays += delayStatus.delays;
#endif
finish_spin_delay(&delayStatus);
}
/*
* Retry. The lock might obviously already be re-acquired by the time
* we're attempting to get it again.
*/
}
#ifdef LWLOCK_STATS
lwstats->spin_delay_count += delays;
#endif
}
/*
* Unlock the LWLock's wait list.
*
* Note that it can be more efficient to manipulate flags and release the
* locks in a single atomic operation.
*/
static void
LWLockWaitListUnlock(LWLock *lock)
{
uint32 old_state PG_USED_FOR_ASSERTS_ONLY;
old_state = pg_atomic_fetch_and_u32(&lock->state, ~LW_FLAG_LOCKED);
Assert(old_state & LW_FLAG_LOCKED);
}
/*
* Wakeup all the lockers that currently have a chance to acquire the lock.
*/
static void
LWLockWakeup(LWLock *lock)
{
bool new_release_ok;
bool wokeup_somebody = false;
proclist_head wakeup;
proclist_mutable_iter iter;
proclist_init(&wakeup);
new_release_ok = true;
/* lock wait list while collecting backends to wake up */
LWLockWaitListLock(lock);
proclist_foreach_modify(iter, &lock->waiters, lwWaitLink)
{
PGPROC *waiter = GetPGProcByNumber(iter.cur);
if (wokeup_somebody && waiter->lwWaitMode == LW_EXCLUSIVE)
continue;
proclist_delete(&lock->waiters, iter.cur, lwWaitLink);
proclist_push_tail(&wakeup, iter.cur, lwWaitLink);
if (waiter->lwWaitMode != LW_WAIT_UNTIL_FREE)
{
/*
* Prevent additional wakeups until retryer gets to run. Backends
* that are just waiting for the lock to become free don't retry
* automatically.
*/
new_release_ok = false;
/*
* Don't wakeup (further) exclusive locks.
*/
wokeup_somebody = true;
}
/*
* Once we've woken up an exclusive lock, there's no point in waking
* up anybody else.
*/
if (waiter->lwWaitMode == LW_EXCLUSIVE)
break;
}
Assert(proclist_is_empty(&wakeup) || pg_atomic_read_u32(&lock->state) & LW_FLAG_HAS_WAITERS);
/* unset required flags, and release lock, in one fell swoop */
{
uint32 old_state;
uint32 desired_state;
old_state = pg_atomic_read_u32(&lock->state);
while (true)
{
desired_state = old_state;
/* compute desired flags */
if (new_release_ok)
desired_state |= LW_FLAG_RELEASE_OK;
else
desired_state &= ~LW_FLAG_RELEASE_OK;
if (proclist_is_empty(&wakeup))
desired_state &= ~LW_FLAG_HAS_WAITERS;
desired_state &= ~LW_FLAG_LOCKED; /* release lock */
if (pg_atomic_compare_exchange_u32(&lock->state, &old_state,
desired_state))
break;
}
}
/* Awaken any waiters I removed from the queue. */
proclist_foreach_modify(iter, &wakeup, lwWaitLink)
{
PGPROC *waiter = GetPGProcByNumber(iter.cur);
LOG_LWDEBUG("LWLockRelease", lock, "release waiter");
proclist_delete(&wakeup, iter.cur, lwWaitLink);
/*
* Guarantee that lwWaiting being unset only becomes visible once the
* unlink from the link has completed. Otherwise the target backend
* could be woken up for other reason and enqueue for a new lock - if
* that happens before the list unlink happens, the list would end up
* being corrupted.
*
* The barrier pairs with the LWLockWaitListLock() when enqueuing for
* another lock.
*/
pg_write_barrier();
waiter->lwWaiting = false;
PGSemaphoreUnlock(waiter->sem);
}
}
/*
* Add ourselves to the end of the queue.
*
* NB: Mode can be LW_WAIT_UNTIL_FREE here!
*/
static void
LWLockQueueSelf(LWLock *lock, LWLockMode mode)
{
/*
* If we don't have a PGPROC structure, there's no way to wait. This
* should never occur, since MyProc should only be null during shared
* memory initialization.
*/
if (MyProc == NULL)
elog(PANIC, "cannot wait without a PGPROC structure");
if (MyProc->lwWaiting)
elog(PANIC, "queueing for lock while waiting on another one");
LWLockWaitListLock(lock);
/* setting the flag is protected by the spinlock */
pg_atomic_fetch_or_u32(&lock->state, LW_FLAG_HAS_WAITERS);
MyProc->lwWaiting = true;
MyProc->lwWaitMode = mode;
/* LW_WAIT_UNTIL_FREE waiters are always at the front of the queue */
if (mode == LW_WAIT_UNTIL_FREE)
proclist_push_head(&lock->waiters, MyProc->pgprocno, lwWaitLink);
else
proclist_push_tail(&lock->waiters, MyProc->pgprocno, lwWaitLink);
/* Can release the mutex now */
LWLockWaitListUnlock(lock);
pg_atomic_fetch_add_u32(&lock->nwaiters, 1);
}
/*
* Remove ourselves from the waitlist.
*
* This is used if we queued ourselves because we thought we needed to sleep
* but, after further checking, we discovered that we don't actually need to
* do so.
*/
static void
LWLockDequeueSelf(LWLock *lock)
{
bool found = false;
proclist_mutable_iter iter;
#ifdef LWLOCK_STATS
lwlock_stats *lwstats;
lwstats = get_lwlock_stats_entry(lock);
lwstats->dequeue_self_count++;
#endif
LWLockWaitListLock(lock);
/*
* Can't just remove ourselves from the list, but we need to iterate over
* all entries as somebody else could have dequeued us.
*/
proclist_foreach_modify(iter, &lock->waiters, lwWaitLink)
{
if (iter.cur == MyProc->pgprocno)
{
found = true;
proclist_delete(&lock->waiters, iter.cur, lwWaitLink);
break;
}
}
if (proclist_is_empty(&lock->waiters) &&
(pg_atomic_read_u32(&lock->state) & LW_FLAG_HAS_WAITERS) != 0)
{
pg_atomic_fetch_and_u32(&lock->state, ~LW_FLAG_HAS_WAITERS);
}
/* XXX: combine with fetch_and above? */
LWLockWaitListUnlock(lock);
/* clear waiting state again, nice for debugging */
if (found)
MyProc->lwWaiting = false;
else
{
int extraWaits = 0;
/*
* Somebody else dequeued us and has or will wake us up. Deal with the
* superfluous absorption of a wakeup.
*/
/*
* Reset releaseOk if somebody woke us before we removed ourselves -
* they'll have set it to false.
*/
pg_atomic_fetch_or_u32(&lock->state, LW_FLAG_RELEASE_OK);
/*
* Now wait for the scheduled wakeup, otherwise our ->lwWaiting would
* get reset at some inconvenient point later. Most of the time this
* will immediately return.
*/
for (;;)
{
PGSemaphoreLock(MyProc->sem);
if (!MyProc->lwWaiting)
break;
extraWaits++;
}
/*
* Fix the process wait semaphore's count for any absorbed wakeups.
*/
while (extraWaits-- > 0)
PGSemaphoreUnlock(MyProc->sem);
}
{
/* not waiting anymore */
uint32 nwaiters PG_USED_FOR_ASSERTS_ONLY = pg_atomic_fetch_sub_u32(&lock->nwaiters, 1);
Assert(nwaiters < MAX_BACKENDS);
}
}
/*
* LWLockAcquire - acquire a lightweight lock in the specified mode
*
* If the lock is not available, sleep until it is. Returns true if the lock
* was available immediately, false if we had to sleep.
*
* Side effect: cancel/die interrupts are held off until lock release.
*/
bool
LWLockAcquire(LWLock *lock, LWLockMode mode)
{
PGPROC *proc = MyProc;
bool result = true;
int extraWaits = 0;
/* POLAR: lock timing */
instr_time lwlock_wait_start;
bool is_blocking = false;
/* POLAR end */
#ifdef LWLOCK_STATS
lwlock_stats *lwstats;
lwstats = get_lwlock_stats_entry(lock);
#endif
/* POLAR: lock timing */
INSTR_TIME_SET_ZERO(lwlock_wait_start);
/* POLAR end */
AssertArg(mode == LW_SHARED || mode == LW_EXCLUSIVE);
PRINT_LWDEBUG("LWLockAcquire", lock, mode);
#ifdef LWLOCK_STATS
/* Count lock acquisition attempts */
if (mode == LW_EXCLUSIVE)
lwstats->ex_acquire_count++;
else
lwstats->sh_acquire_count++;
#endif /* LWLOCK_STATS */
/* POLAR: Count lock acquisition attempts */
polar_lwlock_stat_acquire(lock, mode);
/* POLAR end */
/*
* We can't wait if we haven't got a PGPROC. This should only occur
* during bootstrap or shared memory initialization. Put an Assert here
* to catch unsafe coding practices.
*/
Assert(!(proc == NULL && IsUnderPostmaster));
/* Ensure we will have room to remember the lock */
if (num_held_lwlocks >= MAX_SIMUL_LWLOCKS)
elog(ERROR, "too many LWLocks taken");
/*
* Lock out cancel/die interrupts until we exit the code section protected
* by the LWLock. This ensures that interrupts will not interfere with
* manipulations of data structures in shared memory.
*/
HOLD_INTERRUPTS();
/*
* Loop here to try to acquire lock after each time we are signaled by
* LWLockRelease.
*
* NOTE: it might seem better to have LWLockRelease actually grant us the
* lock, rather than retrying and possibly having to go back to sleep. But
* in practice that is no good because it means a process swap for every
* lock acquisition when two or more processes are contending for the same
* lock. Since LWLocks are normally used to protect not-very-long
* sections of computation, a process needs to be able to acquire and
* release the same lock many times during a single CPU time slice, even
* in the presence of contention. The efficiency of being able to do that
* outweighs the inefficiency of sometimes wasting a process dispatch
* cycle because the lock is not free when a released waiter finally gets
* to run. See pgsql-hackers archives for 29-Dec-01.
*/
for (;;)
{
bool mustwait;
/*
* Try to grab the lock the first time, we're not in the waitqueue
* yet/anymore.
*/
mustwait = LWLockAttemptLock(lock, mode);
if (!mustwait)
{
LOG_LWDEBUG("LWLockAcquire", lock, "immediately acquired lock");
break; /* got the lock */
}
/*
* Ok, at this point we couldn't grab the lock on the first try. We
* cannot simply queue ourselves to the end of the list and wait to be
* woken up because by now the lock could long have been released.
* Instead add us to the queue and try to grab the lock again. If we
* succeed we need to revert the queuing and be happy, otherwise we
* recheck the lock. If we still couldn't grab it, we know that the
* other locker will see our queue entries when releasing since they
* existed before we checked for the lock.
*/
/* add to the queue */
LWLockQueueSelf(lock, mode);
/* we're now guaranteed to be woken up if necessary */
mustwait = LWLockAttemptLock(lock, mode);
/* ok, grabbed the lock the second time round, need to undo queueing */
if (!mustwait)
{
LOG_LWDEBUG("LWLockAcquire", lock, "acquired, undoing queue");
LWLockDequeueSelf(lock);
break;
}
/*
* Wait until awakened.
*
* Since we share the process wait semaphore with the regular lock
* manager and ProcWaitForSignal, and we may need to acquire an LWLock
* while one of those is pending, it is possible that we get awakened
* for a reason other than being signaled by LWLockRelease. If so,
* loop back and wait again. Once we've gotten the LWLock,
* re-increment the sema by the number of additional signals received,
* so that the lock manager or signal manager will see the received
* signal when it next waits.
*/
LOG_LWDEBUG("LWLockAcquire", lock, "waiting");
#ifdef LWLOCK_STATS
lwstats->block_count++;
#endif
/* POLAR: track lock wait */
{
POLAR_LOCK_STATS_TIME_START(lwlock_wait_start);
if (!is_blocking)
polar_stat_wait_obj_and_time_set(pg_atomic_read_u32(&lock->x_pid), &lwlock_wait_start, PGPROC_WAIT_PID);
POLAR_LWLOCK_STAT_BLOCK(lock, is_blocking);
}
/* POLAR end */
LWLockReportWaitStart(lock);
TRACE_POSTGRESQL_LWLOCK_WAIT_START(T_NAME(lock), mode);
for (;;)
{
PGSemaphoreLock(proc->sem);
if (!proc->lwWaiting)
break;
extraWaits++;
}
/* Retrying, allow LWLockRelease to release waiters again. */
pg_atomic_fetch_or_u32(&lock->state, LW_FLAG_RELEASE_OK);
{
/* not waiting anymore */
uint32 nwaiters PG_USED_FOR_ASSERTS_ONLY = pg_atomic_fetch_sub_u32(&lock->nwaiters, 1);
Assert(nwaiters < MAX_BACKENDS);
}
TRACE_POSTGRESQL_LWLOCK_WAIT_DONE(T_NAME(lock), mode);
LWLockReportWaitEnd();
LOG_LWDEBUG("LWLockAcquire", lock, "awakened");
/* Now loop back and try to acquire lock again. */
result = false;
}
/* POLAR: track lock timing */
polar_lwlock_stat_record_time(lock, &lwlock_wait_start);
if (is_blocking)
polar_stat_wait_obj_and_time_clear();
/* POLAR end */
TRACE_POSTGRESQL_LWLOCK_ACQUIRE(T_NAME(lock), mode);
/* Add lock to list of locks held by this backend */
held_lwlocks[num_held_lwlocks].lock = lock;
held_lwlocks[num_held_lwlocks++].mode = mode;
/*
* Fix the process wait semaphore's count for any absorbed wakeups.
*/
while (extraWaits-- > 0)
PGSemaphoreUnlock(proc->sem);
return result;
}
/*
* LWLockConditionalAcquire - acquire a lightweight lock in the specified mode
*
* If the lock is not available, return false with no side-effects.
*
* If successful, cancel/die interrupts are held off until lock release.
*/
bool
LWLockConditionalAcquire(LWLock *lock, LWLockMode mode)
{
bool mustwait;
AssertArg(mode == LW_SHARED || mode == LW_EXCLUSIVE);
PRINT_LWDEBUG("LWLockConditionalAcquire", lock, mode);
/* Ensure we will have room to remember the lock */
if (num_held_lwlocks >= MAX_SIMUL_LWLOCKS)
elog(ERROR, "too many LWLocks taken");
/*
* Lock out cancel/die interrupts until we exit the code section protected
* by the LWLock. This ensures that interrupts will not interfere with
* manipulations of data structures in shared memory.
*/
HOLD_INTERRUPTS();
/* Check for the lock */
mustwait = LWLockAttemptLock(lock, mode);
if (mustwait)
{
/* Failed to get lock, so release interrupt holdoff */
RESUME_INTERRUPTS();
LOG_LWDEBUG("LWLockConditionalAcquire", lock, "failed");
TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE_FAIL(T_NAME(lock), mode);
}
else
{
/* Add lock to list of locks held by this backend */
held_lwlocks[num_held_lwlocks].lock = lock;
held_lwlocks[num_held_lwlocks++].mode = mode;
TRACE_POSTGRESQL_LWLOCK_CONDACQUIRE(T_NAME(lock), mode);
}
return !mustwait;
}
/*
* LWLockAcquireOrWait - Acquire lock, or wait until it's free
*
* The semantics of this function are a bit funky. If the lock is currently
* free, it is acquired in the given mode, and the function returns true. If
* the lock isn't immediately free, the function waits until it is released
* and returns false, but does not acquire the lock.
*
* This is currently used for WALWriteLock: when a backend flushes the WAL,
* holding WALWriteLock, it can flush the commit records of many other
* backends as a side-effect. Those other backends need to wait until the
* flush finishes, but don't need to acquire the lock anymore. They can just
* wake up, observe that their records have already been flushed, and return.
*/
bool
LWLockAcquireOrWait(LWLock *lock, LWLockMode mode)
{
PGPROC *proc = MyProc;
bool mustwait;
int extraWaits = 0;
/* POLAR: lock timing */
instr_time lwlock_wait_start;
bool is_blocking = false;
/* POLAR end */
#ifdef LWLOCK_STATS
lwlock_stats *lwstats;
lwstats = get_lwlock_stats_entry(lock);
#endif
/* POLAR: lock timing */
INSTR_TIME_SET_ZERO(lwlock_wait_start);
/* POLAR end */
Assert(mode == LW_SHARED || mode == LW_EXCLUSIVE);
PRINT_LWDEBUG("LWLockAcquireOrWait", lock, mode);
/* Ensure we will have room to remember the lock */
if (num_held_lwlocks >= MAX_SIMUL_LWLOCKS)
elog(ERROR, "too many LWLocks taken");
/*
* Lock out cancel/die interrupts until we exit the code section protected
* by the LWLock. This ensures that interrupts will not interfere with
* manipulations of data structures in shared memory.
*/
HOLD_INTERRUPTS();
/*
* NB: We're using nearly the same twice-in-a-row lock acquisition
* protocol as LWLockAcquire(). Check its comments for details.
*/
mustwait = LWLockAttemptLock(lock, mode);
if (mustwait)
{
LWLockQueueSelf(lock, LW_WAIT_UNTIL_FREE);
mustwait = LWLockAttemptLock(lock, mode);
if (mustwait)
{
/*
* Wait until awakened. Like in LWLockAcquire, be prepared for
* bogus wakeups, because we share the semaphore with
* ProcWaitForSignal.
*/
LOG_LWDEBUG("LWLockAcquireOrWait", lock, "waiting");
#ifdef LWLOCK_STATS
lwstats->block_count++;
#endif
/* POLAR: track lock wait */
{
POLAR_LOCK_STATS_TIME_START(lwlock_wait_start);
if (!is_blocking)
polar_stat_wait_obj_and_time_set(pg_atomic_read_u32(&lock->x_pid), &lwlock_wait_start, PGPROC_WAIT_PID);
POLAR_LWLOCK_STAT_BLOCK(lock, is_blocking);
}
/* POLAR end */
LWLockReportWaitStart(lock);
TRACE_POSTGRESQL_LWLOCK_WAIT_START(T_NAME(lock), mode);
for (;;)
{
PGSemaphoreLock(proc->sem);
if (!proc->lwWaiting)
break;
extraWaits++;
}
{
/* not waiting anymore */
uint32 nwaiters PG_USED_FOR_ASSERTS_ONLY = pg_atomic_fetch_sub_u32(&lock->nwaiters, 1);
Assert(nwaiters < MAX_BACKENDS);
}
TRACE_POSTGRESQL_LWLOCK_WAIT_DONE(T_NAME(lock), mode);
LWLockReportWaitEnd();
/* POLAR: track lock wait */
polar_lwlock_stat_record_time(lock, &lwlock_wait_start);
if (is_blocking)
polar_stat_wait_obj_and_time_clear();
/* POLAR end */
LOG_LWDEBUG("LWLockAcquireOrWait", lock, "awakened");
}
else
{
LOG_LWDEBUG("LWLockAcquireOrWait", lock, "acquired, undoing queue");
/*
* Got lock in the second attempt, undo queueing. We need to treat
* this as having successfully acquired the lock, otherwise we'd
* not necessarily wake up people we've prevented from acquiring
* the lock.
*/
LWLockDequeueSelf(lock);
}
}
/*
* Fix the process wait semaphore's count for any absorbed wakeups.
*/
while (extraWaits-- > 0)
PGSemaphoreUnlock(proc->sem);
if (mustwait)
{
/* Failed to get lock, so release interrupt holdoff */
RESUME_INTERRUPTS();
LOG_LWDEBUG("LWLockAcquireOrWait", lock, "failed");
TRACE_POSTGRESQL_LWLOCK_ACQUIRE_OR_WAIT_FAIL(T_NAME(lock), mode);
}
else
{
LOG_LWDEBUG("LWLockAcquireOrWait", lock, "succeeded");
/* Add lock to list of locks held by this backend */
held_lwlocks[num_held_lwlocks].lock = lock;
held_lwlocks[num_held_lwlocks++].mode = mode;
TRACE_POSTGRESQL_LWLOCK_ACQUIRE_OR_WAIT(T_NAME(lock), mode);
}
return !mustwait;
}
/*
* Does the lwlock in its current state need to wait for the variable value to
* change?
*
* If we don't need to wait, and it's because the value of the variable has
* changed, store the current value in newval.
*
* *result is set to true if the lock was free, and false otherwise.
*/
static bool
LWLockConflictsWithVar(LWLock *lock,
uint64 *valptr, uint64 oldval, uint64 *newval,
bool *result)
{
bool mustwait;
uint64 value;
/*
* Test first to see if it the slot is free right now.
*
* XXX: the caller uses a spinlock before this, so we don't need a memory
* barrier here as far as the current usage is concerned. But that might
* not be safe in general.
*/
mustwait = (pg_atomic_read_u32(&lock->state) & LW_VAL_EXCLUSIVE) != 0;
if (!mustwait)
{
*result = true;
return false;
}
*result = false;
/*
* Read value using the lwlock's wait list lock, as we can't generally
* rely on atomic 64 bit reads/stores. TODO: On platforms with a way to
* do atomic 64 bit reads/writes the spinlock should be optimized away.
*/
LWLockWaitListLock(lock);
value = *valptr;
LWLockWaitListUnlock(lock);
if (value != oldval)
{
mustwait = false;
*newval = value;
}
else
{
mustwait = true;
}
return mustwait;
}
/*
* LWLockWaitForVar - Wait until lock is free, or a variable is updated.
*
* If the lock is held and *valptr equals oldval, waits until the lock is
* either freed, or the lock holder updates *valptr by calling
* LWLockUpdateVar. If the lock is free on exit (immediately or after
* waiting), returns true. If the lock is still held, but *valptr no longer
* matches oldval, returns false and sets *newval to the current value in
* *valptr.
*
* Note: this function ignores shared lock holders; if the lock is held
* in shared mode, returns 'true'.
*/
bool
LWLockWaitForVar(LWLock *lock, uint64 *valptr, uint64 oldval, uint64 *newval)
{
PGPROC *proc = MyProc;
int extraWaits = 0;
bool result = false;
/* POLAR: lock stats */
instr_time lwlock_wait_start;
bool is_blocking = false;
/* POLAR end */
#ifdef LWLOCK_STATS
lwlock_stats *lwstats;
lwstats = get_lwlock_stats_entry(lock);
#endif
/* POLAR: lock wait time */
INSTR_TIME_SET_ZERO(lwlock_wait_start);
/* POLAR end */
PRINT_LWDEBUG("LWLockWaitForVar", lock, LW_WAIT_UNTIL_FREE);
/*
* Lock out cancel/die interrupts while we sleep on the lock. There is no
* cleanup mechanism to remove us from the wait queue if we got
* interrupted.
*/
HOLD_INTERRUPTS();
/*
* Loop here to check the lock's status after each time we are signaled.
*/
for (;;)
{
bool mustwait;
mustwait = LWLockConflictsWithVar(lock, valptr, oldval, newval,
&result);
if (!mustwait)
break; /* the lock was free or value didn't match */
/*
* Add myself to wait queue. Note that this is racy, somebody else
* could wakeup before we're finished queuing. NB: We're using nearly
* the same twice-in-a-row lock acquisition protocol as
* LWLockAcquire(). Check its comments for details. The only
* difference is that we also have to check the variable's values when
* checking the state of the lock.
*/
LWLockQueueSelf(lock, LW_WAIT_UNTIL_FREE);
/*
* Set RELEASE_OK flag, to make sure we get woken up as soon as the
* lock is released.
*/
pg_atomic_fetch_or_u32(&lock->state, LW_FLAG_RELEASE_OK);
/*
* We're now guaranteed to be woken up if necessary. Recheck the lock
* and variables state.
*/
mustwait = LWLockConflictsWithVar(lock, valptr, oldval, newval,
&result);
/* Ok, no conflict after we queued ourselves. Undo queueing. */
if (!mustwait)
{
LOG_LWDEBUG("LWLockWaitForVar", lock, "free, undoing queue");
LWLockDequeueSelf(lock);
break;
}
/*
* Wait until awakened.
*
* Since we share the process wait semaphore with the regular lock
* manager and ProcWaitForSignal, and we may need to acquire an LWLock
* while one of those is pending, it is possible that we get awakened
* for a reason other than being signaled by LWLockRelease. If so,
* loop back and wait again. Once we've gotten the LWLock,
* re-increment the sema by the number of additional signals received,
* so that the lock manager or signal manager will see the received
* signal when it next waits.
*/
LOG_LWDEBUG("LWLockWaitForVar", lock, "waiting");
#ifdef LWLOCK_STATS
lwstats->block_count++;
#endif
/* POLAR: track lock wait */
{
POLAR_LOCK_STATS_TIME_START(lwlock_wait_start);
if (!is_blocking)
polar_stat_wait_obj_and_time_set(pg_atomic_read_u32(&lock->x_pid), &lwlock_wait_start, PGPROC_WAIT_PID);
POLAR_LWLOCK_STAT_BLOCK(lock, is_blocking);
}
/* POLAR end */
LWLockReportWaitStart(lock);
TRACE_POSTGRESQL_LWLOCK_WAIT_START(T_NAME(lock), LW_EXCLUSIVE);
for (;;)
{
PGSemaphoreLock(proc->sem);
if (!proc->lwWaiting)
break;
extraWaits++;
}
{
/* not waiting anymore */
uint32 nwaiters PG_USED_FOR_ASSERTS_ONLY = pg_atomic_fetch_sub_u32(&lock->nwaiters, 1);
Assert(nwaiters < MAX_BACKENDS);
}
TRACE_POSTGRESQL_LWLOCK_WAIT_DONE(T_NAME(lock), LW_EXCLUSIVE);
LWLockReportWaitEnd();
LOG_LWDEBUG("LWLockWaitForVar", lock, "awakened");
/* Now loop back and check the status of the lock again. */
}
/* POLAR: track lock timing */
polar_lwlock_stat_record_time(lock, &lwlock_wait_start);
if (is_blocking)
polar_stat_wait_obj_and_time_clear();
/* POLAR end */
TRACE_POSTGRESQL_LWLOCK_ACQUIRE(T_NAME(lock), LW_EXCLUSIVE);
/*
* Fix the process wait semaphore's count for any absorbed wakeups.
*/
while (extraWaits-- > 0)
PGSemaphoreUnlock(proc->sem);
/*
* Now okay to allow cancel/die interrupts.
*/
RESUME_INTERRUPTS();
return result;
}
/*
* LWLockUpdateVar - Update a variable and wake up waiters atomically
*
* Sets *valptr to 'val', and wakes up all processes waiting for us with
* LWLockWaitForVar(). Setting the value and waking up the processes happen
* atomically so that any process calling LWLockWaitForVar() on the same lock
* is guaranteed to see the new value, and act accordingly.
*
* The caller must be holding the lock in exclusive mode.
*/
void
LWLockUpdateVar(LWLock *lock, uint64 *valptr, uint64 val)
{
proclist_head wakeup;
proclist_mutable_iter iter;
PRINT_LWDEBUG("LWLockUpdateVar", lock, LW_EXCLUSIVE);
proclist_init(&wakeup);
LWLockWaitListLock(lock);
Assert(pg_atomic_read_u32(&lock->state) & LW_VAL_EXCLUSIVE);
/* Update the lock's value */
*valptr = val;
/*
* See if there are any LW_WAIT_UNTIL_FREE waiters that need to be woken
* up. They are always in the front of the queue.
*/
proclist_foreach_modify(iter, &lock->waiters, lwWaitLink)
{
PGPROC *waiter = GetPGProcByNumber(iter.cur);
if (waiter->lwWaitMode != LW_WAIT_UNTIL_FREE)
break;
proclist_delete(&lock->waiters, iter.cur, lwWaitLink);
proclist_push_tail(&wakeup, iter.cur, lwWaitLink);
}
/* We are done updating shared state of the lock itself. */
LWLockWaitListUnlock(lock);
/*
* Awaken any waiters I removed from the queue.
*/
proclist_foreach_modify(iter, &wakeup, lwWaitLink)
{
PGPROC *waiter = GetPGProcByNumber(iter.cur);
proclist_delete(&wakeup, iter.cur, lwWaitLink);
/* check comment in LWLockWakeup() about this barrier */
pg_write_barrier();
waiter->lwWaiting = false;
PGSemaphoreUnlock(waiter->sem);
}
}
/*
* LWLockRelease - release a previously acquired lock
*/
void
LWLockRelease(LWLock *lock)
{
LWLockMode mode;
uint32 oldstate;
bool check_waiters;
int i;
/*
* Remove lock from list of locks held. Usually, but not always, it will
* be the latest-acquired lock; so search array backwards.
*/
for (i = num_held_lwlocks; --i >= 0;)
if (lock == held_lwlocks[i].lock)
break;
if (i < 0)
elog(ERROR, "lock %s is not held", T_NAME(lock));
mode = held_lwlocks[i].mode;
num_held_lwlocks--;
for (; i < num_held_lwlocks; i++)
held_lwlocks[i] = held_lwlocks[i + 1];
PRINT_LWDEBUG("LWLockRelease", lock, mode);
/*
* Release my hold on lock, after that it can immediately be acquired by
* others, even if we still have to wakeup other waiters.
*/
if (mode == LW_EXCLUSIVE)
oldstate = pg_atomic_sub_fetch_u32(&lock->state, LW_VAL_EXCLUSIVE);
else
oldstate = pg_atomic_sub_fetch_u32(&lock->state, LW_VAL_SHARED);
/* nobody else can have that kind of lock */
Assert(!(oldstate & LW_VAL_EXCLUSIVE));
if (mode == LW_EXCLUSIVE)
{
pg_atomic_write_u32(&lock->x_pid, 0);
}
/*
* We're still waiting for backends to get scheduled, don't wake them up
* again.
*/
if ((oldstate & (LW_FLAG_HAS_WAITERS | LW_FLAG_RELEASE_OK)) ==
(LW_FLAG_HAS_WAITERS | LW_FLAG_RELEASE_OK) &&
(oldstate & LW_LOCK_MASK) == 0)
check_waiters = true;
else
check_waiters = false;
/*
* As waking up waiters requires the spinlock to be acquired, only do so
* if necessary.
*/
if (check_waiters)
{
/* XXX: remove before commit? */
LOG_LWDEBUG("LWLockRelease", lock, "releasing waiters");
LWLockWakeup(lock);
}
TRACE_POSTGRESQL_LWLOCK_RELEASE(T_NAME(lock));
/*
* Now okay to allow cancel/die interrupts.
*/
RESUME_INTERRUPTS();
}
/*
* LWLockReleaseClearVar - release a previously acquired lock, reset variable
*/
void
LWLockReleaseClearVar(LWLock *lock, uint64 *valptr, uint64 val)
{
LWLockWaitListLock(lock);
/*
* Set the variable's value before releasing the lock, that prevents race
* a race condition wherein a new locker acquires the lock, but hasn't yet
* set the variables value.
*/
*valptr = val;
LWLockWaitListUnlock(lock);
LWLockRelease(lock);
}
/*
* LWLockReleaseAll - release all currently-held locks
*
* Used to clean up after ereport(ERROR). An important difference between this
* function and retail LWLockRelease calls is that InterruptHoldoffCount is
* unchanged by this operation. This is necessary since InterruptHoldoffCount
* has been set to an appropriate level earlier in error recovery. We could
* decrement it below zero if we allow it to drop for each released lock!
*/
void
LWLockReleaseAll(void)
{
while (num_held_lwlocks > 0)
{
HOLD_INTERRUPTS(); /* match the upcoming RESUME_INTERRUPTS */
LWLockRelease(held_lwlocks[num_held_lwlocks - 1].lock);
}
}
/*
* LWLockHeldByMe - test whether my process holds a lock in any mode
*
* This is meant as debug support only.
*/
bool
LWLockHeldByMe(LWLock *l)
{
int i;
for (i = 0; i < num_held_lwlocks; i++)
{
if (held_lwlocks[i].lock == l)
return true;
}
return false;
}
/*
* LWLockHeldByMeInMode - test whether my process holds a lock in given mode
*
* This is meant as debug support only.
*/
bool
LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
{
int i;
for (i = 0; i < num_held_lwlocks; i++)
{
if (held_lwlocks[i].lock == l && held_lwlocks[i].mode == mode)
return true;
}
return false;
}
/*
* PALOR
* polar_remaining_lwlock_slot_count -- return remaining slot count of held_lwlocks.
*/
int
polar_remaining_lwlock_slot_count(void)
{
return MAX_SIMUL_LWLOCKS - num_held_lwlocks;
}
/*
* POLAR: get max lock tranche id now
*/
int
polar_get_lwlock_counter(void)
{
int result;
int *LWLockCounter;
LWLockCounter = (int *) ((char *) MainLWLockArray - sizeof(int));
SpinLockAcquire(ShmemLock);
result = (*LWLockCounter);
SpinLockRelease(ShmemLock);
return result;
}
/* POLAR end */
|
579663.c | /*
* Copyright (c) 2000-2002, Darren Hiebert
*
* This source code is released for free distribution under the terms of the
* GNU General Public License version 2 or (at your option) any later version.
*
* This module contains functions for generating tags for LISP files.
*/
/*
* INCLUDE FILES
*/
#include "general.h" /* must always come first */
#include "parse.h"
#include "read.h"
#include "routines.h"
#include "vstring.h"
/*
* DATA DEFINITIONS
*/
typedef enum {
K_FUNCTION
} lispKind;
static kindOption LispKinds [] = {
{ true, 'f', "function", "functions" }
};
/*
* FUNCTION DEFINITIONS
*/
/*
* lisp tag functions
* look for (def or (DEF, quote or QUOTE
*/
static int L_isdef (const unsigned char *strp)
{
return ( (strp [1] == 'd' || strp [1] == 'D')
&& (strp [2] == 'e' || strp [2] == 'E')
&& (strp [3] == 'f' || strp [3] == 'F'));
}
static int L_isquote (const unsigned char *strp)
{
return ( (*(++strp) == 'q' || *strp == 'Q')
&& (*(++strp) == 'u' || *strp == 'U')
&& (*(++strp) == 'o' || *strp == 'O')
&& (*(++strp) == 't' || *strp == 'T')
&& (*(++strp) == 'e' || *strp == 'E')
&& isspace (*(++strp)));
}
static void L_getit (vString *const name, const unsigned char *dbp)
{
const unsigned char *p;
if (*dbp == '\'') /* Skip prefix quote */
dbp++;
else if (*dbp == '(' && L_isquote (dbp)) /* Skip "(quote " */
{
dbp += 7;
while (isspace (*dbp))
dbp++;
}
for (p=dbp ; *p!='\0' && *p!='(' && !isspace ((int) *p) && *p!=')' ; p++)
vStringPut (name, *p);
if (vStringLength (name) > 0)
makeSimpleTag (name, LispKinds, K_FUNCTION);
vStringClear (name);
}
/* Algorithm adapted from from GNU etags.
*/
static void findLispTags (void)
{
vString *name = vStringNew ();
const unsigned char* p;
while ((p = readLineFromInputFile ()) != NULL)
{
if (*p == '(')
{
if (L_isdef (p))
{
while (*p != '\0' && !isspace ((int) *p))
p++;
while (isspace ((int) *p))
p++;
L_getit (name, p);
}
else
{
/* Check for (foo::defmumble name-defined ... */
do
p++;
while (*p != '\0' && !isspace ((int) *p)
&& *p != ':' && *p != '(' && *p != ')');
if (*p == ':')
{
do
p++;
while (*p == ':');
if (L_isdef (p - 1))
{
while (*p != '\0' && !isspace ((int) *p))
p++;
while (isspace (*p))
p++;
L_getit (name, p);
}
}
}
}
}
vStringDelete (name);
}
extern parserDefinition* LispParser (void)
{
static const char *const extensions [] = {
"cl", "clisp", "el", "l", "lisp", "lsp", NULL
};
static const char *const aliases [] = {
"clisp", "emacs-lisp", NULL
};
parserDefinition* def = parserNew ("Lisp");
def->kinds = LispKinds;
def->kindCount = ARRAY_SIZE (LispKinds);
def->extensions = extensions;
def->aliases = aliases;
def->parser = findLispTags;
return def;
}
|
739431.c | // Options: --no-arrays --no-pointers --no-structs --no-unions --argc --no-bitfields --checksum --comma-operators --compound-assignment --concise --consts --divs --embedded-assigns --pre-incr-operator --pre-decr-operator --post-incr-operator --post-decr-operator --unary-plus-operator --jumps --longlong --int8 --uint8 --no-float --main --math64 --muls --safe-math --no-packed-struct --no-paranoid --no-volatiles --no-volatile-pointers --const-pointers --no-builtins --max-array-dim 1 --max-array-len-per-dim 4 --max-block-depth 1 --max-block-size 4 --max-expr-complexity 1 --max-funcs 1 --max-pointer-depth 2 --max-struct-fields 2 --max-union-fields 2 -o csmith_574.c
#include "csmith.h"
static long __undefined;
static int64_t g_2 = 0x70AD6F2EE76F5020LL;
static int64_t g_3 = 1L;
static int64_t g_8 = (-1L);
static uint32_t g_9 = 3UL;
static uint32_t func_1(void);
static uint32_t func_1(void)
{
uint8_t l_4 = 9UL;
g_3 = g_2;
l_4 = g_3;
for (l_4 = (-14); (l_4 < 10); ++l_4)
{
int32_t l_7 = (-1L);
++g_9;
}
return l_4;
}
int main (int argc, char* argv[])
{
int print_hash_value = 0;
if (argc == 2 && strcmp(argv[1], "1") == 0) print_hash_value = 1;
platform_main_begin();
crc32_gentab();
func_1();
transparent_crc(g_2, "g_2", print_hash_value);
transparent_crc(g_3, "g_3", print_hash_value);
transparent_crc(g_8, "g_8", print_hash_value);
transparent_crc(g_9, "g_9", print_hash_value);
platform_main_end(crc32_context ^ 0xFFFFFFFFUL, print_hash_value);
return 0;
}
|
630444.c | /*
-Procedure j2100_c ( Julian Date of 2100 JAN 1.5 )
-Abstract
Return the Julian Date of 2100 JAN 01 12:00:00 (2100 JAN 1.5).
-Disclaimer
THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE
CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S.
GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE
ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE
PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS"
TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY
WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A
PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC
SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE
SOFTWARE AND RELATED MATERIALS, HOWEVER USED.
IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA
BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT
LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND,
INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS,
REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE
REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY.
RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF
THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY
CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE
ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE.
-Required_Reading
None.
-Keywords
CONSTANTS
*/
#include "SpiceUsr.h"
SpiceDouble j2100_c ( void )
/*
-Brief_I/O
The function returns the Julian Date of 2100 JAN 01 12:00:00
(2100 JAN 1.5).
-Detailed_Input
None.
-Detailed_Output
The function returns 2488070.0, the Julian Date corresponding
to 2100 JAN 01 12:00:00 (2100 JAN 1.5).
-Parameters
None.
-Exceptions
Error free.
-Files
None.
-Particulars
The function always returns the constant value shown above.
-Examples
The numerical results shown for these examples may differ across
platforms. The results depend on the SPICE kernels used as
input, the compiler and supporting libraries, and the machine
specific arithmetic implementation.
1) Display the double precision value for the J2100 date.
Example code begins here.
/.
Program j2100_ex1
./
#include <stdio.h>
#include "SpiceUsr.h"
int main( )
{
/.
Display the J2100 date in 16.8 floating point format
./
printf ( "J2100 date: %16.8f\n", j2100_c() );
return ( 0 );
}
When this program was executed on a Mac/Intel/cc/64-bit
platform, the output was:
J2100 date: 2488070.00000000
2) Convert an input time in UTC format to TDB seconds past the
following reference epochs:
- Besselian date 1900 and 1950; and
- Julian date 1900, 1950, 2000 and 2100.
Use the LSK kernel below to load the leap seconds and time
constants required for the conversions.
naif0012.tls
Example code begins here.
/.
Program j2100_ex2
./
#include <stdio.h>
#include "SpiceUsr.h"
int main( )
{
/.
Local constants.
./
#define UTCSTR "1991-NOV-26"
/.
Local variables.
./
SpiceDouble et;
SpiceDouble jed;
/.
Load the LSK file.
./
furnsh_c ( "naif0012.tls" );
/.
Convert input UTC string to Ephemeris Time.
./
str2et_c ( UTCSTR, &et );
printf ( "Input ephemeris time : %20.3f\n\n", et );
/.
Convert the Ephemeris Time to Julian ephemeris date, i.e.
Julian date relative to TDB time scale.
./
jed = unitim_c ( et, "ET", "JED" );
/.
Convert Julian Date to TDB seconds past the reference epochs
and output the results.
./
printf ( "TDB seconds past B1900: %20.3f\n",
( jed - b1900_c() ) * spd_c() );
printf ( "TDB seconds past B1950: %20.3f\n",
( jed - b1950_c() ) * spd_c() );
printf ( "TDB seconds past J1900: %20.3f\n",
( jed - j1900_c() ) * spd_c() );
printf ( "TDB seconds past J1950: %20.3f\n",
( jed - j1950_c() ) * spd_c() );
printf ( "TDB seconds past J2000: %20.3f\n",
( jed - j2000_c() ) * spd_c() );
printf ( "TDB seconds past J2100: %20.3f\n",
( jed - j2100_c() ) * spd_c() );
return ( 0 );
}
When this program was executed on a Mac/Intel/cc/64-bit
platform, the output was:
Input ephemeris time : -255614341.817
TDB seconds past B1900: 2900118570.055
TDB seconds past B1950: 1322272271.321
TDB seconds past J1900: 2900145658.183
TDB seconds past J1950: 1322265658.183
TDB seconds past J2000: -255614341.817
TDB seconds past J2100: -3411374341.817
-Restrictions
None.
-Literature_References
None.
-Author_and_Institution
J. Diaz del Rio (ODC Space)
W.L. Taber (JPL)
I.M. Underwood (JPL)
E.D. Wright (JPL)
-Version
-CSPICE Version 1.0.1, 06-JUL-2021 (JDR)
Edited the header to comply with NAIF standard. Added
complete code examples.
-CSPICE Version 1.0.0, 08-FEB-1998 (EDW) (WLT) (IMU)
-Index_Entries
julian date of 2100 jan 1.5
-&
*/
{ /* Begin j2100_c */
return 2488070.0;
} /* End j2100_c */
|
118409.c | /*
* RV10/RV20 decoder
* Copyright (c) 2000,2001 Fabrice Bellard
* Copyright (c) 2002-2004 Michael Niedermayer
*
* 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
* RV10/RV20 decoder
*/
#include "libavutil/imgutils.h"
#include "avcodec.h"
#include "error_resilience.h"
#include "internal.h"
#include "mpegvideo.h"
#include "mpeg4video.h"
#include "h263.h"
#define RV_GET_MAJOR_VER(x) ((x) >> 28)
#define RV_GET_MINOR_VER(x) (((x) >> 20) & 0xFF)
#define RV_GET_MICRO_VER(x) (((x) >> 12) & 0xFF)
#define DC_VLC_BITS 14 //FIXME find a better solution
typedef struct RVDecContext {
MpegEncContext m;
int sub_id;
} RVDecContext;
static const uint16_t rv_lum_code[256] = {
0x3e7f, 0x0f00, 0x0f01, 0x0f02, 0x0f03, 0x0f04, 0x0f05, 0x0f06,
0x0f07, 0x0f08, 0x0f09, 0x0f0a, 0x0f0b, 0x0f0c, 0x0f0d, 0x0f0e,
0x0f0f, 0x0f10, 0x0f11, 0x0f12, 0x0f13, 0x0f14, 0x0f15, 0x0f16,
0x0f17, 0x0f18, 0x0f19, 0x0f1a, 0x0f1b, 0x0f1c, 0x0f1d, 0x0f1e,
0x0f1f, 0x0f20, 0x0f21, 0x0f22, 0x0f23, 0x0f24, 0x0f25, 0x0f26,
0x0f27, 0x0f28, 0x0f29, 0x0f2a, 0x0f2b, 0x0f2c, 0x0f2d, 0x0f2e,
0x0f2f, 0x0f30, 0x0f31, 0x0f32, 0x0f33, 0x0f34, 0x0f35, 0x0f36,
0x0f37, 0x0f38, 0x0f39, 0x0f3a, 0x0f3b, 0x0f3c, 0x0f3d, 0x0f3e,
0x0f3f, 0x0380, 0x0381, 0x0382, 0x0383, 0x0384, 0x0385, 0x0386,
0x0387, 0x0388, 0x0389, 0x038a, 0x038b, 0x038c, 0x038d, 0x038e,
0x038f, 0x0390, 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396,
0x0397, 0x0398, 0x0399, 0x039a, 0x039b, 0x039c, 0x039d, 0x039e,
0x039f, 0x00c0, 0x00c1, 0x00c2, 0x00c3, 0x00c4, 0x00c5, 0x00c6,
0x00c7, 0x00c8, 0x00c9, 0x00ca, 0x00cb, 0x00cc, 0x00cd, 0x00ce,
0x00cf, 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056,
0x0057, 0x0020, 0x0021, 0x0022, 0x0023, 0x000c, 0x000d, 0x0004,
0x0000, 0x0005, 0x000e, 0x000f, 0x0024, 0x0025, 0x0026, 0x0027,
0x0058, 0x0059, 0x005a, 0x005b, 0x005c, 0x005d, 0x005e, 0x005f,
0x00d0, 0x00d1, 0x00d2, 0x00d3, 0x00d4, 0x00d5, 0x00d6, 0x00d7,
0x00d8, 0x00d9, 0x00da, 0x00db, 0x00dc, 0x00dd, 0x00de, 0x00df,
0x03a0, 0x03a1, 0x03a2, 0x03a3, 0x03a4, 0x03a5, 0x03a6, 0x03a7,
0x03a8, 0x03a9, 0x03aa, 0x03ab, 0x03ac, 0x03ad, 0x03ae, 0x03af,
0x03b0, 0x03b1, 0x03b2, 0x03b3, 0x03b4, 0x03b5, 0x03b6, 0x03b7,
0x03b8, 0x03b9, 0x03ba, 0x03bb, 0x03bc, 0x03bd, 0x03be, 0x03bf,
0x0f40, 0x0f41, 0x0f42, 0x0f43, 0x0f44, 0x0f45, 0x0f46, 0x0f47,
0x0f48, 0x0f49, 0x0f4a, 0x0f4b, 0x0f4c, 0x0f4d, 0x0f4e, 0x0f4f,
0x0f50, 0x0f51, 0x0f52, 0x0f53, 0x0f54, 0x0f55, 0x0f56, 0x0f57,
0x0f58, 0x0f59, 0x0f5a, 0x0f5b, 0x0f5c, 0x0f5d, 0x0f5e, 0x0f5f,
0x0f60, 0x0f61, 0x0f62, 0x0f63, 0x0f64, 0x0f65, 0x0f66, 0x0f67,
0x0f68, 0x0f69, 0x0f6a, 0x0f6b, 0x0f6c, 0x0f6d, 0x0f6e, 0x0f6f,
0x0f70, 0x0f71, 0x0f72, 0x0f73, 0x0f74, 0x0f75, 0x0f76, 0x0f77,
0x0f78, 0x0f79, 0x0f7a, 0x0f7b, 0x0f7c, 0x0f7d, 0x0f7e, 0x0f7f,
};
static const uint8_t rv_lum_bits[256] = {
14, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12,
12, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10,
10, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8,
8, 7, 7, 7, 7, 7, 7, 7,
7, 6, 6, 6, 6, 5, 5, 4,
2, 4, 5, 5, 6, 6, 6, 6,
7, 7, 7, 7, 7, 7, 7, 7,
8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8,
10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10,
12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12,
};
static const uint16_t rv_chrom_code[256] = {
0xfe7f, 0x3f00, 0x3f01, 0x3f02, 0x3f03, 0x3f04, 0x3f05, 0x3f06,
0x3f07, 0x3f08, 0x3f09, 0x3f0a, 0x3f0b, 0x3f0c, 0x3f0d, 0x3f0e,
0x3f0f, 0x3f10, 0x3f11, 0x3f12, 0x3f13, 0x3f14, 0x3f15, 0x3f16,
0x3f17, 0x3f18, 0x3f19, 0x3f1a, 0x3f1b, 0x3f1c, 0x3f1d, 0x3f1e,
0x3f1f, 0x3f20, 0x3f21, 0x3f22, 0x3f23, 0x3f24, 0x3f25, 0x3f26,
0x3f27, 0x3f28, 0x3f29, 0x3f2a, 0x3f2b, 0x3f2c, 0x3f2d, 0x3f2e,
0x3f2f, 0x3f30, 0x3f31, 0x3f32, 0x3f33, 0x3f34, 0x3f35, 0x3f36,
0x3f37, 0x3f38, 0x3f39, 0x3f3a, 0x3f3b, 0x3f3c, 0x3f3d, 0x3f3e,
0x3f3f, 0x0f80, 0x0f81, 0x0f82, 0x0f83, 0x0f84, 0x0f85, 0x0f86,
0x0f87, 0x0f88, 0x0f89, 0x0f8a, 0x0f8b, 0x0f8c, 0x0f8d, 0x0f8e,
0x0f8f, 0x0f90, 0x0f91, 0x0f92, 0x0f93, 0x0f94, 0x0f95, 0x0f96,
0x0f97, 0x0f98, 0x0f99, 0x0f9a, 0x0f9b, 0x0f9c, 0x0f9d, 0x0f9e,
0x0f9f, 0x03c0, 0x03c1, 0x03c2, 0x03c3, 0x03c4, 0x03c5, 0x03c6,
0x03c7, 0x03c8, 0x03c9, 0x03ca, 0x03cb, 0x03cc, 0x03cd, 0x03ce,
0x03cf, 0x00e0, 0x00e1, 0x00e2, 0x00e3, 0x00e4, 0x00e5, 0x00e6,
0x00e7, 0x0030, 0x0031, 0x0032, 0x0033, 0x0008, 0x0009, 0x0002,
0x0000, 0x0003, 0x000a, 0x000b, 0x0034, 0x0035, 0x0036, 0x0037,
0x00e8, 0x00e9, 0x00ea, 0x00eb, 0x00ec, 0x00ed, 0x00ee, 0x00ef,
0x03d0, 0x03d1, 0x03d2, 0x03d3, 0x03d4, 0x03d5, 0x03d6, 0x03d7,
0x03d8, 0x03d9, 0x03da, 0x03db, 0x03dc, 0x03dd, 0x03de, 0x03df,
0x0fa0, 0x0fa1, 0x0fa2, 0x0fa3, 0x0fa4, 0x0fa5, 0x0fa6, 0x0fa7,
0x0fa8, 0x0fa9, 0x0faa, 0x0fab, 0x0fac, 0x0fad, 0x0fae, 0x0faf,
0x0fb0, 0x0fb1, 0x0fb2, 0x0fb3, 0x0fb4, 0x0fb5, 0x0fb6, 0x0fb7,
0x0fb8, 0x0fb9, 0x0fba, 0x0fbb, 0x0fbc, 0x0fbd, 0x0fbe, 0x0fbf,
0x3f40, 0x3f41, 0x3f42, 0x3f43, 0x3f44, 0x3f45, 0x3f46, 0x3f47,
0x3f48, 0x3f49, 0x3f4a, 0x3f4b, 0x3f4c, 0x3f4d, 0x3f4e, 0x3f4f,
0x3f50, 0x3f51, 0x3f52, 0x3f53, 0x3f54, 0x3f55, 0x3f56, 0x3f57,
0x3f58, 0x3f59, 0x3f5a, 0x3f5b, 0x3f5c, 0x3f5d, 0x3f5e, 0x3f5f,
0x3f60, 0x3f61, 0x3f62, 0x3f63, 0x3f64, 0x3f65, 0x3f66, 0x3f67,
0x3f68, 0x3f69, 0x3f6a, 0x3f6b, 0x3f6c, 0x3f6d, 0x3f6e, 0x3f6f,
0x3f70, 0x3f71, 0x3f72, 0x3f73, 0x3f74, 0x3f75, 0x3f76, 0x3f77,
0x3f78, 0x3f79, 0x3f7a, 0x3f7b, 0x3f7c, 0x3f7d, 0x3f7e, 0x3f7f,
};
static const uint8_t rv_chrom_bits[256] = {
16, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14,
14, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12,
12, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10,
10, 8, 8, 8, 8, 8, 8, 8,
8, 6, 6, 6, 6, 4, 4, 3,
2, 3, 4, 4, 6, 6, 6, 6,
8, 8, 8, 8, 8, 8, 8, 8,
10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10,
12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12,
14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14,
};
static VLC rv_dc_lum, rv_dc_chrom;
int ff_rv_decode_dc(MpegEncContext *s, int n)
{
int code;
if (n < 4) {
code = get_vlc2(&s->gb, rv_dc_lum.table, DC_VLC_BITS, 2);
if (code < 0) {
/* XXX: I don't understand why they use LONGER codes than
necessary. The following code would be completely useless
if they had thought about it !!! */
code = get_bits(&s->gb, 7);
if (code == 0x7c) {
code = (int8_t)(get_bits(&s->gb, 7) + 1);
} else if (code == 0x7d) {
code = -128 + get_bits(&s->gb, 7);
} else if (code == 0x7e) {
if (get_bits1(&s->gb) == 0)
code = (int8_t)(get_bits(&s->gb, 8) + 1);
else
code = (int8_t)(get_bits(&s->gb, 8));
} else if (code == 0x7f) {
skip_bits(&s->gb, 11);
code = 1;
}
} else {
code -= 128;
}
} else {
code = get_vlc2(&s->gb, rv_dc_chrom.table, DC_VLC_BITS, 2);
/* same remark */
if (code < 0) {
code = get_bits(&s->gb, 9);
if (code == 0x1fc) {
code = (int8_t)(get_bits(&s->gb, 7) + 1);
} else if (code == 0x1fd) {
code = -128 + get_bits(&s->gb, 7);
} else if (code == 0x1fe) {
skip_bits(&s->gb, 9);
code = 1;
} else {
av_log(s->avctx, AV_LOG_ERROR, "chroma dc error\n");
return 0xffff;
}
} else {
code -= 128;
}
}
return -code;
}
/* read RV 1.0 compatible frame header */
static int rv10_decode_picture_header(MpegEncContext *s)
{
int mb_count, pb_frame, marker, mb_xy;
marker = get_bits1(&s->gb);
if (get_bits1(&s->gb))
s->pict_type = AV_PICTURE_TYPE_P;
else
s->pict_type = AV_PICTURE_TYPE_I;
if (!marker)
av_log(s->avctx, AV_LOG_ERROR, "marker missing\n");
pb_frame = get_bits1(&s->gb);
av_dlog(s->avctx, "pict_type=%d pb_frame=%d\n", s->pict_type, pb_frame);
if (pb_frame) {
avpriv_request_sample(s->avctx, "pb frame");
return AVERROR_PATCHWELCOME;
}
s->qscale = get_bits(&s->gb, 5);
if (s->qscale == 0) {
av_log(s->avctx, AV_LOG_ERROR, "Invalid qscale value: 0\n");
return AVERROR_INVALIDDATA;
}
if (s->pict_type == AV_PICTURE_TYPE_I) {
if (s->rv10_version == 3) {
/* specific MPEG like DC coding not used */
s->last_dc[0] = get_bits(&s->gb, 8);
s->last_dc[1] = get_bits(&s->gb, 8);
s->last_dc[2] = get_bits(&s->gb, 8);
av_dlog(s->avctx, "DC:%d %d %d\n", s->last_dc[0],
s->last_dc[1], s->last_dc[2]);
}
}
/* if multiple packets per frame are sent, the position at which
to display the macroblocks is coded here */
mb_xy = s->mb_x + s->mb_y * s->mb_width;
if (show_bits(&s->gb, 12) == 0 || (mb_xy && mb_xy < s->mb_num)) {
s->mb_x = get_bits(&s->gb, 6); /* mb_x */
s->mb_y = get_bits(&s->gb, 6); /* mb_y */
mb_count = get_bits(&s->gb, 12);
} else {
s->mb_x = 0;
s->mb_y = 0;
mb_count = s->mb_width * s->mb_height;
}
skip_bits(&s->gb, 3); /* ignored */
s->f_code = 1;
s->unrestricted_mv = 1;
return mb_count;
}
static int rv20_decode_picture_header(RVDecContext *rv)
{
MpegEncContext *s = &rv->m;
int seq, mb_pos, i, ret;
int rpr_max;
i = get_bits(&s->gb, 2);
switch(i) {
case 0: s->pict_type = AV_PICTURE_TYPE_I; break;
case 1: s->pict_type = AV_PICTURE_TYPE_I; break; //hmm ...
case 2: s->pict_type = AV_PICTURE_TYPE_P; break;
case 3: s->pict_type = AV_PICTURE_TYPE_B; break;
default:
av_log(s->avctx, AV_LOG_ERROR, "unknown frame type\n");
return AVERROR_INVALIDDATA;
}
if (s->low_delay && s->pict_type == AV_PICTURE_TYPE_B) {
av_log(s->avctx, AV_LOG_ERROR, "low delay B\n");
return -1;
}
if (s->last_picture_ptr == NULL && s->pict_type == AV_PICTURE_TYPE_B) {
av_log(s->avctx, AV_LOG_ERROR, "early B-frame\n");
return AVERROR_INVALIDDATA;
}
if (get_bits1(&s->gb)) {
av_log(s->avctx, AV_LOG_ERROR, "reserved bit set\n");
return AVERROR_INVALIDDATA;
}
s->qscale = get_bits(&s->gb, 5);
if (s->qscale == 0) {
av_log(s->avctx, AV_LOG_ERROR, "Invalid qscale value: 0\n");
return AVERROR_INVALIDDATA;
}
if (RV_GET_MINOR_VER(rv->sub_id) >= 2)
s->loop_filter = get_bits1(&s->gb) && !s->avctx->lowres;
if (RV_GET_MINOR_VER(rv->sub_id) <= 1)
seq = get_bits(&s->gb, 8) << 7;
else
seq = get_bits(&s->gb, 13) << 2;
rpr_max = s->avctx->extradata[1] & 7;
if (rpr_max) {
int f, new_w, new_h;
int rpr_bits = av_log2(rpr_max) + 1;
f = get_bits(&s->gb, rpr_bits);
if (f) {
if (s->avctx->extradata_size < 8 + 2 * f) {
av_log(s->avctx, AV_LOG_ERROR, "Extradata too small.\n");
return AVERROR_INVALIDDATA;
}
new_w = 4 * ((uint8_t*)s->avctx->extradata)[6 + 2 * f];
new_h = 4 * ((uint8_t*)s->avctx->extradata)[7 + 2 * f];
} else {
new_w = s->orig_width ;
new_h = s->orig_height;
}
if (new_w != s->width || new_h != s->height) {
AVRational old_aspect = s->avctx->sample_aspect_ratio;
av_log(s->avctx, AV_LOG_DEBUG,
"attempting to change resolution to %dx%d\n", new_w, new_h);
if (av_image_check_size(new_w, new_h, 0, s->avctx) < 0)
return AVERROR_INVALIDDATA;
ff_MPV_common_end(s);
// attempt to keep aspect during typical resolution switches
if (!old_aspect.num)
old_aspect = (AVRational){1, 1};
if (2 * new_w * s->height == new_h * s->width)
s->avctx->sample_aspect_ratio = av_mul_q(old_aspect, (AVRational){2, 1});
if (new_w * s->height == 2 * new_h * s->width)
s->avctx->sample_aspect_ratio = av_mul_q(old_aspect, (AVRational){1, 2});
ret = ff_set_dimensions(s->avctx, new_w, new_h);
if (ret < 0)
return ret;
s->width = new_w;
s->height = new_h;
if ((ret = ff_MPV_common_init(s)) < 0)
return ret;
}
if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
av_log(s->avctx, AV_LOG_DEBUG, "F %d/%d/%d\n", f, rpr_bits, rpr_max);
}
}
if (av_image_check_size(s->width, s->height, 0, s->avctx) < 0)
return AVERROR_INVALIDDATA;
mb_pos = ff_h263_decode_mba(s);
seq |= s->time & ~0x7FFF;
if (seq - s->time > 0x4000)
seq -= 0x8000;
if (seq - s->time < -0x4000)
seq += 0x8000;
if (seq != s->time) {
if (s->pict_type != AV_PICTURE_TYPE_B) {
s->time = seq;
s->pp_time = s->time - s->last_non_b_time;
s->last_non_b_time = s->time;
} else {
s->time = seq;
s->pb_time = s->pp_time - (s->last_non_b_time - s->time);
}
}
if (s->pict_type == AV_PICTURE_TYPE_B) {
if (s->pp_time <=s->pb_time || s->pp_time <= s->pp_time - s->pb_time || s->pp_time<=0) {
av_log(s->avctx, AV_LOG_DEBUG,
"messed up order, possible from seeking? skipping current b frame\n");
#define ERROR_SKIP_FRAME -123
return ERROR_SKIP_FRAME;
}
ff_mpeg4_init_direct_mv(s);
}
s->no_rounding = get_bits1(&s->gb);
if (RV_GET_MINOR_VER(rv->sub_id) <= 1 && s->pict_type == AV_PICTURE_TYPE_B)
skip_bits(&s->gb, 5); // binary decoder reads 3+2 bits here but they don't seem to be used
s->f_code = 1;
s->unrestricted_mv = 1;
s->h263_aic = s->pict_type == AV_PICTURE_TYPE_I;
s->modified_quant = 1;
if (!s->avctx->lowres)
s->loop_filter = 1;
if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
av_log(s->avctx, AV_LOG_INFO, "num:%5d x:%2d y:%2d type:%d qscale:%2d rnd:%d\n",
seq, s->mb_x, s->mb_y, s->pict_type, s->qscale, s->no_rounding);
}
av_assert0(s->pict_type != AV_PICTURE_TYPE_B || !s->low_delay);
return s->mb_width*s->mb_height - mb_pos;
}
static av_cold int rv10_decode_init(AVCodecContext *avctx)
{
RVDecContext *rv = avctx->priv_data;
MpegEncContext *s = &rv->m;
static int done = 0;
int major_ver, minor_ver, micro_ver, ret;
if (avctx->extradata_size < 8) {
av_log(avctx, AV_LOG_ERROR, "Extradata is too small.\n");
return AVERROR_INVALIDDATA;
}
if ((ret = av_image_check_size(avctx->coded_width,
avctx->coded_height, 0, avctx)) < 0)
return ret;
ff_MPV_decode_defaults(s);
s->avctx = avctx;
s->out_format = FMT_H263;
s->codec_id = avctx->codec_id;
s->orig_width = s->width = avctx->coded_width;
s->orig_height = s->height = avctx->coded_height;
s->h263_long_vectors = ((uint8_t*)avctx->extradata)[3] & 1;
rv->sub_id = AV_RB32((uint8_t*)avctx->extradata + 4);
major_ver = RV_GET_MAJOR_VER(rv->sub_id);
minor_ver = RV_GET_MINOR_VER(rv->sub_id);
micro_ver = RV_GET_MICRO_VER(rv->sub_id);
s->low_delay = 1;
switch (major_ver) {
case 1:
s->rv10_version = micro_ver ? 3 : 1;
s->obmc = micro_ver == 2;
break;
case 2:
if (minor_ver >= 2) {
s->low_delay = 0;
s->avctx->has_b_frames = 1;
}
break;
default:
av_log(s->avctx, AV_LOG_ERROR, "unknown header %X\n", rv->sub_id);
avpriv_request_sample(avctx, "RV1/2 version");
return AVERROR_PATCHWELCOME;
}
if (avctx->debug & FF_DEBUG_PICT_INFO) {
av_log(avctx, AV_LOG_DEBUG, "ver:%X ver0:%X\n", rv->sub_id,
((uint32_t*)avctx->extradata)[0]);
}
avctx->pix_fmt = AV_PIX_FMT_YUV420P;
if ((ret = ff_MPV_common_init(s)) < 0)
return ret;
ff_h263dsp_init(&s->h263dsp);
ff_h263_decode_init_vlc();
/* init rv vlc */
if (!done) {
INIT_VLC_STATIC(&rv_dc_lum, DC_VLC_BITS, 256,
rv_lum_bits, 1, 1,
rv_lum_code, 2, 2, 16384);
INIT_VLC_STATIC(&rv_dc_chrom, DC_VLC_BITS, 256,
rv_chrom_bits, 1, 1,
rv_chrom_code, 2, 2, 16388);
done = 1;
}
return 0;
}
static av_cold int rv10_decode_end(AVCodecContext *avctx)
{
MpegEncContext *s = avctx->priv_data;
ff_MPV_common_end(s);
return 0;
}
static int rv10_decode_packet(AVCodecContext *avctx,
const uint8_t *buf, int buf_size, int buf_size2)
{
RVDecContext *rv = avctx->priv_data;
MpegEncContext *s = &rv->m;
int mb_count, mb_pos, left, start_mb_x, active_bits_size, ret;
active_bits_size = buf_size * 8;
init_get_bits(&s->gb, buf, FFMAX(buf_size, buf_size2) * 8);
if (s->codec_id == AV_CODEC_ID_RV10)
mb_count = rv10_decode_picture_header(s);
else
mb_count = rv20_decode_picture_header(rv);
if (mb_count < 0) {
if (mb_count != ERROR_SKIP_FRAME)
av_log(s->avctx, AV_LOG_ERROR, "HEADER ERROR\n");
return AVERROR_INVALIDDATA;
}
if (s->mb_x >= s->mb_width ||
s->mb_y >= s->mb_height) {
av_log(s->avctx, AV_LOG_ERROR, "POS ERROR %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
mb_pos = s->mb_y * s->mb_width + s->mb_x;
left = s->mb_width * s->mb_height - mb_pos;
if (mb_count > left) {
av_log(s->avctx, AV_LOG_ERROR, "COUNT ERROR\n");
return AVERROR_INVALIDDATA;
}
if ((s->mb_x == 0 && s->mb_y == 0) || s->current_picture_ptr == NULL) {
if (s->current_picture_ptr) { // FIXME write parser so we always have complete frames?
ff_er_frame_end(&s->er);
ff_MPV_frame_end(s);
s->mb_x = s->mb_y = s->resync_mb_x = s->resync_mb_y = 0;
}
if ((ret = ff_MPV_frame_start(s, avctx)) < 0)
return ret;
ff_mpeg_er_frame_start(s);
} else {
if (s->current_picture_ptr->f.pict_type != s->pict_type) {
av_log(s->avctx, AV_LOG_ERROR, "Slice type mismatch\n");
return AVERROR_INVALIDDATA;
}
}
av_dlog(avctx, "qscale=%d\n", s->qscale);
/* default quantization values */
if (s->codec_id == AV_CODEC_ID_RV10) {
if (s->mb_y == 0)
s->first_slice_line = 1;
} else {
s->first_slice_line = 1;
s->resync_mb_x = s->mb_x;
}
start_mb_x = s->mb_x;
s->resync_mb_y = s->mb_y;
if (s->h263_aic) {
s->y_dc_scale_table = s->c_dc_scale_table = ff_aic_dc_scale_table;
} else {
s->y_dc_scale_table = s->c_dc_scale_table = ff_mpeg1_dc_scale_table;
}
if (s->modified_quant)
s->chroma_qscale_table = ff_h263_chroma_qscale_table;
ff_set_qscale(s, s->qscale);
s->rv10_first_dc_coded[0] = 0;
s->rv10_first_dc_coded[1] = 0;
s->rv10_first_dc_coded[2] = 0;
s->block_wrap[0] =
s->block_wrap[1] =
s->block_wrap[2] =
s->block_wrap[3] = s->b8_stride;
s->block_wrap[4] =
s->block_wrap[5] = s->mb_stride;
ff_init_block_index(s);
/* decode each macroblock */
for (s->mb_num_left = mb_count; s->mb_num_left > 0; s->mb_num_left--) {
int ret;
ff_update_block_index(s);
av_dlog(avctx, "**mb x=%d y=%d\n", s->mb_x, s->mb_y);
s->mv_dir = MV_DIR_FORWARD;
s->mv_type = MV_TYPE_16X16;
ret = ff_h263_decode_mb(s, s->block);
// Repeat the slice end check from ff_h263_decode_mb with our active
// bitstream size
if (ret != SLICE_ERROR) {
int v = show_bits(&s->gb, 16);
if (get_bits_count(&s->gb) + 16 > active_bits_size)
v >>= get_bits_count(&s->gb) + 16 - active_bits_size;
if (!v)
ret = SLICE_END;
}
if (ret != SLICE_ERROR && active_bits_size < get_bits_count(&s->gb) &&
8 * buf_size2 >= get_bits_count(&s->gb)) {
active_bits_size = buf_size2 * 8;
av_log(avctx, AV_LOG_DEBUG, "update size from %d to %d\n",
8 * buf_size, active_bits_size);
ret = SLICE_OK;
}
if (ret == SLICE_ERROR || active_bits_size < get_bits_count(&s->gb)) {
av_log(s->avctx, AV_LOG_ERROR, "ERROR at MB %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
if (s->pict_type != AV_PICTURE_TYPE_B)
ff_h263_update_motion_val(s);
ff_MPV_decode_mb(s, s->block);
if (s->loop_filter)
ff_h263_loop_filter(s);
if (++s->mb_x == s->mb_width) {
s->mb_x = 0;
s->mb_y++;
ff_init_block_index(s);
}
if (s->mb_x == s->resync_mb_x)
s->first_slice_line = 0;
if (ret == SLICE_END)
break;
}
ff_er_add_slice(&s->er, start_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y,
ER_MB_END);
return active_bits_size;
}
static int get_slice_offset(AVCodecContext *avctx, const uint8_t *buf, int n)
{
if (avctx->slice_count)
return avctx->slice_offset[n];
else
return AV_RL32(buf + n * 8);
}
static int rv10_decode_frame(AVCodecContext *avctx,
void *data, int *got_frame,
AVPacket *avpkt)
{
const uint8_t *buf = avpkt->data;
int buf_size = avpkt->size;
MpegEncContext *s = avctx->priv_data;
AVFrame *pict = data;
int i, ret;
int slice_count;
const uint8_t *slices_hdr = NULL;
av_dlog(avctx, "*****frame %d size=%d\n", avctx->frame_number, buf_size);
s->flags = avctx->flags;
s->flags2 = avctx->flags2;
/* no supplementary picture */
if (buf_size == 0) {
return 0;
}
if (!avctx->slice_count) {
slice_count = (*buf++) + 1;
buf_size--;
if (!slice_count || buf_size <= 8 * slice_count) {
av_log(avctx, AV_LOG_ERROR, "Invalid slice count: %d.\n", slice_count);
return AVERROR_INVALIDDATA;
}
slices_hdr = buf + 4;
buf += 8 * slice_count;
buf_size -= 8 * slice_count;
} else
slice_count = avctx->slice_count;
for (i = 0; i < slice_count; i++) {
unsigned offset = get_slice_offset(avctx, slices_hdr, i);
int size, size2;
if (offset >= buf_size)
return AVERROR_INVALIDDATA;
if (i + 1 == slice_count)
size = buf_size - offset;
else
size = get_slice_offset(avctx, slices_hdr, i + 1) - offset;
if (i + 2 >= slice_count)
size2 = buf_size - offset;
else
size2 = get_slice_offset(avctx, slices_hdr, i + 2) - offset;
if (size <= 0 || size2 <= 0 ||
offset + FFMAX(size, size2) > buf_size)
return AVERROR_INVALIDDATA;
if (rv10_decode_packet(avctx, buf + offset, size, size2) > 8 * size)
i++;
}
if (s->current_picture_ptr != NULL && s->mb_y >= s->mb_height) {
ff_er_frame_end(&s->er);
ff_MPV_frame_end(s);
if (s->pict_type == AV_PICTURE_TYPE_B || s->low_delay) {
if ((ret = av_frame_ref(pict, &s->current_picture_ptr->f)) < 0)
return ret;
ff_print_debug_info(s, s->current_picture_ptr, pict);
ff_mpv_export_qp_table(s, pict, s->current_picture_ptr, FF_QSCALE_TYPE_MPEG1);
} else if (s->last_picture_ptr != NULL) {
if ((ret = av_frame_ref(pict, &s->last_picture_ptr->f)) < 0)
return ret;
ff_print_debug_info(s, s->last_picture_ptr, pict);
ff_mpv_export_qp_table(s, pict,s->last_picture_ptr, FF_QSCALE_TYPE_MPEG1);
}
if (s->last_picture_ptr || s->low_delay) {
*got_frame = 1;
}
// so we can detect if frame_end was not called (find some nicer solution...)
s->current_picture_ptr = NULL;
}
return avpkt->size;
}
AVCodec ff_rv10_decoder = {
.name = "rv10",
.long_name = NULL_IF_CONFIG_SMALL("RealVideo 1.0"),
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_RV10,
.priv_data_size = sizeof(RVDecContext),
.init = rv10_decode_init,
.close = rv10_decode_end,
.decode = rv10_decode_frame,
.capabilities = CODEC_CAP_DR1,
.max_lowres = 3,
.pix_fmts = ff_pixfmt_list_420,
};
AVCodec ff_rv20_decoder = {
.name = "rv20",
.long_name = NULL_IF_CONFIG_SMALL("RealVideo 2.0"),
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_RV20,
.priv_data_size = sizeof(RVDecContext),
.init = rv10_decode_init,
.close = rv10_decode_end,
.decode = rv10_decode_frame,
.capabilities = CODEC_CAP_DR1 | CODEC_CAP_DELAY,
.flush = ff_mpeg_flush,
.max_lowres = 3,
.pix_fmts = ff_pixfmt_list_420,
};
|
617302.c | int main() {
int foo = 1;
int bar = 2 + 3;
return foo + bar;
} |
457150.c | /*
* $Id: pa_mac_hostapis.c 1097 2006-08-26 08:27:53Z rossb $
* Portable Audio I/O Library Macintosh initialization table
*
* Based on the Open Source API proposed by Ross Bencina
* Copyright (c) 1999-2002 Ross Bencina, Phil Burk
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup macosx_src
Mac OS host API initialization function table.
*/
#include "pa_hostapi.h"
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
PaError PaSkeleton_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
PaError PaMacSm_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
PaError PaJack_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
PaError PaMacAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
#ifdef __cplusplus
}
#endif /* __cplusplus */
PaUtilHostApiInitializer *paHostApiInitializers[] =
{
#ifdef PA_USE_COREAUDIO
PaMacCore_Initialize,
#endif
#ifdef PA_USE_SM
PaMacSm_Initialize,
#endif
#ifdef PA_USE_JACK
PaJack_Initialize,
#endif
#ifdef PA_USE_ASIO
PaMacAsio_Initialize,
#endif
PaSkeleton_Initialize, /* just for testing */
0 /* NULL terminated array */
};
int paDefaultHostApiIndex = 0;
|
470616.c | /*
* Copyright (c) 2014-2021, Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
//!
//! \file mhw_utilities.c
//! \brief This modules implements utilities which are shared by both the HW interface and the state heap interface.
//!
#include "mhw_utilities.h"
#include "mhw_render.h"
#include "mhw_state_heap.h"
#include "hal_oca_interface.h"
#include "mos_interface.h"
#include "mhw_mi_itf.h"
#define MHW_NS_PER_TICK_RENDER_ENGINE 80 // 80 nano seconds per tick in render engine
//!
//! \brief Set mocs index
//! \details Set mocs index
//! command buffer or indirect state
//! \param PMOS_INTERFACE osInterface
//! [in] OS interface
//! \param PMOS_RESOURCE resource
//! [in] resource
//! \param MHW_MOCS_PARAMS &mocsParams
//! [in] mocsParams
//! \return MOS_STATUS
//! MOS_STATUS_SUCCESS if success, else fail reason
//!
MOS_STATUS Mhw_SetMocsTableIndex(
PMOS_INTERFACE osInterface,
PMOS_RESOURCE resource,
MHW_MOCS_PARAMS &mocsParams)
{
MHW_CHK_NULL_RETURN(resource);
MHW_CHK_NULL_RETURN(osInterface);
// Index is defined in bit 1:6
const uint8_t indexBitFieldLow = 1;
const uint8_t indexMask = 0x3F;
auto memObjCtrlState = resource->memObjCtrlState;
uint32_t memObjCtrlStateValue = 0;
uint32_t *data = mocsParams.mocsTableIndex;
uint32_t value = 0;
uint32_t mask = 0;
uint8_t bitFieldLow = mocsParams.bitFieldLow;
uint8_t bitFieldHigh = mocsParams.bitFieldHigh;
if (data == nullptr)
{
MHW_NORMALMESSAGE("skip to set the mocs");
return MOS_STATUS_SUCCESS;
}
if (bitFieldLow > bitFieldHigh || bitFieldHigh > 31)
{
MOS_OS_ASSERTMESSAGE("invalid bit field");
return MOS_STATUS_INVALID_PARAMETER;
}
value = *data;
if (resource->mocsMosResUsageType == MOS_CODEC_RESOURCE_USAGE_BEGIN_CODEC ||
resource->mocsMosResUsageType >= MOS_HW_RESOURCE_USAGE_MEDIA_BATCH_BUFFERS ||
resource->memObjCtrlState.DwordValue == 0)
{
MHW_NORMALMESSAGE("Invalid resource->mocsMosResUsageType = %d, use default cache MOS_MP_RESOURCE_USAGE_DEFAULT", resource->mocsMosResUsageType);
auto gmmClientContext = osInterface->pfnGetGmmClientContext(osInterface);
memObjCtrlState = MosInterface::GetCachePolicyMemoryObject(gmmClientContext, MOS_MP_RESOURCE_USAGE_DEFAULT);
}
memObjCtrlStateValue = (memObjCtrlState.DwordValue >> indexBitFieldLow) & indexMask;
if (bitFieldHigh == 31)
{
mask = (1 << bitFieldLow) - 1;
}
else
{
mask = (~((1 << (bitFieldHigh + 1)) - 1)) | ((1 << bitFieldLow) - 1);
}
value = value & mask;
*data = value | (memObjCtrlStateValue << bitFieldLow);
return MOS_STATUS_SUCCESS;
}
//!
//! \brief Adds graphics address of a resource to the command buffer or indirect state
//! \details Internal MHW function to add the graphics address of resources to the
//! command buffer or indirect state
//! \param PMOS_INTERFACE pOsInterface
//! [in] OS interface
//! \param PMOS_COMMAND_BUFFER pCmdBuffer
//! [in] Command buffer
//! \param PMHW_RESOURCE_PARAMS pParams
//! [in] Parameters necessary to insert the graphics address
//! \return MOS_STATUS
//! MOS_STATUS_SUCCESS if success, else fail reason
//!
MOS_STATUS Mhw_AddResourceToCmd_GfxAddress(
PMOS_INTERFACE pOsInterface,
PMOS_COMMAND_BUFFER pCmdBuffer,
PMHW_RESOURCE_PARAMS pParams)
{
uint32_t dwAlign, dwMask;
uint32_t dwGfxAddrBottom, dwGfxAddrTop = 0;
uint64_t ui64GfxAddress, ui64GfxAddressUpperBound;
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
int32_t iAllocationIndex = 0;
uint32_t uiPatchOffset = 0;
uint8_t *pbCmdBufBase = nullptr;
MHW_CHK_NULL(pOsInterface);
MHW_CHK_NULL(pParams);
MHW_CHK_NULL(pParams->presResource);
MHW_CHK_NULL(pCmdBuffer);
MHW_CHK_NULL(pCmdBuffer->pCmdBase);
pbCmdBufBase = (uint8_t*)pCmdBuffer->pCmdBase;
MHW_CHK_STATUS(pOsInterface->pfnRegisterResource(
pOsInterface,
pParams->presResource,
pParams->bIsWritable ? true : false,
pParams->bIsWritable ? true : false));
dwAlign = ( 1 << pParams->dwLsbNum);
dwMask = (-1 << pParams->dwLsbNum);
pParams->dwOffset = MOS_ALIGN_CEIL(pParams->dwOffset, dwAlign);
ui64GfxAddress =
pOsInterface->pfnGetResourceGfxAddress(pOsInterface, pParams->presResource) + pParams->dwOffset;
MHW_CHK_COND(ui64GfxAddress == 0, "Driver can't add resource with ui64GfxAddress == 0. DW location in cmd == %d.", pParams->dwLocationInCmd);
dwGfxAddrBottom = (uint32_t)(ui64GfxAddress & 0x00000000FFFFFFFF);
dwGfxAddrTop = (uint32_t)((ui64GfxAddress & 0xFFFFFFFF00000000) >> 32);
*pParams->pdwCmd = (*pParams->pdwCmd & ~dwMask) | (dwGfxAddrBottom & dwMask);
// this is next DW for top part of the address
*(pParams->pdwCmd + 1) = dwGfxAddrTop;
Mhw_SetMocsTableIndex(pOsInterface, pParams->presResource, pParams->mocsParams);
#if (_DEBUG || _RELEASE_INTERNAL)
{
uint32_t evtData[4] ={(uint32_t)pParams->HwCommandType, pParams->dwLocationInCmd, pParams->dwOffset, pParams->dwSize};
MOS_TraceEventExt(EVENT_RESOURCE_REGISTER, EVENT_TYPE_INFO2, evtData, sizeof(evtData), &ui64GfxAddress, sizeof(ui64GfxAddress));
}
#endif
if (pParams->dwOffsetInSSH > 0)
{
// Calculate the patch offset to command buffer
uiPatchOffset = pParams->dwOffsetInSSH + (pParams->dwLocationInCmd * sizeof(uint32_t));
}
else
{
// Calculate the patch offset to command buffer
uiPatchOffset = pCmdBuffer->iOffset + (pParams->dwLocationInCmd * sizeof(uint32_t));
}
MOS_PATCH_ENTRY_PARAMS PatchEntryParams;
iAllocationIndex = pOsInterface->pfnGetResourceAllocationIndex(pOsInterface, pParams->presResource);
MOS_ZeroMemory(&PatchEntryParams, sizeof(PatchEntryParams));
PatchEntryParams.uiAllocationIndex = iAllocationIndex;
PatchEntryParams.uiResourceOffset = pParams->dwOffset;
PatchEntryParams.uiPatchOffset = uiPatchOffset;
PatchEntryParams.bWrite = pParams->bIsWritable;
PatchEntryParams.HwCommandType = pParams->HwCommandType;
PatchEntryParams.forceDwordOffset = pParams->dwSharedMocsOffset;
PatchEntryParams.cmdBufBase = pbCmdBufBase;
PatchEntryParams.presResource = pParams->presResource;
// Add patch entry
MHW_CHK_STATUS(pOsInterface->pfnSetPatchEntry(
pOsInterface,
&PatchEntryParams));
if (pParams->dwUpperBoundLocationOffsetFromCmd > 0)
{
pParams->dwSize = MOS_ALIGN_CEIL(pParams->dwSize, dwAlign);
ui64GfxAddressUpperBound = ui64GfxAddress + pParams->dwSize;
dwGfxAddrBottom = (uint32_t)(ui64GfxAddressUpperBound & 0x00000000FFFFFFFF);
dwGfxAddrTop = (uint32_t)((ui64GfxAddressUpperBound & 0xFFFFFFFF00000000) >> 32);
pParams->pdwCmd += pParams->dwUpperBoundLocationOffsetFromCmd;
*pParams->pdwCmd = (*pParams->pdwCmd & ~dwMask) | (dwGfxAddrBottom & dwMask);
// this is next DW for top part of the address
*(pParams->pdwCmd + 1) = dwGfxAddrTop;
MOS_PATCH_ENTRY_PARAMS PatchEntryParams;
// Calculate the patch offset to command buffer
uiPatchOffset += pParams->dwUpperBoundLocationOffsetFromCmd * sizeof(uint32_t);
MOS_ZeroMemory(&PatchEntryParams, sizeof(PatchEntryParams));
PatchEntryParams.uiAllocationIndex = iAllocationIndex;
PatchEntryParams.uiResourceOffset = pParams->dwOffset + pParams->dwSize;
PatchEntryParams.uiPatchOffset = uiPatchOffset;
PatchEntryParams.bUpperBoundPatch = true;
PatchEntryParams.presResource = pParams->presResource;
// Add patch entry (CP won't register this patch point since bUpperBoundPatch = true)
MHW_CHK_STATUS(pOsInterface->pfnSetPatchEntry(
pOsInterface,
&PatchEntryParams));
}
if (MOS_VEBOX_STATE == pParams->HwCommandType ||
MOS_VEBOX_DI_IECP == pParams->HwCommandType ||
MOS_VEBOX_TILING_CONVERT == pParams->HwCommandType ||
MOS_SFC_STATE == pParams->HwCommandType ||
MOS_STATE_BASE_ADDR == pParams->HwCommandType ||
MOS_SURFACE_STATE == pParams->HwCommandType ||
MOS_SURFACE_STATE_ADV == pParams->HwCommandType ||
MOS_MFX_PIPE_BUF_ADDR == pParams->HwCommandType ||
MOS_MFX_VP8_PIC == pParams->HwCommandType ||
MOS_MFX_BSP_BUF_BASE_ADDR == pParams->HwCommandType ||
MOS_MFX_INDIRECT_OBJ_BASE_ADDR == pParams->HwCommandType ||
MOS_MI_BATCH_BUFFER_START == pParams->HwCommandType)
{
HalOcaInterface::DumpResourceInfo(*pCmdBuffer, *pOsInterface, *pParams->presResource, pParams->HwCommandType,
pParams->dwLocationInCmd, pParams->dwOffset);
}
finish:
return eStatus;
}
//!
//! \brief Adds resources to a patch list
//! \details Internal MHW function to put resources to be added to the command
//! buffer or indirect state into a patch list for patch later
//! \param PMOS_INTERFACE pOsInterface
//! [in] OS interface
//! \param PMOS_COMMAND_BUFFER pCmdBuffer
//! [in] Command buffer
//! \param PMHW_RESOURCE_PARAMS pParams
//! [in] Parameters necessary to add the resource to the patch list
//! \return MOS_STATUS
//! MOS_STATUS_SUCCESS if success, else fail reason
//!
MOS_STATUS Mhw_AddResourceToCmd_PatchList(
PMOS_INTERFACE pOsInterface,
PMOS_COMMAND_BUFFER pCmdBuffer,
PMHW_RESOURCE_PARAMS pParams)
{
MOS_GPU_CONTEXT GpuContext;
int32_t iAllocationIndex;
uint32_t dwLsbNum, dwUpperBoundOffset;
uint32_t dwOffset;
uint32_t uiPatchOffset;
MOS_PATCH_ENTRY_PARAMS PatchEntryParams;
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
MHW_CHK_NULL(pOsInterface);
MHW_CHK_NULL(pParams);
MHW_CHK_NULL(pParams->presResource);
MHW_CHK_NULL(pCmdBuffer);
MOS_TraceEventExt(EVENT_RESOURCE_REGISTER, EVENT_TYPE_INFO2, &pParams->HwCommandType, sizeof(uint32_t), &pParams->dwLocationInCmd, sizeof(uint32_t));
MHW_CHK_STATUS(pOsInterface->pfnRegisterResource(
pOsInterface,
pParams->presResource,
pParams->bIsWritable ? true : false,
pParams->bIsWritable ? true : false));
GpuContext = pOsInterface->pfnGetGpuContext(pOsInterface);
iAllocationIndex = pOsInterface->pfnGetResourceAllocationIndex(pOsInterface, pParams->presResource);
dwLsbNum = pParams->dwLsbNum;
// Offset and command LSB parameters
dwOffset = pParams->dwOffset | ((*pParams->pdwCmd) & ((1 << dwLsbNum) - 1));
if (pParams->dwOffsetInSSH > 0)
{
// Calculate the patch offset to command buffer
uiPatchOffset = pParams->dwOffsetInSSH + (pParams->dwLocationInCmd * sizeof(uint32_t));
}
else
{
// Calculate the patch offset to command buffer
uiPatchOffset = pCmdBuffer->iOffset + (pParams->dwLocationInCmd * sizeof(uint32_t));
}
MOS_ZeroMemory(&PatchEntryParams, sizeof(PatchEntryParams));
PatchEntryParams.uiAllocationIndex = iAllocationIndex;
if(pParams->patchType == MOS_PATCH_TYPE_UV_Y_OFFSET ||
pParams->patchType == MOS_PATCH_TYPE_PITCH ||
pParams->patchType == MOS_PATCH_TYPE_V_Y_OFFSET)
{
PatchEntryParams.uiResourceOffset = *pParams->pdwCmd;
}
else
{
PatchEntryParams.uiResourceOffset = dwOffset;
}
PatchEntryParams.uiPatchOffset = uiPatchOffset;
PatchEntryParams.bWrite = pParams->bIsWritable;
PatchEntryParams.HwCommandType = pParams->HwCommandType;
PatchEntryParams.forceDwordOffset = pParams->dwSharedMocsOffset;
PatchEntryParams.cmdBufBase = (uint8_t*)pCmdBuffer->pCmdBase;
PatchEntryParams.presResource = pParams->presResource;
PatchEntryParams.patchType = pParams->patchType;
PatchEntryParams.shiftAmount = pParams->shiftAmount;
PatchEntryParams.shiftDirection = pParams->shiftDirection;
PatchEntryParams.offsetInSSH = pParams->dwOffsetInSSH;
PatchEntryParams.cmdBuffer = pCmdBuffer;
// Add patch entry to patch the address field for this command
MHW_CHK_STATUS(pOsInterface->pfnSetPatchEntry(
pOsInterface,
&PatchEntryParams));
if (pParams->dwUpperBoundLocationOffsetFromCmd > 0)
{
pParams->pdwCmd += pParams->dwUpperBoundLocationOffsetFromCmd;
dwUpperBoundOffset = pParams->dwUpperBoundLocationOffsetFromCmd;
// Offset and command LSB parameters
dwOffset = MOS_ALIGN_CEIL((pParams->dwOffset + pParams->dwSize), (1 << dwLsbNum));
dwOffset = dwOffset | ((*pParams->pdwCmd) & ((1 << dwLsbNum) - 1));
// Calculate the patch offset to command buffer
uiPatchOffset += dwUpperBoundOffset * sizeof(uint32_t);
MOS_ZeroMemory(&PatchEntryParams, sizeof(PatchEntryParams));
PatchEntryParams.uiAllocationIndex = iAllocationIndex;
PatchEntryParams.uiResourceOffset = dwOffset;
PatchEntryParams.uiPatchOffset = uiPatchOffset;
PatchEntryParams.bUpperBoundPatch = true;
PatchEntryParams.presResource = pParams->presResource;
PatchEntryParams.patchType = pParams->patchType;
PatchEntryParams.shiftAmount = pParams->shiftAmount;
PatchEntryParams.shiftDirection = pParams->shiftDirection;
PatchEntryParams.offsetInSSH = pParams->dwOffsetInSSH;
PatchEntryParams.cmdBuffer = pCmdBuffer;
if(dwLsbNum)
{
PatchEntryParams.shiftAmount = dwLsbNum;
PatchEntryParams.shiftDirection = 0;
}
// Add patch entry to patch the address field for this command
MHW_CHK_STATUS(pOsInterface->pfnSetPatchEntry(
pOsInterface,
&PatchEntryParams));
}
if (MOS_VEBOX_STATE == pParams->HwCommandType ||
MOS_VEBOX_DI_IECP == pParams->HwCommandType ||
MOS_VEBOX_TILING_CONVERT == pParams->HwCommandType ||
MOS_SFC_STATE == pParams->HwCommandType ||
MOS_STATE_BASE_ADDR == pParams->HwCommandType ||
MOS_SURFACE_STATE == pParams->HwCommandType ||
MOS_SURFACE_STATE_ADV == pParams->HwCommandType ||
MOS_MFX_PIPE_BUF_ADDR == pParams->HwCommandType ||
MOS_MFX_VP8_PIC == pParams->HwCommandType ||
MOS_MFX_BSP_BUF_BASE_ADDR == pParams->HwCommandType ||
MOS_MFX_INDIRECT_OBJ_BASE_ADDR == pParams->HwCommandType ||
MOS_MI_BATCH_BUFFER_START == pParams->HwCommandType)
{
HalOcaInterface::DumpResourceInfo(*pCmdBuffer, *pOsInterface, *pParams->presResource, pParams->HwCommandType,
pParams->dwLocationInCmd, pParams->dwOffset);
}
finish:
return eStatus;
}
//!
//! \brief Derive Surface Type from Surface Format
//! \details Internal MHW function to dervie surface type from surface format
//! \param uint32_t dwForceSurfaceFormat
//! [in] surface format information
//! \param PMOS_SURFACE psSurface
//! [in] surface which have depth information
//! \param uint32_t* pdwSurfaceType
//! [out] Surface type
//! \return MOS_STATUS
//! MOS_STATUS_SUCCESS if success, else fail reason
//!
MOS_STATUS Mhw_SurfaceFormatToType(
uint32_t dwForceSurfaceFormat,
PMOS_SURFACE psSurface,
uint32_t *pdwSurfaceType)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
MHW_FUNCTION_ENTER;
MHW_CHK_NULL(psSurface);
MHW_CHK_NULL(pdwSurfaceType);
switch ( dwForceSurfaceFormat )
{
// 1D Surface
case MHW_GFX3DSTATE_SURFACEFORMAT_RAW:
case MHW_GFX3DSTATE_SURFACEFORMAT_R32_UINT:
case MHW_GFX3DSTATE_SURFACEFORMAT_L8_UNORM:
*pdwSurfaceType = GFX3DSTATE_SURFACETYPE_BUFFER;
break;
// 2D Surface for Codec: GFX3DSTATE_SURFACEFORMAT_YCRCB_NORMAL, GFX3DSTATE_SURFACEFORMAT_YCRCB_SWAPY
// GFX3DSTATE_SURFACEFORMAT_R32_UNORM, GFX3DSTATE_SURFACEFORMAT_R16_UNORM, GFX3DSTATE_SURFACEFORMAT_R8_UNORM
// 2D & 3D Surface
default:
(psSurface->dwDepth > 1) ?
*pdwSurfaceType = GFX3DSTATE_SURFACETYPE_3D:
*pdwSurfaceType = GFX3DSTATE_SURFACETYPE_2D;
}
finish:
return eStatus;
}
//!
//! \brief Inserts the generic prologue command for a command buffer
//! \details Client facing function to add the generic prologue commands:
//! - the command buffer header (if necessary)
//! - flushes for the read/write caches (MI_FLUSH_DW or PIPE_CONTROL)
//! - CP prologue if necessary
//! \param PMOS_COMMAND_BUFFER pCmdBuffer
//! [in] Command buffer
//! \param PMHW_GENERIC_PROLOG_PARAMS pParams
//! [in] Parameters necessary to add the generic prologue commands
//! \return MOS_STATUS
//! MOS_STATUS_SUCCESS if success, else fail reason
//!
MOS_STATUS Mhw_SendGenericPrologCmd(
PMOS_COMMAND_BUFFER pCmdBuffer,
PMHW_GENERIC_PROLOG_PARAMS pParams,
MHW_MI_MMIOREGISTERS *pMmioReg)
{
PMOS_INTERFACE pOsInterface;
MhwMiInterface *pMiInterface;
MEDIA_FEATURE_TABLE *pSkuTable;
MEDIA_WA_TABLE *pWaTable;
MOS_GPU_CONTEXT GpuContext;
MHW_PIPE_CONTROL_PARAMS PipeControlParams;
MHW_MI_FLUSH_DW_PARAMS FlushDwParams;
bool bRcsEngineUsed = false;
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
MHW_FUNCTION_ENTER;
MHW_CHK_NULL(pCmdBuffer);
MHW_CHK_NULL(pParams);
MHW_CHK_NULL(pParams->pOsInterface);
pOsInterface = pParams->pOsInterface;
MHW_CHK_NULL(pParams->pvMiInterface);
pMiInterface = (MhwMiInterface *)pParams->pvMiInterface;
MHW_CHK_NULL(pMiInterface);
pSkuTable = pOsInterface->pfnGetSkuTable(pOsInterface);
MHW_CHK_NULL(pSkuTable);
pWaTable = pOsInterface->pfnGetWaTable(pOsInterface);
MHW_CHK_NULL(pWaTable);
GpuContext = pOsInterface->pfnGetGpuContext(pOsInterface);
if ( pOsInterface->Component != COMPONENT_CM )
{
if ( GpuContext == MOS_GPU_CONTEXT_RENDER ||
GpuContext == MOS_GPU_CONTEXT_RENDER2 ||
GpuContext == MOS_GPU_CONTEXT_RENDER3 ||
GpuContext == MOS_GPU_CONTEXT_RENDER4 ||
GpuContext == MOS_GPU_CONTEXT_VIDEO ||
GpuContext == MOS_GPU_CONTEXT_VIDEO2 ||
GpuContext == MOS_GPU_CONTEXT_VIDEO3 ||
GpuContext == MOS_GPU_CONTEXT_VIDEO4 ||
GpuContext == MOS_GPU_CONTEXT_VDBOX2_VIDEO ||
GpuContext == MOS_GPU_CONTEXT_VDBOX2_VIDEO2 ||
GpuContext == MOS_GPU_CONTEXT_VDBOX2_VIDEO3 ||
GpuContext == MOS_GPU_CONTEXT_VEBOX ||
GpuContext == MOS_GPU_CONTEXT_VIDEO5 ||
GpuContext == MOS_GPU_CONTEXT_VIDEO6 ||
GpuContext == MOS_GPU_CONTEXT_VIDEO7 )
{
MHW_CHK_STATUS(pMiInterface->AddWatchdogTimerStartCmd(pCmdBuffer));
}
}
bRcsEngineUsed = MOS_RCS_ENGINE_USED(GpuContext);
if (bRcsEngineUsed)
{
MOS_ZeroMemory(&PipeControlParams, sizeof(PipeControlParams));
PipeControlParams.dwFlushMode = MHW_FLUSH_WRITE_CACHE;
MHW_CHK_STATUS(pMiInterface->AddPipeControl(
pCmdBuffer,
nullptr,
&PipeControlParams));
PipeControlParams.dwFlushMode = MHW_FLUSH_READ_CACHE;
PipeControlParams.presDest = pParams->presStoreData;
PipeControlParams.dwPostSyncOp = MHW_FLUSH_WRITE_IMMEDIATE_DATA;
PipeControlParams.dwResourceOffset = pParams->dwStoreDataOffset;
PipeControlParams.dwDataDW1 = pParams->dwStoreDataValue;
MHW_CHK_STATUS(pMiInterface->AddPipeControl(
pCmdBuffer,
nullptr,
&PipeControlParams));
if(pCmdBuffer->Attributes.bUmdSSEUEnable)
{
MHW_MI_LOAD_REGISTER_IMM_PARAMS MiLoadRegImmParams;
MHW_RENDER_PWR_CLK_STATE_PARAMS params;
MOS_ZeroMemory(¶ms, sizeof(params));
params.PowerClkStateEn = true;
params.SCountEn = true;
params.SSCountEn = true;
params.SliceCount = pCmdBuffer->Attributes.dwNumRequestedEUSlices;
params.SubSliceCount = pCmdBuffer->Attributes.dwNumRequestedSubSlices;
params.EUmax = pCmdBuffer->Attributes.dwNumRequestedEUs;
params.EUmin = pCmdBuffer->Attributes.dwNumRequestedEUs;
MOS_ZeroMemory(&MiLoadRegImmParams, sizeof(MiLoadRegImmParams));
MiLoadRegImmParams.dwRegister = MHW__PWR_CLK_STATE_REG;
MiLoadRegImmParams.dwData = params.Data;
MHW_CHK_STATUS(pMiInterface->AddMiLoadRegisterImmCmd(
pCmdBuffer,
&MiLoadRegImmParams));
}
}
else
{
// Send MI_FLUSH with protection bit off, which will FORCE exit protected mode for MFX
MOS_ZeroMemory(&FlushDwParams, sizeof(FlushDwParams));
FlushDwParams.bVideoPipelineCacheInvalidate = true;
FlushDwParams.pOsResource = pParams->presStoreData;
FlushDwParams.dwResourceOffset = pParams->dwStoreDataOffset;
FlushDwParams.dwDataDW1 = pParams->dwStoreDataValue;
MHW_CHK_STATUS(pMiInterface->AddMiFlushDwCmd(
pCmdBuffer,
&FlushDwParams));
}
MHW_CHK_STATUS(pMiInterface->AddProtectedProlog(pCmdBuffer));
if (pMmioReg)
{
HalOcaInterface::On1stLevelBBStart(
*pCmdBuffer,
*pOsInterface->pOsContext,
pOsInterface->CurrentGpuContextHandle,
*pMiInterface,
*pMmioReg);
}
finish:
return eStatus;
}
//!
//! \brief Inserts the generic prologue command for a command buffer
//! \details Client facing function to add the generic prologue commands:
//! - the command buffer header (if necessary)
//! - flushes for the read/write caches (MI_FLUSH_DW or PIPE_CONTROL)
//! - CP prologue if necessary
//! \param PMOS_COMMAND_BUFFER pCmdBuffer
//! [in] Command buffer
//! \param PMHW_GENERIC_PROLOG_PARAMS pParams
//! [in] Parameters necessary to add the generic prologue commands
//! \return MOS_STATUS
//! MOS_STATUS_SUCCESS if success, else fail reason
//!
MOS_STATUS Mhw_SendGenericPrologCmd_Next(
PMOS_COMMAND_BUFFER pCmdBuffer,
PMHW_GENERIC_PROLOG_PARAMS pParams,
MHW_MI_MMIOREGISTERS *pMmioReg)
{
PMOS_INTERFACE pOsInterface;
MhwMiInterface *pMiInterface;
MEDIA_FEATURE_TABLE *pSkuTable;
MEDIA_WA_TABLE *pWaTable;
MOS_GPU_CONTEXT GpuContext;
bool bRcsEngineUsed = false;
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
std::shared_ptr<mhw::mi::Itf> miItf = nullptr;
MHW_FUNCTION_ENTER;
MHW_CHK_NULL(pCmdBuffer);
MHW_CHK_NULL(pParams);
MHW_CHK_NULL(pParams->pOsInterface);
pOsInterface = pParams->pOsInterface;
MHW_CHK_NULL(pParams->pvMiInterface);
pMiInterface = (MhwMiInterface *)pParams->pvMiInterface;
MHW_CHK_NULL(pMiInterface);
miItf = std::static_pointer_cast<mhw::mi::Itf>(pMiInterface->GetNewMiInterface());
if (miItf == nullptr)
{
return(Mhw_SendGenericPrologCmd(pCmdBuffer, pParams, pMmioReg));
}
pSkuTable = pOsInterface->pfnGetSkuTable(pOsInterface);
MHW_CHK_NULL(pSkuTable);
pWaTable = pOsInterface->pfnGetWaTable(pOsInterface);
MHW_CHK_NULL(pWaTable);
GpuContext = pOsInterface->pfnGetGpuContext(pOsInterface);
if (pOsInterface->Component != COMPONENT_CM)
{
if ( GpuContext == MOS_GPU_CONTEXT_RENDER ||
GpuContext == MOS_GPU_CONTEXT_RENDER2 ||
GpuContext == MOS_GPU_CONTEXT_RENDER3 ||
GpuContext == MOS_GPU_CONTEXT_RENDER4 ||
GpuContext == MOS_GPU_CONTEXT_VIDEO ||
GpuContext == MOS_GPU_CONTEXT_VIDEO2 ||
GpuContext == MOS_GPU_CONTEXT_VIDEO3 ||
GpuContext == MOS_GPU_CONTEXT_VIDEO4 ||
GpuContext == MOS_GPU_CONTEXT_VDBOX2_VIDEO ||
GpuContext == MOS_GPU_CONTEXT_VDBOX2_VIDEO2 ||
GpuContext == MOS_GPU_CONTEXT_VDBOX2_VIDEO3 ||
GpuContext == MOS_GPU_CONTEXT_VEBOX ||
GpuContext == MOS_GPU_CONTEXT_VIDEO5 ||
GpuContext == MOS_GPU_CONTEXT_VIDEO6 ||
GpuContext == MOS_GPU_CONTEXT_VIDEO7 )
{
MHW_CHK_STATUS(miItf->AddWatchdogTimerStartCmd(pCmdBuffer));
}
}
bRcsEngineUsed = MOS_RCS_ENGINE_USED(GpuContext);
if (bRcsEngineUsed)
{
auto &PipeControlParams = miItf->MHW_GETPAR_F(PIPE_CONTROL)();
PipeControlParams = {};
PipeControlParams.dwFlushMode = MHW_FLUSH_WRITE_CACHE;
MHW_CHK_STATUS(miItf->MHW_ADDCMD_F(PIPE_CONTROL)(pCmdBuffer));
PipeControlParams.dwFlushMode = MHW_FLUSH_READ_CACHE;
PipeControlParams.presDest = pParams->presStoreData;
PipeControlParams.dwPostSyncOp = MHW_FLUSH_WRITE_IMMEDIATE_DATA;
PipeControlParams.dwResourceOffset = pParams->dwStoreDataOffset;
PipeControlParams.dwDataDW1 = pParams->dwStoreDataValue;
MHW_CHK_STATUS(miItf->MHW_ADDCMD_F(PIPE_CONTROL)(pCmdBuffer));
if(pCmdBuffer->Attributes.bUmdSSEUEnable)
{
MHW_RENDER_PWR_CLK_STATE_PARAMS params = {};
params.PowerClkStateEn = true;
params.SCountEn = true;
params.SSCountEn = true;
params.SliceCount = pCmdBuffer->Attributes.dwNumRequestedEUSlices;
params.SubSliceCount = pCmdBuffer->Attributes.dwNumRequestedSubSlices;
params.EUmax = pCmdBuffer->Attributes.dwNumRequestedEUs;
params.EUmin = pCmdBuffer->Attributes.dwNumRequestedEUs;
//MHW_MI_LOAD_REGISTER_IMM_PARAMS MiLoadRegImmParams;
auto &MiLoadRegImmParams = miItf->MHW_GETPAR_F(MI_LOAD_REGISTER_IMM)();
MiLoadRegImmParams = {};
MiLoadRegImmParams.dwRegister = MHW__PWR_CLK_STATE_REG;
MiLoadRegImmParams.dwData = params.Data;
MHW_CHK_STATUS(miItf->MHW_ADDCMD_F(MI_LOAD_REGISTER_IMM)(pCmdBuffer));
}
}
else
{
// Send MI_FLUSH with protection bit off, which will FORCE exit protected mode for MFX
auto &FlushDwParams = miItf->MHW_GETPAR_F(MI_FLUSH_DW)();
FlushDwParams = {};
FlushDwParams.bVideoPipelineCacheInvalidate = true;
FlushDwParams.pOsResource = pParams->presStoreData;
FlushDwParams.dwResourceOffset = pParams->dwStoreDataOffset;
FlushDwParams.dwDataDW1 = pParams->dwStoreDataValue;
MHW_CHK_STATUS(miItf->MHW_ADDCMD_F(MI_FLUSH_DW)(pCmdBuffer));
}
MHW_CHK_STATUS(pMiInterface->AddProtectedProlog(pCmdBuffer));
if (pMmioReg)
{
HalOcaInterface::On1stLevelBBStart(
*pCmdBuffer,
*pOsInterface->pOsContext,
pOsInterface->CurrentGpuContextHandle,
*pMiInterface,
*pMmioReg);
}
finish:
return eStatus;
}
//!
//! \brief Sets Nearest Mode Table for Gen75/9, across SFC and Render engine to set the sampler states
//! \details This function sets Coefficients for Nearest Mode
//! \param int32_t* iCoefs
//! [out] Polyphase Table to fill
//! \param uint32_t dwPlane
//! [in] Number of Polyphase tables
//! \param bool bBalancedFilter
//! [in] If Filter is balanced, set true
//! \return MOS_STATUS
//! MOS_STATUS_SUCCESS if success, else fail reason
//!
MOS_STATUS Mhw_SetNearestModeTable(
int32_t *iCoefs,
uint32_t dwPlane,
bool bBalancedFilter)
{
uint32_t dwNumEntries;
uint32_t dwOffset;
uint32_t i;
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
MHW_FUNCTION_ENTER;
MHW_CHK_NULL(iCoefs);
if (dwPlane == MHW_GENERIC_PLANE || dwPlane == MHW_Y_PLANE)
{
dwNumEntries = NUM_POLYPHASE_Y_ENTRIES;
dwOffset = 3;
}
else // if (dwPlane == MHW_U_PLANE || dwPlane == MHW_V_PLANE)
{
dwNumEntries = NUM_POLYPHASE_UV_ENTRIES;
dwOffset = 1;
}
for (i = 0; i <= NUM_HW_POLYPHASE_TABLES / 2; i++)
{
iCoefs[i * dwNumEntries + dwOffset] = 0x40;
}
if (bBalancedFilter)
{
// Fix offset so that filter is balanced
for (i = (NUM_HW_POLYPHASE_TABLES / 2 + 1); i < NUM_HW_POLYPHASE_TABLES; i++)
{
iCoefs[i * dwNumEntries + dwOffset + 1] = 0x40;
}
}
finish:
return eStatus;
}
//!
//! \brief Calculate Polyphase tables for Y , across SFC and Render engine to set the sampler states
//! \details Calculate Polyphase tables for Y
//! This function uses 17 phases.
//! MHW_NUM_HW_POLYPHASE_TABLES reflects the phases to program coefficients in HW, and
//! NUM_POLYPHASE_TABLES reflects the number of phases used for internal calculations.
//! \param int32_t* iCoefs
//! [out] Polyphase Table to fill
//! \param float fScaleFactor
//! [in] Scaling factor
//! \param uint32_t dwPlane
//! [in] Plane Info
//! \param MOS_FORMAT srcFmt
//! [in] Source Format
//! \param float fHPStrength
//! [in] High Pass Strength
//! \param bool bUse8x8Filter
//! [in] is 8x8 Filter used
//! \param uint32_t dwHwPhase
//! [in] Number of phases in HW
//! \param float fLanczosT
//! [in] Lanczos factor
//! \return MOS_STATUS
//! MOS_STATUS_SUCCESS if success, else fail reason
//!
MOS_STATUS Mhw_CalcPolyphaseTablesY(
int32_t *iCoefs,
float fScaleFactor,
uint32_t dwPlane,
MOS_FORMAT srcFmt,
float fHPStrength,
bool bUse8x8Filter,
uint32_t dwHwPhase,
float fLanczosT)
{
uint32_t dwNumEntries;
uint32_t dwTableCoefUnit;
uint32_t i, j;
int32_t k;
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
float fPhaseCoefs[NUM_POLYPHASE_Y_ENTRIES];
float fPhaseCoefsCopy[NUM_POLYPHASE_Y_ENTRIES];
float fStartOffset;
float fHPFilter[3], fHPSum, fHPHalfPhase; // Only used for Y_PLANE
float fBase, fPos, fSumCoefs;
int32_t iCenterPixel;
int32_t iSumQuantCoefs;
MHW_FUNCTION_ENTER;
MHW_CHK_NULL(iCoefs);
MHW_ASSERT((dwHwPhase == MHW_NUM_HW_POLYPHASE_TABLES) || (dwHwPhase == NUM_HW_POLYPHASE_TABLES));
if (dwPlane == MHW_GENERIC_PLANE || dwPlane == MHW_Y_PLANE)
{
dwNumEntries = NUM_POLYPHASE_Y_ENTRIES;
}
else // if (dwPlane == MHW_U_PLANE || dwPlane == MHW_V_PLANE)
{
dwNumEntries = NUM_POLYPHASE_UV_ENTRIES;
}
MOS_ZeroMemory(fPhaseCoefs , sizeof(fPhaseCoefs));
MOS_ZeroMemory(fPhaseCoefsCopy, sizeof(fPhaseCoefsCopy));
dwTableCoefUnit = 1 << MHW_AVS_TBL_COEF_PREC;
iCenterPixel = dwNumEntries / 2 - 1;
fStartOffset = (float)(-iCenterPixel);
if ((IS_YUV_FORMAT(srcFmt) &&
dwPlane != MHW_U_PLANE &&
dwPlane != MHW_V_PLANE) ||
((IS_RGB32_FORMAT(srcFmt) ||
srcFmt == Format_Y410 ||
srcFmt == Format_AYUV) &&
dwPlane == MHW_Y_PLANE))
{
if (fScaleFactor < 1.0F)
{
fLanczosT = 4.0F;
}
else
{
fLanczosT = 8.0F;
}
}
else // if (dwPlane == MHW_U_PLANE || dwPlane == MHW_V_PLANE || (IS_RGB_FORMAT(srcFmt) && dwPlane != MHW_V_PLANE))
{
fLanczosT = 2.0F;
}
for (i = 0; i < dwHwPhase; i++)
{
fBase = fStartOffset - (float)i / (float)NUM_POLYPHASE_TABLES;
fSumCoefs = 0.0F;
for (j = 0; j < dwNumEntries; j++)
{
fPos = fBase + (float)j;
if (bUse8x8Filter)
{
fPhaseCoefs[j] = fPhaseCoefsCopy[j] = MosUtilities::MosLanczos(fPos * fScaleFactor, dwNumEntries, fLanczosT);
}
else
{
fPhaseCoefs[j] = fPhaseCoefsCopy[j] = MosUtilities::MosLanczosG(fPos * fScaleFactor, NUM_POLYPHASE_5x5_Y_ENTRIES, fLanczosT);
}
fSumCoefs += fPhaseCoefs[j];
}
// Convolve with HP
if (dwPlane == MHW_GENERIC_PLANE || dwPlane == MHW_Y_PLANE)
{
if (i <= NUM_POLYPHASE_TABLES / 2)
{
fHPHalfPhase = (float)i / (float)NUM_POLYPHASE_TABLES;
}
else
{
fHPHalfPhase = (float)(NUM_POLYPHASE_TABLES - i) / (float)NUM_POLYPHASE_TABLES;
}
fHPFilter[0] = fHPFilter[2] = -fHPStrength * MosUtilities::MosSinc(fHPHalfPhase * MOS_PI);
fHPFilter[1] = 1.0F + 2.0F * fHPStrength;
for (j = 0; j < dwNumEntries; j++)
{
fHPSum = 0.0F;
for (k = -1; k <= 1; k++)
{
if ((((long)j + k) >= 0) && (j + k < dwNumEntries))
{
fHPSum += fPhaseCoefsCopy[(int32_t)j+k] * fHPFilter[k+1];
}
fPhaseCoefs[j] = fHPSum;
}
}
}
// Normalize coefs and save
iSumQuantCoefs = 0;
for (j = 0; j < dwNumEntries; j++)
{
iCoefs[i * dwNumEntries + j] = (int32_t)floor(0.5F + (float)dwTableCoefUnit * fPhaseCoefs[j] / fSumCoefs);
iSumQuantCoefs += iCoefs[i * dwNumEntries + j];
}
// Fix center coef so that filter is balanced
if (i <= NUM_POLYPHASE_TABLES / 2)
{
iCoefs[i * dwNumEntries + iCenterPixel] -= iSumQuantCoefs - dwTableCoefUnit;
}
else
{
iCoefs[i * dwNumEntries + iCenterPixel + 1] -= iSumQuantCoefs - dwTableCoefUnit;
}
}
finish:
return eStatus;
}
//!
//! \brief Calculate Polyphase tables for UV for Gen9, across SFC and Render engine to set the sampler states
//! \details Calculate Polyphase tables for UV
//! \param int32_t* piCoefs
//! [out] Polyphase Table to fill
//! \param float fLanczosT
//! [in] Lanczos modifying factor
//! \param float fInverseScaleFactor
//! [in] Inverse scaling factor
//! \return MOS_STATUS
//! MOS_STATUS_SUCCESS if success, else fail reason
//!
MOS_STATUS Mhw_CalcPolyphaseTablesUV(
int32_t *piCoefs,
float fLanczosT,
float fInverseScaleFactor)
{
int32_t phaseCount, tableCoefUnit, centerPixel, sumQuantCoefs;
double phaseCoefs[MHW_SCALER_UV_WIN_SIZE];
double startOffset, sf, base, sumCoefs, pos;
int32_t minCoef[MHW_SCALER_UV_WIN_SIZE];
int32_t maxCoef[MHW_SCALER_UV_WIN_SIZE];
int32_t i, j;
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
MHW_FUNCTION_ENTER;
MHW_CHK_NULL(piCoefs);
phaseCount = MHW_TABLE_PHASE_COUNT;
centerPixel = (MHW_SCALER_UV_WIN_SIZE / 2) - 1;
startOffset = (double)(-centerPixel);
tableCoefUnit = 1 << MHW_TBL_COEF_PREC;
sf = MOS_MIN(1.0, fInverseScaleFactor); // Sf isn't used for upscaling
MOS_ZeroMemory(piCoefs, sizeof(int32_t) * MHW_SCALER_UV_WIN_SIZE * phaseCount);
MOS_ZeroMemory(minCoef, sizeof(minCoef));
MOS_ZeroMemory(maxCoef, sizeof(maxCoef));
if (sf < 1.0F)
{
fLanczosT = 2.0F;
}
for(i = 0; i < phaseCount; ++i, piCoefs += MHW_SCALER_UV_WIN_SIZE)
{
// Write all
// Note - to shift by a half you need to a half to each phase.
base = startOffset - (double)(i) / (double)(phaseCount);
sumCoefs = 0.0;
for(j = 0; j < MHW_SCALER_UV_WIN_SIZE; ++j)
{
pos = base + (double) j;
phaseCoefs[j] = MosUtilities::MosLanczos((float)(pos * sf), MHW_SCALER_UV_WIN_SIZE, fLanczosT);
sumCoefs += phaseCoefs[j];
}
// Normalize coefs and save
for(j = 0; j < MHW_SCALER_UV_WIN_SIZE; ++j)
{
piCoefs[j] = (int32_t) floor((0.5 + (double)(tableCoefUnit) * (phaseCoefs[j] / sumCoefs)));
//For debug purposes:
minCoef[j] = MOS_MIN(minCoef[j], piCoefs[j]);
maxCoef[j] = MOS_MAX(maxCoef[j], piCoefs[j]);
}
// Recalc center coef
sumQuantCoefs = 0;
for(j = 0; j < MHW_SCALER_UV_WIN_SIZE; ++j)
{
sumQuantCoefs += piCoefs[j];
}
// Fix center coef so that filter is balanced
if (i <= phaseCount/2)
{
piCoefs[centerPixel] -= sumQuantCoefs - tableCoefUnit;
}
else
{
piCoefs[centerPixel + 1] -= sumQuantCoefs - tableCoefUnit;
}
}
finish:
return eStatus;
}
//!
//! \brief Calculate polyphase tables UV offset for Gen9, across SFC and Render engine to set the sampler states
//! \details Calculate Polyphase tables for UV with chroma siting for
//! 420 to 444 conversion
//! \param int32_t* piCoefs
//! [out] Polyphase Table to fill
//! \param float fLanczosT
//! [in] Lanczos modifying factor
//! \param float fInverseScaleFactor
//! [in] Inverse scaling factor
//! \param int32_t iUvPhaseOffset
//! [in] UV Phase Offset
//! \return MOS_STATUS
//! MOS_STATUS_SUCCESS if success, else fail reason
//!
MOS_STATUS Mhw_CalcPolyphaseTablesUVOffset(
int32_t *piCoefs,
float fLanczosT,
float fInverseScaleFactor,
int32_t iUvPhaseOffset)
{
int32_t phaseCount, tableCoefUnit, centerPixel, sumQuantCoefs;
double phaseCoefs[MHW_SCALER_UV_WIN_SIZE];
double startOffset, sf, pos, sumCoefs, base;
int32_t minCoef[MHW_SCALER_UV_WIN_SIZE];
int32_t maxCoef[MHW_SCALER_UV_WIN_SIZE];
int32_t i, j;
int32_t adjusted_phase;
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
MHW_FUNCTION_ENTER;
MHW_CHK_NULL(piCoefs);
phaseCount = MHW_TABLE_PHASE_COUNT;
centerPixel = (MHW_SCALER_UV_WIN_SIZE / 2) - 1;
startOffset = (double)(-centerPixel +
(double)iUvPhaseOffset / (double)(phaseCount));
tableCoefUnit = 1 << MHW_TBL_COEF_PREC;
MOS_ZeroMemory(minCoef, sizeof(minCoef));
MOS_ZeroMemory(maxCoef, sizeof(maxCoef));
MOS_ZeroMemory(piCoefs, sizeof(int32_t)* MHW_SCALER_UV_WIN_SIZE * phaseCount);
sf = MOS_MIN(1.0, fInverseScaleFactor); // Sf isn't used for upscaling
if (sf < 1.0)
{
fLanczosT = 3.0;
}
for (i = 0; i < phaseCount; ++i, piCoefs += MHW_SCALER_UV_WIN_SIZE)
{
// Write all
// Note - to shift by a half you need to a half to each phase.
base = startOffset - (double)(i) / (double)(phaseCount);
sumCoefs = 0.0;
for (j = 0; j < MHW_SCALER_UV_WIN_SIZE; ++j)
{
pos = base + (double)j;
phaseCoefs[j] = MosUtilities::MosLanczos((float)(pos * sf), 6/*MHW_SCALER_UV_WIN_SIZE*/, fLanczosT);
sumCoefs += phaseCoefs[j];
}
// Normalize coefs and save
for (j = 0; j < MHW_SCALER_UV_WIN_SIZE; ++j)
{
piCoefs[j] = (int32_t)floor((0.5 + (double)(tableCoefUnit)* (phaseCoefs[j] / sumCoefs)));
// For debug purposes:
minCoef[j] = MOS_MIN(minCoef[j], piCoefs[j]);
maxCoef[j] = MOS_MAX(maxCoef[j], piCoefs[j]);
}
// Recalc center coef
sumQuantCoefs = 0;
for (j = 0; j < MHW_SCALER_UV_WIN_SIZE; ++j)
{
sumQuantCoefs += piCoefs[j];
}
// Fix center coef so that filter is balanced
adjusted_phase = i - iUvPhaseOffset;
if (adjusted_phase <= phaseCount / 2)
{
piCoefs[centerPixel] -= sumQuantCoefs - tableCoefUnit;
}
else // if(adjusted_phase < phaseCount)
{
piCoefs[centerPixel + 1] -= sumQuantCoefs - tableCoefUnit;
}
}
finish:
return eStatus;
}
//!
//! \brief Allocate BB
//! \details Allocated Batch Buffer
//! \param PMOS_INTERFACE pOsInterface
//! [in] Pointer to OS Interface
//! \param PMHW_BATCH_BUFFER pBatchBuffer
//! [in/out] Pointer to Batch Buffer
//! \param PMHW_BATCH_BUFFER pBatchBufferList
//! [in/out] If valid, represents the batch buffer list maintained by the client
//! \param uint32_t dwSize
//! [in] Sixe of the batch vuffer to be allocated
//! \param bool notLockable
//! [in] Indicate if the batch buffer not lockable, by default is false
//! \param bool inSystemMem
//! [in] Indicate if the batch buffer in system memory, by default is false
//! \return MOS_STATUS
//! true if the Batch Buffer was successfully allocated
//! false if failed
//!
MOS_STATUS Mhw_AllocateBb(
PMOS_INTERFACE pOsInterface,
PMHW_BATCH_BUFFER pBatchBuffer,
PMHW_BATCH_BUFFER pBatchBufferList,
uint32_t dwSize,
uint32_t batchCount,
bool notLockable,
bool inSystemMem)
{
MHW_FUNCTION_ENTER;
MOS_RESOURCE OsResource;
MOS_ALLOC_GFXRES_PARAMS AllocParams;
uint32_t allocSize;
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
MHW_CHK_NULL(pOsInterface);
MHW_CHK_NULL(pBatchBuffer);
MHW_ASSERT(!(notLockable && inSystemMem)); // Notlockable system memory doesn't make sense
dwSize += 8 * MHW_CACHELINE_SIZE;
dwSize = MOS_ALIGN_CEIL(dwSize, MOS_PAGE_SIZE);
allocSize = dwSize * batchCount;
MOS_ZeroMemory(&OsResource, sizeof(OsResource));
MOS_ZeroMemory(&AllocParams, sizeof(AllocParams));
AllocParams.Type = MOS_GFXRES_BUFFER;
AllocParams.TileType = MOS_TILE_LINEAR;
AllocParams.Format = Format_Buffer;
AllocParams.dwBytes = allocSize;
AllocParams.pBufName = "BatchBuffer";
AllocParams.ResUsageType = MOS_HW_RESOURCE_USAGE_MEDIA_BATCH_BUFFERS;
AllocParams.Flags.bNotLockable = notLockable ? 1 : 0;
if (notLockable)
{
AllocParams.dwMemType = MOS_MEMPOOL_DEVICEMEMORY;
}
else if (inSystemMem)
{
AllocParams.dwMemType = MOS_MEMPOOL_SYSTEMMEMORY;
}
else
{
AllocParams.dwMemType = MOS_MEMPOOL_VIDEOMEMORY;
}
MHW_CHK_STATUS(pOsInterface->pfnAllocateResource(
pOsInterface,
&AllocParams,
&OsResource));
// Reset Allocation
pOsInterface->pfnResetResourceAllocationIndex(pOsInterface, &OsResource);
pBatchBuffer->OsResource = OsResource;
pBatchBuffer->iSize = (int32_t)dwSize;
pBatchBuffer->count = batchCount;
pBatchBuffer->iRemaining = pBatchBuffer->iSize;
pBatchBuffer->iCurrent = 0;
pBatchBuffer->bLocked = false;
#if (_DEBUG || _RELEASE_INTERNAL)
pBatchBuffer->iLastCurrent = 0;
#endif
// Link BB for synchronization
pBatchBuffer->bBusy = false;
pBatchBuffer->dwCmdBufId = 0;
if (pBatchBufferList)
{
pBatchBuffer->pNext = pBatchBufferList;
pBatchBufferList = pBatchBuffer;
if (pBatchBuffer->pNext)
{
pBatchBuffer->pNext->pPrev = pBatchBuffer;
}
}
finish:
return eStatus;
}
//!
//! \brief Free BB
//! \details Frees Batch Buffer
//! \param PMOS_INTERFACE pOsInterface
//! [in] Pointer to OS Interface
//! \param PMHW_BATCH_BUFFER pBatchBuffer
//! [in] Pointer to Batch Buffer
//! \param PMHW_BATCH_BUFFER pBatchBufferList
//! [in/out] If valid, represents the batch buffer list maintained by the client
//! \return MOS_STATUS
//!
MOS_STATUS Mhw_FreeBb(
PMOS_INTERFACE pOsInterface,
PMHW_BATCH_BUFFER pBatchBuffer,
PMHW_BATCH_BUFFER pBatchBufferList)
{
MHW_FUNCTION_ENTER;
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
MHW_CHK_NULL(pOsInterface);
MHW_CHK_NULL(pBatchBuffer);
if (pBatchBuffer->bLocked)
{
MHW_CHK_STATUS(Mhw_UnlockBb(pOsInterface, pBatchBuffer, true));
}
pOsInterface->pfnFreeResource(pOsInterface, &pBatchBuffer->OsResource);
pBatchBuffer->dwCmdBufId = 0;
pBatchBuffer->iSize = 0;
pBatchBuffer->count = 0;
pBatchBuffer->iCurrent = 0;
#if (_DEBUG || _RELEASE_INTERNAL)
pBatchBuffer->iLastCurrent = 0;
#endif
if (pBatchBufferList)
{
// Unlink BB from synchronization list
if (pBatchBuffer->pNext)
{
pBatchBuffer->pNext->pPrev = pBatchBuffer->pPrev;
}
if (pBatchBuffer->pPrev)
{
pBatchBuffer->pPrev->pNext = pBatchBuffer->pNext;
}
else
{
pBatchBufferList = pBatchBuffer->pNext;
}
pBatchBuffer->pPrev = pBatchBuffer->pNext = nullptr;
}
finish:
return eStatus;
}
//!
//! \brief Lock BB
//! \details Locks Batch Buffer
//! \param PMOS_INTERFACE pOsInterface
//! [in] Pointer to OS Interface
//! \param PMHW_BATCH_BUFFER pBatchBuffer
//! [in] Pointer to Batch Buffer
//! \return MOS_STATUS
//!
MOS_STATUS Mhw_LockBb(
PMOS_INTERFACE pOsInterface,
PMHW_BATCH_BUFFER pBatchBuffer)
{
MHW_FUNCTION_ENTER;
MOS_LOCK_PARAMS LockFlags;
MOS_STATUS eStatus;
MHW_CHK_NULL(pOsInterface);
MHW_CHK_NULL(pBatchBuffer);
eStatus = MOS_STATUS_UNKNOWN;
if (pBatchBuffer->bLocked)
{
MHW_ASSERTMESSAGE("Batch Buffer is already locked.");
goto finish;
}
MOS_ZeroMemory(&LockFlags, sizeof(MOS_LOCK_PARAMS));
LockFlags.WriteOnly = 1;
pBatchBuffer->pData = (uint8_t*)pOsInterface->pfnLockResource(
pOsInterface,
&pBatchBuffer->OsResource,
&LockFlags);
MHW_CHK_NULL(pBatchBuffer->pData);
pBatchBuffer->bLocked = true;
eStatus = MOS_STATUS_SUCCESS;
finish:
return eStatus;
}
//!
//! \brief Unlock BB
//! \details Unlocks Batch Buffer
//! \param PMOS_INTERFACE pOsInterface
//! [in] Pointer to OS Interface
//! \param PMHW_BATCH_BUFFER pBatchBuffer
//! [in] Pointer to Batch Buffer
//! \param bool bResetBuffer
//! [in] Reset BB information concerning current offset and size
//! \return MOS_STATUS
//!
MOS_STATUS Mhw_UnlockBb(
PMOS_INTERFACE pOsInterface,
PMHW_BATCH_BUFFER pBatchBuffer,
bool bResetBuffer)
{
MHW_FUNCTION_ENTER;
MOS_STATUS eStatus;
MHW_CHK_NULL(pOsInterface);
MHW_CHK_NULL(pBatchBuffer);
eStatus = MOS_STATUS_UNKNOWN;
if (!pBatchBuffer->bLocked)
{
MHW_ASSERTMESSAGE("Batch buffer is locked.");
goto finish;
}
if (bResetBuffer)
{
pBatchBuffer->iRemaining = pBatchBuffer->iSize;
pBatchBuffer->iCurrent = 0;
}
MHW_CHK_STATUS(pOsInterface->pfnUnlockResource(
pOsInterface,
&pBatchBuffer->OsResource));
pBatchBuffer->bLocked = false;
pBatchBuffer->pData = nullptr;
eStatus = MOS_STATUS_SUCCESS;
finish:
return eStatus;
}
//!
//! \brief Convert To Nano Seconds
//! \details Convert to Nano Seconds
//! \param PVPHAL_HW_int32_tERFACE pHwInterface
//! [in] Pointer to Hardware Interface Structure
//! \param uint64_t iTicks
//! [in] Ticks
//! \param uint64_t* piNs
//! [in] Nano Seconds
//! \return MOS_STATUS
//!
MOS_STATUS Mhw_ConvertToNanoSeconds(
uint64_t iTicks,
uint64_t *piNs)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
MHW_CHK_NULL(piNs);
*piNs = iTicks * MHW_NS_PER_TICK_RENDER_ENGINE;
finish:
return eStatus;
}
//!
//! \brief Convert Mos Tile Type to TR Mode
//! \details Convert Mos Tile Type to TR Mode
//! \param MOS_TILE_TYPE Type
//! [in] MOS tile type
//! \return uint32_t
//! Tile Resouece Mode
//!
uint32_t Mhw_ConvertToTRMode(MOS_TILE_TYPE Type)
{
switch (Type)
{
case MOS_TILE_YS:
return TRMODE_TILEYS;
case MOS_TILE_YF:
return TRMODE_TILEYF;
default:
return TRMODE_NONE;
}
}
|
834157.c | /*
* Copyright (c) 2000-2003 Fabrice Bellard
*
* 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
* multimedia converter based on the FFmpeg libraries
*/
#include "config.h"
#include <ctype.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include <stdatomic.h>
#include <stdint.h>
#if HAVE_IO_H
#include <io.h>
#endif
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#include "libavformat/avformat.h"
#include "libswresample/swresample.h"
#include "libavutil/opt.h"
#include "libavutil/channel_layout.h"
#include "libavutil/parseutils.h"
#include "libavutil/samplefmt.h"
#include "libavutil/fifo.h"
#include "libavutil/hwcontext.h"
#include "libavutil/internal.h"
#include "libavutil/intreadwrite.h"
#include "libavutil/dict.h"
#include "libavutil/display.h"
#include "libavutil/mathematics.h"
#include "libavutil/pixdesc.h"
#include "libavutil/avstring.h"
#include "libavutil/libm.h"
#include "libavutil/imgutils.h"
#include "libavutil/timestamp.h"
#include "libavutil/bprint.h"
#include "libavutil/time.h"
#include "libavutil/thread.h"
#include "libavutil/threadmessage.h"
#include "libavcodec/mathops.h"
#include "libavformat/os_support.h"
# include "libavfilter/avfilter.h"
# include "libavfilter/buffersrc.h"
# include "libavfilter/buffersink.h"
#if HAVE_SYS_RESOURCE_H
#include <sys/time.h>
#include <sys/types.h>
#include <sys/resource.h>
#elif HAVE_GETPROCESSTIMES
#include <windows.h>
#endif
#if HAVE_GETPROCESSMEMORYINFO
#include <windows.h>
#include <psapi.h>
#endif
#if HAVE_SETCONSOLECTRLHANDLER
#include <windows.h>
#endif
#if HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#if HAVE_TERMIOS_H
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <termios.h>
#elif HAVE_KBHIT
#include <conio.h>
#endif
#include <time.h>
#include "ffmpeg.h"
#include "cmdutils.h"
#include "libavutil/avassert.h"
#include <setjmp.h>
jmp_buf jump_buf;
const char program_name[] = "ffmpeg";
const int program_birth_year = 2000;
static FILE *vstats_file;
const char *const forced_keyframes_const_names[] = {
"n",
"n_forced",
"prev_forced_n",
"prev_forced_t",
"t",
NULL
};
typedef struct BenchmarkTimeStamps {
int64_t real_usec;
int64_t user_usec;
int64_t sys_usec;
} BenchmarkTimeStamps;
static void do_video_stats(OutputStream *ost, int frame_size);
static BenchmarkTimeStamps get_benchmark_time_stamps(void);
static int64_t getmaxrss(void);
static int ifilter_has_all_input_formats(FilterGraph *fg);
static int run_as_daemon = 0;
static int nb_frames_dup = 0;
static unsigned dup_warning = 1000;
static int nb_frames_drop = 0;
static int64_t decode_error_stat[2];
static int want_sdp = 1;
static BenchmarkTimeStamps current_time;
AVIOContext *progress_avio = NULL;
static uint8_t *subtitle_out;
InputStream **input_streams = NULL;
int nb_input_streams = 0;
InputFile **input_files = NULL;
int nb_input_files = 0;
OutputStream **output_streams = NULL;
int nb_output_streams = 0;
OutputFile **output_files = NULL;
int nb_output_files = 0;
FilterGraph **filtergraphs;
int nb_filtergraphs;
#if HAVE_TERMIOS_H
/* init terminal so that we can grab keys */
static struct termios oldtty;
static int restore_tty;
#endif
#if HAVE_THREADS
static void free_input_threads(void);
#endif
/* sub2video hack:
Convert subtitles to video with alpha to insert them in filter graphs.
This is a temporary solution until libavfilter gets real subtitles support.
*/
static int sub2video_get_blank_frame(InputStream *ist)
{
int ret;
AVFrame *frame = ist->sub2video.frame;
av_frame_unref(frame);
ist->sub2video.frame->width = ist->dec_ctx->width ? ist->dec_ctx->width : ist->sub2video.w;
ist->sub2video.frame->height = ist->dec_ctx->height ? ist->dec_ctx->height : ist->sub2video.h;
ist->sub2video.frame->format = AV_PIX_FMT_RGB32;
if ((ret = av_frame_get_buffer(frame, 32)) < 0)
return ret;
memset(frame->data[0], 0, frame->height * frame->linesize[0]);
return 0;
}
static void sub2video_copy_rect(uint8_t *dst, int dst_linesize, int w, int h,
AVSubtitleRect *r)
{
uint32_t *pal, *dst2;
uint8_t *src, *src2;
int x, y;
if (r->type != SUBTITLE_BITMAP) {
av_log(NULL, AV_LOG_WARNING, "sub2video: non-bitmap subtitle\n");
return;
}
if (r->x < 0 || r->x + r->w > w || r->y < 0 || r->y + r->h > h) {
av_log(NULL, AV_LOG_WARNING, "sub2video: rectangle (%d %d %d %d) overflowing %d %d\n",
r->x, r->y, r->w, r->h, w, h
);
return;
}
dst += r->y * dst_linesize + r->x * 4;
src = r->data[0];
pal = (uint32_t *)r->data[1];
for (y = 0; y < r->h; y++) {
dst2 = (uint32_t *)dst;
src2 = src;
for (x = 0; x < r->w; x++)
*(dst2++) = pal[*(src2++)];
dst += dst_linesize;
src += r->linesize[0];
}
}
static void sub2video_push_ref(InputStream *ist, int64_t pts)
{
AVFrame *frame = ist->sub2video.frame;
int i;
int ret;
av_assert1(frame->data[0]);
ist->sub2video.last_pts = frame->pts = pts;
for (i = 0; i < ist->nb_filters; i++) {
ret = av_buffersrc_add_frame_flags(ist->filters[i]->filter, frame,
AV_BUFFERSRC_FLAG_KEEP_REF |
AV_BUFFERSRC_FLAG_PUSH);
if (ret != AVERROR_EOF && ret < 0)
av_log(NULL, AV_LOG_WARNING, "Error while add the frame to buffer source(%s).\n",
av_err2str(ret));
}
}
void sub2video_update(InputStream *ist, AVSubtitle *sub)
{
AVFrame *frame = ist->sub2video.frame;
int8_t *dst;
int dst_linesize;
int num_rects, i;
int64_t pts, end_pts;
if (!frame)
return;
if (sub) {
pts = av_rescale_q(sub->pts + sub->start_display_time * 1000LL,
AV_TIME_BASE_Q, ist->st->time_base);
end_pts = av_rescale_q(sub->pts + sub->end_display_time * 1000LL,
AV_TIME_BASE_Q, ist->st->time_base);
num_rects = sub->num_rects;
} else {
pts = ist->sub2video.end_pts;
end_pts = INT64_MAX;
num_rects = 0;
}
if (sub2video_get_blank_frame(ist) < 0) {
av_log(ist->dec_ctx, AV_LOG_ERROR,
"Impossible to get a blank canvas.\n");
return;
}
dst = frame->data [0];
dst_linesize = frame->linesize[0];
for (i = 0; i < num_rects; i++)
sub2video_copy_rect(dst, dst_linesize, frame->width, frame->height, sub->rects[i]);
sub2video_push_ref(ist, pts);
ist->sub2video.end_pts = end_pts;
}
static void sub2video_heartbeat(InputStream *ist, int64_t pts)
{
InputFile *infile = input_files[ist->file_index];
int i, j, nb_reqs;
int64_t pts2;
/* When a frame is read from a file, examine all sub2video streams in
the same file and send the sub2video frame again. Otherwise, decoded
video frames could be accumulating in the filter graph while a filter
(possibly overlay) is desperately waiting for a subtitle frame. */
for (i = 0; i < infile->nb_streams; i++) {
InputStream *ist2 = input_streams[infile->ist_index + i];
if (!ist2->sub2video.frame)
continue;
/* subtitles seem to be usually muxed ahead of other streams;
if not, subtracting a larger time here is necessary */
pts2 = av_rescale_q(pts, ist->st->time_base, ist2->st->time_base) - 1;
/* do not send the heartbeat frame if the subtitle is already ahead */
if (pts2 <= ist2->sub2video.last_pts)
continue;
if (pts2 >= ist2->sub2video.end_pts ||
(!ist2->sub2video.frame->data[0] && ist2->sub2video.end_pts < INT64_MAX))
sub2video_update(ist2, NULL);
for (j = 0, nb_reqs = 0; j < ist2->nb_filters; j++)
nb_reqs += av_buffersrc_get_nb_failed_requests(ist2->filters[j]->filter);
if (nb_reqs)
sub2video_push_ref(ist2, pts2);
}
}
static void sub2video_flush(InputStream *ist)
{
int i;
int ret;
if (ist->sub2video.end_pts < INT64_MAX)
sub2video_update(ist, NULL);
for (i = 0; i < ist->nb_filters; i++) {
ret = av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
if (ret != AVERROR_EOF && ret < 0)
av_log(NULL, AV_LOG_WARNING, "Flush the frame error.\n");
}
}
/* end of sub2video hack */
static void term_exit_sigsafe(void)
{
#if HAVE_TERMIOS_H
if(restore_tty)
tcsetattr (0, TCSANOW, &oldtty);
#endif
}
void term_exit(void)
{
av_log(NULL, AV_LOG_QUIET, "%s", "");
term_exit_sigsafe();
}
static volatile int received_sigterm = 0;
static volatile int received_nb_signals = 0;
static atomic_int transcode_init_done = ATOMIC_VAR_INIT(0);
static volatile int ffmpeg_exited = 0;
static int main_return_code = 0;
static void
sigterm_handler(int sig)
{
int ret;
received_sigterm = sig;
received_nb_signals++;
term_exit_sigsafe();
if(received_nb_signals > 3) {
ret = write(2/*STDERR_FILENO*/, "Received > 3 system signals, hard exiting\n",
strlen("Received > 3 system signals, hard exiting\n"));
if (ret < 0) { /* Do nothing */ };
exit(123);
}
}
#if HAVE_SETCONSOLECTRLHANDLER
static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
{
av_log(NULL, AV_LOG_DEBUG, "\nReceived windows signal %ld\n", fdwCtrlType);
switch (fdwCtrlType)
{
case CTRL_C_EVENT:
case CTRL_BREAK_EVENT:
sigterm_handler(SIGINT);
return TRUE;
case CTRL_CLOSE_EVENT:
case CTRL_LOGOFF_EVENT:
case CTRL_SHUTDOWN_EVENT:
sigterm_handler(SIGTERM);
/* Basically, with these 3 events, when we return from this method the
process is hard terminated, so stall as long as we need to
to try and let the main thread(s) clean up and gracefully terminate
(we have at most 5 seconds, but should be done far before that). */
while (!ffmpeg_exited) {
Sleep(0);
}
return TRUE;
default:
av_log(NULL, AV_LOG_ERROR, "Received unknown windows signal %ld\n", fdwCtrlType);
return FALSE;
}
}
#endif
void term_init(void)
{
#if HAVE_TERMIOS_H
if (!run_as_daemon && stdin_interaction) {
struct termios tty;
if (tcgetattr (0, &tty) == 0) {
oldtty = tty;
restore_tty = 1;
tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
|INLCR|IGNCR|ICRNL|IXON);
tty.c_oflag |= OPOST;
tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
tty.c_cflag &= ~(CSIZE|PARENB);
tty.c_cflag |= CS8;
tty.c_cc[VMIN] = 1;
tty.c_cc[VTIME] = 0;
tcsetattr (0, TCSANOW, &tty);
}
signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
}
#endif
signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
#ifdef SIGXCPU
signal(SIGXCPU, sigterm_handler);
#endif
#ifdef SIGPIPE
signal(SIGPIPE, SIG_IGN); /* Broken pipe (POSIX). */
#endif
#if HAVE_SETCONSOLECTRLHANDLER
SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlHandler, TRUE);
#endif
}
/* read a key without blocking */
static int read_key(void)
{
unsigned char ch;
#if HAVE_TERMIOS_H
int n = 1;
struct timeval tv;
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(0, &rfds);
tv.tv_sec = 0;
tv.tv_usec = 0;
n = select(1, &rfds, NULL, NULL, &tv);
if (n > 0) {
n = read(0, &ch, 1);
if (n == 1)
return ch;
return n;
}
#elif HAVE_KBHIT
# if HAVE_PEEKNAMEDPIPE
static int is_pipe;
static HANDLE input_handle;
DWORD dw, nchars;
if(!input_handle){
input_handle = GetStdHandle(STD_INPUT_HANDLE);
is_pipe = !GetConsoleMode(input_handle, &dw);
}
if (is_pipe) {
/* When running under a GUI, you will end here. */
if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL)) {
// input pipe may have been closed by the program that ran ffmpeg
return -1;
}
//Read it
if(nchars != 0) {
read(0, &ch, 1);
return ch;
}else{
return -1;
}
}
# endif
if(kbhit())
return(getch());
#endif
return -1;
}
static int decode_interrupt_cb(void *ctx)
{
return received_nb_signals > atomic_load(&transcode_init_done);
}
const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
static void ffmpeg_cleanup(int ret)
{
int i, j;
if (do_benchmark) {
int maxrss = getmaxrss() / 1024;
av_log(NULL, AV_LOG_INFO, "bench: maxrss=%ikB\n", maxrss);
}
for (i = 0; i < nb_filtergraphs; i++) {
FilterGraph *fg = filtergraphs[i];
avfilter_graph_free(&fg->graph);
for (j = 0; j < fg->nb_inputs; j++) {
while (av_fifo_size(fg->inputs[j]->frame_queue)) {
AVFrame *frame;
av_fifo_generic_read(fg->inputs[j]->frame_queue, &frame,
sizeof(frame), NULL);
av_frame_free(&frame);
}
av_fifo_freep(&fg->inputs[j]->frame_queue);
if (fg->inputs[j]->ist->sub2video.sub_queue) {
while (av_fifo_size(fg->inputs[j]->ist->sub2video.sub_queue)) {
AVSubtitle sub;
av_fifo_generic_read(fg->inputs[j]->ist->sub2video.sub_queue,
&sub, sizeof(sub), NULL);
avsubtitle_free(&sub);
}
av_fifo_freep(&fg->inputs[j]->ist->sub2video.sub_queue);
}
av_buffer_unref(&fg->inputs[j]->hw_frames_ctx);
av_freep(&fg->inputs[j]->name);
av_freep(&fg->inputs[j]);
}
av_freep(&fg->inputs);
for (j = 0; j < fg->nb_outputs; j++) {
av_freep(&fg->outputs[j]->name);
av_freep(&fg->outputs[j]->formats);
av_freep(&fg->outputs[j]->channel_layouts);
av_freep(&fg->outputs[j]->sample_rates);
av_freep(&fg->outputs[j]);
}
av_freep(&fg->outputs);
av_freep(&fg->graph_desc);
av_freep(&filtergraphs[i]);
}
av_freep(&filtergraphs);
av_freep(&subtitle_out);
/* close files */
for (i = 0; i < nb_output_files; i++) {
OutputFile *of = output_files[i];
AVFormatContext *s;
if (!of)
continue;
s = of->ctx;
if (s && s->oformat && !(s->oformat->flags & AVFMT_NOFILE))
avio_closep(&s->pb);
avformat_free_context(s);
av_dict_free(&of->opts);
av_freep(&output_files[i]);
}
for (i = 0; i < nb_output_streams; i++) {
OutputStream *ost = output_streams[i];
if (!ost)
continue;
for (j = 0; j < ost->nb_bitstream_filters; j++)
av_bsf_free(&ost->bsf_ctx[j]);
av_freep(&ost->bsf_ctx);
av_frame_free(&ost->filtered_frame);
av_frame_free(&ost->last_frame);
av_dict_free(&ost->encoder_opts);
av_freep(&ost->forced_keyframes);
av_expr_free(ost->forced_keyframes_pexpr);
av_freep(&ost->avfilter);
av_freep(&ost->logfile_prefix);
av_freep(&ost->audio_channels_map);
ost->audio_channels_mapped = 0;
av_dict_free(&ost->sws_dict);
avcodec_free_context(&ost->enc_ctx);
avcodec_parameters_free(&ost->ref_par);
if (ost->muxing_queue) {
while (av_fifo_size(ost->muxing_queue)) {
AVPacket pkt;
av_fifo_generic_read(ost->muxing_queue, &pkt, sizeof(pkt), NULL);
av_packet_unref(&pkt);
}
av_fifo_freep(&ost->muxing_queue);
}
av_freep(&output_streams[i]);
}
#if HAVE_THREADS
free_input_threads();
#endif
for (i = 0; i < nb_input_files; i++) {
avformat_close_input(&input_files[i]->ctx);
av_freep(&input_files[i]);
}
for (i = 0; i < nb_input_streams; i++) {
InputStream *ist = input_streams[i];
av_frame_free(&ist->decoded_frame);
av_frame_free(&ist->filter_frame);
av_dict_free(&ist->decoder_opts);
avsubtitle_free(&ist->prev_sub.subtitle);
av_frame_free(&ist->sub2video.frame);
av_freep(&ist->filters);
av_freep(&ist->hwaccel_device);
av_freep(&ist->dts_buffer);
avcodec_free_context(&ist->dec_ctx);
av_freep(&input_streams[i]);
}
if (vstats_file) {
if (fclose(vstats_file))
av_log(NULL, AV_LOG_ERROR,
"Error closing vstats file, loss of information possible: %s\n",
av_err2str(AVERROR(errno)));
}
av_freep(&vstats_filename);
av_freep(&input_streams);
av_freep(&input_files);
av_freep(&output_streams);
av_freep(&output_files);
uninit_opts();
avformat_network_deinit();
if (received_sigterm) {
av_log(NULL, AV_LOG_INFO, "Exiting normally, received signal %d.\n",
(int) received_sigterm);
} else if (ret && atomic_load(&transcode_init_done)) {
av_log(NULL, AV_LOG_INFO, "Conversion failed!\n");
}
term_exit();
ffmpeg_exited = 1;
filtergraphs = NULL;
nb_filtergraphs = 0;
output_files = NULL;
nb_output_files = 0;
output_streams = NULL;
nb_output_streams = 0;
input_files = NULL;
nb_input_files = 0;
input_streams = NULL;
nb_input_streams = 0;
}
void remove_avoptions(AVDictionary **a, AVDictionary *b)
{
AVDictionaryEntry *t = NULL;
while ((t = av_dict_get(b, "", t, AV_DICT_IGNORE_SUFFIX))) {
av_dict_set(a, t->key, NULL, AV_DICT_MATCH_CASE);
}
}
void assert_avoptions(AVDictionary *m)
{
AVDictionaryEntry *t;
if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
exit_program(1);
}
}
static void abort_codec_experimental(AVCodec *c, int encoder)
{
exit_program(1);
}
static void update_benchmark(const char *fmt, ...)
{
if (do_benchmark_all) {
BenchmarkTimeStamps t = get_benchmark_time_stamps();
va_list va;
char buf[1024];
if (fmt) {
va_start(va, fmt);
vsnprintf(buf, sizeof(buf), fmt, va);
va_end(va);
av_log(NULL, AV_LOG_INFO,
"bench: %8" PRIu64 " user %8" PRIu64 " sys %8" PRIu64 " real %s \n",
t.user_usec - current_time.user_usec,
t.sys_usec - current_time.sys_usec,
t.real_usec - current_time.real_usec, buf);
}
current_time = t;
}
}
static void close_all_output_streams(OutputStream *ost, OSTFinished this_stream, OSTFinished others)
{
int i;
for (i = 0; i < nb_output_streams; i++) {
OutputStream *ost2 = output_streams[i];
ost2->finished |= ost == ost2 ? this_stream : others;
}
}
static void write_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost, int unqueue)
{
AVFormatContext *s = of->ctx;
AVStream *st = ost->st;
int ret;
/*
* Audio encoders may split the packets -- #frames in != #packets out.
* But there is no reordering, so we can limit the number of output packets
* by simply dropping them here.
* Counting encoded video frames needs to be done separately because of
* reordering, see do_video_out().
* Do not count the packet when unqueued because it has been counted when queued.
*/
if (!(st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && ost->encoding_needed) && !unqueue) {
if (ost->frame_number >= ost->max_frames) {
av_packet_unref(pkt);
return;
}
ost->frame_number++;
}
if (!of->header_written) {
AVPacket tmp_pkt = {0};
/* the muxer is not initialized yet, buffer the packet */
if (!av_fifo_space(ost->muxing_queue)) {
int new_size = FFMIN(2 * av_fifo_size(ost->muxing_queue),
ost->max_muxing_queue_size);
if (new_size <= av_fifo_size(ost->muxing_queue)) {
av_log(NULL, AV_LOG_ERROR,
"Too many packets buffered for output stream %d:%d.\n",
ost->file_index, ost->st->index);
exit_program(1);
}
ret = av_fifo_realloc2(ost->muxing_queue, new_size);
if (ret < 0)
exit_program(1);
}
ret = av_packet_make_refcounted(pkt);
if (ret < 0)
exit_program(1);
av_packet_move_ref(&tmp_pkt, pkt);
av_fifo_generic_write(ost->muxing_queue, &tmp_pkt, sizeof(tmp_pkt), NULL);
return;
}
if ((st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||
(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))
pkt->pts = pkt->dts = AV_NOPTS_VALUE;
if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
int i;
uint8_t *sd = av_packet_get_side_data(pkt, AV_PKT_DATA_QUALITY_STATS,
NULL);
ost->quality = sd ? AV_RL32(sd) : -1;
ost->pict_type = sd ? sd[4] : AV_PICTURE_TYPE_NONE;
for (i = 0; i<FF_ARRAY_ELEMS(ost->error); i++) {
if (sd && i < sd[5])
ost->error[i] = AV_RL64(sd + 8 + 8*i);
else
ost->error[i] = -1;
}
if (ost->frame_rate.num && ost->is_cfr) {
if (pkt->duration > 0)
av_log(NULL, AV_LOG_WARNING, "Overriding packet duration by frame rate, this should not happen\n");
pkt->duration = av_rescale_q(1, av_inv_q(ost->frame_rate),
ost->mux_timebase);
}
}
av_packet_rescale_ts(pkt, ost->mux_timebase, ost->st->time_base);
if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
if (pkt->dts != AV_NOPTS_VALUE &&
pkt->pts != AV_NOPTS_VALUE &&
pkt->dts > pkt->pts) {
av_log(s, AV_LOG_WARNING, "Invalid DTS: %"PRId64" PTS: %"PRId64" in output stream %d:%d, replacing by guess\n",
pkt->dts, pkt->pts,
ost->file_index, ost->st->index);
pkt->pts =
pkt->dts = pkt->pts + pkt->dts + ost->last_mux_dts + 1
- FFMIN3(pkt->pts, pkt->dts, ost->last_mux_dts + 1)
- FFMAX3(pkt->pts, pkt->dts, ost->last_mux_dts + 1);
}
if ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO || st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) &&
pkt->dts != AV_NOPTS_VALUE &&
!(st->codecpar->codec_id == AV_CODEC_ID_VP9 && ost->stream_copy) &&
ost->last_mux_dts != AV_NOPTS_VALUE) {
int64_t max = ost->last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
if (pkt->dts < max) {
int loglevel = max - pkt->dts > 2 || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG;
av_log(s, loglevel, "Non-monotonous DTS in output stream "
"%d:%d; previous: %"PRId64", current: %"PRId64"; ",
ost->file_index, ost->st->index, ost->last_mux_dts, pkt->dts);
if (exit_on_error) {
av_log(NULL, AV_LOG_FATAL, "aborting.\n");
exit_program(1);
}
av_log(s, loglevel, "changing to %"PRId64". This may result "
"in incorrect timestamps in the output file.\n",
max);
if (pkt->pts >= pkt->dts)
pkt->pts = FFMAX(pkt->pts, max);
pkt->dts = max;
}
}
}
ost->last_mux_dts = pkt->dts;
ost->data_size += pkt->size;
ost->packets_written++;
pkt->stream_index = ost->index;
if (debug_ts) {
av_log(NULL, AV_LOG_INFO, "muxer <- type:%s "
"pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s size:%d\n",
av_get_media_type_string(ost->enc_ctx->codec_type),
av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &ost->st->time_base),
av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ost->st->time_base),
pkt->size
);
}
ret = av_interleaved_write_frame(s, pkt);
if (ret < 0) {
print_error("av_interleaved_write_frame()", ret);
main_return_code = 1;
close_all_output_streams(ost, MUXER_FINISHED | ENCODER_FINISHED, ENCODER_FINISHED);
}
av_packet_unref(pkt);
}
static void close_output_stream(OutputStream *ost)
{
OutputFile *of = output_files[ost->file_index];
ost->finished |= ENCODER_FINISHED;
if (of->shortest) {
int64_t end = av_rescale_q(ost->sync_opts - ost->first_pts, ost->enc_ctx->time_base, AV_TIME_BASE_Q);
of->recording_time = FFMIN(of->recording_time, end);
}
}
/*
* Send a single packet to the output, applying any bitstream filters
* associated with the output stream. This may result in any number
* of packets actually being written, depending on what bitstream
* filters are applied. The supplied packet is consumed and will be
* blank (as if newly-allocated) when this function returns.
*
* If eof is set, instead indicate EOF to all bitstream filters and
* therefore flush any delayed packets to the output. A blank packet
* must be supplied in this case.
*/
static void output_packet(OutputFile *of, AVPacket *pkt,
OutputStream *ost, int eof)
{
int ret = 0;
/* apply the output bitstream filters, if any */
if (ost->nb_bitstream_filters) {
int idx;
ret = av_bsf_send_packet(ost->bsf_ctx[0], eof ? NULL : pkt);
if (ret < 0)
goto finish;
eof = 0;
idx = 1;
while (idx) {
/* get a packet from the previous filter up the chain */
ret = av_bsf_receive_packet(ost->bsf_ctx[idx - 1], pkt);
if (ret == AVERROR(EAGAIN)) {
ret = 0;
idx--;
continue;
} else if (ret == AVERROR_EOF) {
eof = 1;
} else if (ret < 0)
goto finish;
/* send it to the next filter down the chain or to the muxer */
if (idx < ost->nb_bitstream_filters) {
ret = av_bsf_send_packet(ost->bsf_ctx[idx], eof ? NULL : pkt);
if (ret < 0)
goto finish;
idx++;
eof = 0;
} else if (eof)
goto finish;
else
write_packet(of, pkt, ost, 0);
}
} else if (!eof)
write_packet(of, pkt, ost, 0);
finish:
if (ret < 0 && ret != AVERROR_EOF) {
av_log(NULL, AV_LOG_ERROR, "Error applying bitstream filters to an output "
"packet for stream #%d:%d.\n", ost->file_index, ost->index);
if(exit_on_error)
exit_program(1);
}
}
static int check_recording_time(OutputStream *ost)
{
OutputFile *of = output_files[ost->file_index];
if (of->recording_time != INT64_MAX &&
av_compare_ts(ost->sync_opts - ost->first_pts, ost->enc_ctx->time_base, of->recording_time,
AV_TIME_BASE_Q) >= 0) {
close_output_stream(ost);
return 0;
}
return 1;
}
static void do_audio_out(OutputFile *of, OutputStream *ost,
AVFrame *frame)
{
AVCodecContext *enc = ost->enc_ctx;
AVPacket pkt;
int ret;
av_init_packet(&pkt);
pkt.data = NULL;
pkt.size = 0;
if (!check_recording_time(ost))
return;
if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
frame->pts = ost->sync_opts;
ost->sync_opts = frame->pts + frame->nb_samples;
ost->samples_encoded += frame->nb_samples;
ost->frames_encoded++;
av_assert0(pkt.size || !pkt.data);
update_benchmark(NULL);
if (debug_ts) {
av_log(NULL, AV_LOG_INFO, "encoder <- type:audio "
"frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
av_ts2str(frame->pts), av_ts2timestr(frame->pts, &enc->time_base),
enc->time_base.num, enc->time_base.den);
}
ret = avcodec_send_frame(enc, frame);
if (ret < 0)
goto error;
while (1) {
ret = avcodec_receive_packet(enc, &pkt);
if (ret == AVERROR(EAGAIN))
break;
if (ret < 0)
goto error;
update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);
av_packet_rescale_ts(&pkt, enc->time_base, ost->mux_timebase);
if (debug_ts) {
av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "
"pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &enc->time_base),
av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &enc->time_base));
}
output_packet(of, &pkt, ost, 0);
}
return;
error:
av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
exit_program(1);
}
static void do_subtitle_out(OutputFile *of,
OutputStream *ost,
AVSubtitle *sub)
{
int subtitle_out_max_size = 1024 * 1024;
int subtitle_out_size, nb, i;
AVCodecContext *enc;
AVPacket pkt;
int64_t pts;
if (sub->pts == AV_NOPTS_VALUE) {
av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
if (exit_on_error)
exit_program(1);
return;
}
enc = ost->enc_ctx;
if (!subtitle_out) {
subtitle_out = av_malloc(subtitle_out_max_size);
if (!subtitle_out) {
av_log(NULL, AV_LOG_FATAL, "Failed to allocate subtitle_out\n");
exit_program(1);
}
}
/* Note: DVB subtitle need one packet to draw them and one other
packet to clear them */
/* XXX: signal it in the codec context ? */
if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
nb = 2;
else
nb = 1;
/* shift timestamp to honor -ss and make check_recording_time() work with -t */
pts = sub->pts;
if (output_files[ost->file_index]->start_time != AV_NOPTS_VALUE)
pts -= output_files[ost->file_index]->start_time;
for (i = 0; i < nb; i++) {
unsigned save_num_rects = sub->num_rects;
ost->sync_opts = av_rescale_q(pts, AV_TIME_BASE_Q, enc->time_base);
if (!check_recording_time(ost))
return;
sub->pts = pts;
// start_display_time is required to be 0
sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
sub->end_display_time -= sub->start_display_time;
sub->start_display_time = 0;
if (i == 1)
sub->num_rects = 0;
ost->frames_encoded++;
subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
subtitle_out_max_size, sub);
if (i == 1)
sub->num_rects = save_num_rects;
if (subtitle_out_size < 0) {
av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
exit_program(1);
}
av_init_packet(&pkt);
pkt.data = subtitle_out;
pkt.size = subtitle_out_size;
pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->mux_timebase);
pkt.duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->mux_timebase);
if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
/* XXX: the pts correction is handled here. Maybe handling
it in the codec would be better */
if (i == 0)
pkt.pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, ost->mux_timebase);
else
pkt.pts += av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->mux_timebase);
}
pkt.dts = pkt.pts;
output_packet(of, &pkt, ost, 0);
}
}
static void do_video_out(OutputFile *of,
OutputStream *ost,
AVFrame *next_picture,
double sync_ipts)
{
int ret, format_video_sync;
AVPacket pkt;
AVCodecContext *enc = ost->enc_ctx;
AVCodecParameters *mux_par = ost->st->codecpar;
AVRational frame_rate;
int nb_frames, nb0_frames, i;
double delta, delta0;
double duration = 0;
int frame_size = 0;
InputStream *ist = NULL;
AVFilterContext *filter = ost->filter->filter;
if (ost->source_index >= 0)
ist = input_streams[ost->source_index];
frame_rate = av_buffersink_get_frame_rate(filter);
if (frame_rate.num > 0 && frame_rate.den > 0)
duration = 1/(av_q2d(frame_rate) * av_q2d(enc->time_base));
if(ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE && ost->frame_rate.num)
duration = FFMIN(duration, 1/(av_q2d(ost->frame_rate) * av_q2d(enc->time_base)));
if (!ost->filters_script &&
!ost->filters &&
(nb_filtergraphs == 0 || !filtergraphs[0]->graph_desc) &&
next_picture &&
ist &&
lrintf(next_picture->pkt_duration * av_q2d(ist->st->time_base) / av_q2d(enc->time_base)) > 0) {
duration = lrintf(next_picture->pkt_duration * av_q2d(ist->st->time_base) / av_q2d(enc->time_base));
}
if (!next_picture) {
//end, flushing
nb0_frames = nb_frames = mid_pred(ost->last_nb0_frames[0],
ost->last_nb0_frames[1],
ost->last_nb0_frames[2]);
} else {
delta0 = sync_ipts - ost->sync_opts; // delta0 is the "drift" between the input frame (next_picture) and where it would fall in the output.
delta = delta0 + duration;
/* by default, we output a single frame */
nb0_frames = 0; // tracks the number of times the PREVIOUS frame should be duplicated, mostly for variable framerate (VFR)
nb_frames = 1;
format_video_sync = video_sync_method;
if (format_video_sync == VSYNC_AUTO) {
if(!strcmp(of->ctx->oformat->name, "avi")) {
format_video_sync = VSYNC_VFR;
} else
format_video_sync = (of->ctx->oformat->flags & AVFMT_VARIABLE_FPS) ? ((of->ctx->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : VSYNC_CFR;
if ( ist
&& format_video_sync == VSYNC_CFR
&& input_files[ist->file_index]->ctx->nb_streams == 1
&& input_files[ist->file_index]->input_ts_offset == 0) {
format_video_sync = VSYNC_VSCFR;
}
if (format_video_sync == VSYNC_CFR && copy_ts) {
format_video_sync = VSYNC_VSCFR;
}
}
ost->is_cfr = (format_video_sync == VSYNC_CFR || format_video_sync == VSYNC_VSCFR);
if (delta0 < 0 &&
delta > 0 &&
format_video_sync != VSYNC_PASSTHROUGH &&
format_video_sync != VSYNC_DROP) {
if (delta0 < -0.6) {
av_log(NULL, AV_LOG_VERBOSE, "Past duration %f too large\n", -delta0);
} else
av_log(NULL, AV_LOG_DEBUG, "Clipping frame in rate conversion by %f\n", -delta0);
sync_ipts = ost->sync_opts;
duration += delta0;
delta0 = 0;
}
switch (format_video_sync) {
case VSYNC_VSCFR:
if (ost->frame_number == 0 && delta0 >= 0.5) {
av_log(NULL, AV_LOG_DEBUG, "Not duplicating %d initial frames\n", (int)lrintf(delta0));
delta = duration;
delta0 = 0;
ost->sync_opts = lrint(sync_ipts);
}
case VSYNC_CFR:
// FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
if (frame_drop_threshold && delta < frame_drop_threshold && ost->frame_number) {
nb_frames = 0;
} else if (delta < -1.1)
nb_frames = 0;
else if (delta > 1.1) {
nb_frames = lrintf(delta);
if (delta0 > 1.1)
nb0_frames = lrintf(delta0 - 0.6);
}
break;
case VSYNC_VFR:
if (delta <= -0.6)
nb_frames = 0;
else if (delta > 0.6)
ost->sync_opts = lrint(sync_ipts);
break;
case VSYNC_DROP:
case VSYNC_PASSTHROUGH:
ost->sync_opts = lrint(sync_ipts);
break;
default:
av_assert0(0);
}
}
nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
nb0_frames = FFMIN(nb0_frames, nb_frames);
memmove(ost->last_nb0_frames + 1,
ost->last_nb0_frames,
sizeof(ost->last_nb0_frames[0]) * (FF_ARRAY_ELEMS(ost->last_nb0_frames) - 1));
ost->last_nb0_frames[0] = nb0_frames;
if (nb0_frames == 0 && ost->last_dropped) {
nb_frames_drop++;
av_log(NULL, AV_LOG_VERBOSE,
"*** dropping frame %d from stream %d at ts %"PRId64"\n",
ost->frame_number, ost->st->index, ost->last_frame->pts);
}
if (nb_frames > (nb0_frames && ost->last_dropped) + (nb_frames > nb0_frames)) {
if (nb_frames > dts_error_threshold * 30) {
av_log(NULL, AV_LOG_ERROR, "%d frame duplication too large, skipping\n", nb_frames - 1);
nb_frames_drop++;
return;
}
nb_frames_dup += nb_frames - (nb0_frames && ost->last_dropped) - (nb_frames > nb0_frames);
av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
if (nb_frames_dup > dup_warning) {
av_log(NULL, AV_LOG_WARNING, "More than %d frames duplicated\n", dup_warning);
dup_warning *= 10;
}
}
ost->last_dropped = nb_frames == nb0_frames && next_picture;
/* duplicates frame if needed */
for (i = 0; i < nb_frames; i++) {
AVFrame *in_picture;
int forced_keyframe = 0;
double pts_time;
av_init_packet(&pkt);
pkt.data = NULL;
pkt.size = 0;
if (i < nb0_frames && ost->last_frame) {
in_picture = ost->last_frame;
} else
in_picture = next_picture;
if (!in_picture)
return;
in_picture->pts = ost->sync_opts;
if (!check_recording_time(ost))
return;
if (enc->flags & (AV_CODEC_FLAG_INTERLACED_DCT | AV_CODEC_FLAG_INTERLACED_ME) &&
ost->top_field_first >= 0)
in_picture->top_field_first = !!ost->top_field_first;
if (in_picture->interlaced_frame) {
if (enc->codec->id == AV_CODEC_ID_MJPEG)
mux_par->field_order = in_picture->top_field_first ? AV_FIELD_TT:AV_FIELD_BB;
else
mux_par->field_order = in_picture->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
} else
mux_par->field_order = AV_FIELD_PROGRESSIVE;
in_picture->quality = enc->global_quality;
in_picture->pict_type = 0;
if (ost->forced_kf_ref_pts == AV_NOPTS_VALUE &&
in_picture->pts != AV_NOPTS_VALUE)
ost->forced_kf_ref_pts = in_picture->pts;
pts_time = in_picture->pts != AV_NOPTS_VALUE ?
(in_picture->pts - ost->forced_kf_ref_pts) * av_q2d(enc->time_base) : NAN;
if (ost->forced_kf_index < ost->forced_kf_count &&
in_picture->pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
ost->forced_kf_index++;
forced_keyframe = 1;
} else if (ost->forced_keyframes_pexpr) {
double res;
ost->forced_keyframes_expr_const_values[FKF_T] = pts_time;
res = av_expr_eval(ost->forced_keyframes_pexpr,
ost->forced_keyframes_expr_const_values, NULL);
ff_dlog(NULL, "force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",
ost->forced_keyframes_expr_const_values[FKF_N],
ost->forced_keyframes_expr_const_values[FKF_N_FORCED],
ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N],
ost->forced_keyframes_expr_const_values[FKF_T],
ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T],
res);
if (res) {
forced_keyframe = 1;
ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] =
ost->forced_keyframes_expr_const_values[FKF_N];
ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] =
ost->forced_keyframes_expr_const_values[FKF_T];
ost->forced_keyframes_expr_const_values[FKF_N_FORCED] += 1;
}
ost->forced_keyframes_expr_const_values[FKF_N] += 1;
} else if ( ost->forced_keyframes
&& !strncmp(ost->forced_keyframes, "source", 6)
&& in_picture->key_frame==1) {
forced_keyframe = 1;
}
if (forced_keyframe) {
in_picture->pict_type = AV_PICTURE_TYPE_I;
av_log(NULL, AV_LOG_DEBUG, "Forced keyframe at time %f\n", pts_time);
}
update_benchmark(NULL);
if (debug_ts) {
av_log(NULL, AV_LOG_INFO, "encoder <- type:video "
"frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
av_ts2str(in_picture->pts), av_ts2timestr(in_picture->pts, &enc->time_base),
enc->time_base.num, enc->time_base.den);
}
ost->frames_encoded++;
ret = avcodec_send_frame(enc, in_picture);
if (ret < 0)
goto error;
// Make sure Closed Captions will not be duplicated
av_frame_remove_side_data(in_picture, AV_FRAME_DATA_A53_CC);
while (1) {
ret = avcodec_receive_packet(enc, &pkt);
update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
if (ret == AVERROR(EAGAIN))
break;
if (ret < 0)
goto error;
if (debug_ts) {
av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
"pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &enc->time_base),
av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &enc->time_base));
}
if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & AV_CODEC_CAP_DELAY))
pkt.pts = ost->sync_opts;
av_packet_rescale_ts(&pkt, enc->time_base, ost->mux_timebase);
if (debug_ts) {
av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
"pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->mux_timebase),
av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->mux_timebase));
}
frame_size = pkt.size;
output_packet(of, &pkt, ost, 0);
/* if two pass, output log */
if (ost->logfile && enc->stats_out) {
fprintf(ost->logfile, "%s", enc->stats_out);
}
}
ost->sync_opts++;
/*
* For video, number of frames in == number of packets out.
* But there may be reordering, so we can't throw away frames on encoder
* flush, we need to limit them here, before they go into encoder.
*/
ost->frame_number++;
if (vstats_filename && frame_size)
do_video_stats(ost, frame_size);
}
if (!ost->last_frame)
ost->last_frame = av_frame_alloc();
av_frame_unref(ost->last_frame);
if (next_picture && ost->last_frame)
av_frame_ref(ost->last_frame, next_picture);
else
av_frame_free(&ost->last_frame);
return;
error:
av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
exit_program(1);
}
static double psnr(double d)
{
return -10.0 * log10(d);
}
static void do_video_stats(OutputStream *ost, int frame_size)
{
AVCodecContext *enc;
int frame_number;
double ti1, bitrate, avg_bitrate;
/* this is executed just the first time do_video_stats is called */
if (!vstats_file) {
vstats_file = fopen(vstats_filename, "w");
if (!vstats_file) {
perror("fopen");
exit_program(1);
}
}
enc = ost->enc_ctx;
if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
frame_number = ost->st->nb_frames;
if (vstats_version <= 1) {
fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number,
ost->quality / (float)FF_QP2LAMBDA);
} else {
fprintf(vstats_file, "out= %2d st= %2d frame= %5d q= %2.1f ", ost->file_index, ost->index, frame_number,
ost->quality / (float)FF_QP2LAMBDA);
}
if (ost->error[0]>=0 && (enc->flags & AV_CODEC_FLAG_PSNR))
fprintf(vstats_file, "PSNR= %6.2f ", psnr(ost->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
fprintf(vstats_file,"f_size= %6d ", frame_size);
/* compute pts value */
ti1 = av_stream_get_end_pts(ost->st) * av_q2d(ost->st->time_base);
if (ti1 < 0.01)
ti1 = 0.01;
bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
avg_bitrate = (double)(ost->data_size * 8) / ti1 / 1000.0;
fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
(double)ost->data_size / 1024, ti1, bitrate, avg_bitrate);
fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(ost->pict_type));
}
}
static int init_output_stream(OutputStream *ost, char *error, int error_len);
static void finish_output_stream(OutputStream *ost)
{
OutputFile *of = output_files[ost->file_index];
int i;
ost->finished = ENCODER_FINISHED | MUXER_FINISHED;
if (of->shortest) {
for (i = 0; i < of->ctx->nb_streams; i++)
output_streams[of->ost_index + i]->finished = ENCODER_FINISHED | MUXER_FINISHED;
}
}
/**
* Get and encode new output from any of the filtergraphs, without causing
* activity.
*
* @return 0 for success, <0 for severe errors
*/
static int reap_filters(int flush)
{
AVFrame *filtered_frame = NULL;
int i;
/* Reap all buffers present in the buffer sinks */
for (i = 0; i < nb_output_streams; i++) {
OutputStream *ost = output_streams[i];
OutputFile *of = output_files[ost->file_index];
AVFilterContext *filter;
AVCodecContext *enc = ost->enc_ctx;
int ret = 0;
if (!ost->filter || !ost->filter->graph->graph)
continue;
filter = ost->filter->filter;
if (!ost->initialized) {
char error[1024] = "";
ret = init_output_stream(ost, error, sizeof(error));
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Error initializing output stream %d:%d -- %s\n",
ost->file_index, ost->index, error);
exit_program(1);
}
}
if (!ost->filtered_frame && !(ost->filtered_frame = av_frame_alloc())) {
return AVERROR(ENOMEM);
}
filtered_frame = ost->filtered_frame;
while (1) {
double float_pts = AV_NOPTS_VALUE; // this is identical to filtered_frame.pts but with higher precision
ret = av_buffersink_get_frame_flags(filter, filtered_frame,
AV_BUFFERSINK_FLAG_NO_REQUEST);
if (ret < 0) {
if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
av_log(NULL, AV_LOG_WARNING,
"Error in av_buffersink_get_frame_flags(): %s\n", av_err2str(ret));
} else if (flush && ret == AVERROR_EOF) {
if (av_buffersink_get_type(filter) == AVMEDIA_TYPE_VIDEO)
do_video_out(of, ost, NULL, AV_NOPTS_VALUE);
}
break;
}
if (ost->finished) {
av_frame_unref(filtered_frame);
continue;
}
if (filtered_frame->pts != AV_NOPTS_VALUE) {
int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
AVRational filter_tb = av_buffersink_get_time_base(filter);
AVRational tb = enc->time_base;
int extra_bits = av_clip(29 - av_log2(tb.den), 0, 16);
tb.den <<= extra_bits;
float_pts =
av_rescale_q(filtered_frame->pts, filter_tb, tb) -
av_rescale_q(start_time, AV_TIME_BASE_Q, tb);
float_pts /= 1 << extra_bits;
// avoid exact midoints to reduce the chance of rounding differences, this can be removed in case the fps code is changed to work with integers
float_pts += FFSIGN(float_pts) * 1.0 / (1<<17);
filtered_frame->pts =
av_rescale_q(filtered_frame->pts, filter_tb, enc->time_base) -
av_rescale_q(start_time, AV_TIME_BASE_Q, enc->time_base);
}
switch (av_buffersink_get_type(filter)) {
case AVMEDIA_TYPE_VIDEO:
if (!ost->frame_aspect_ratio.num)
enc->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;
if (debug_ts) {
av_log(NULL, AV_LOG_INFO, "filter -> pts:%s pts_time:%s exact:%f time_base:%d/%d\n",
av_ts2str(filtered_frame->pts), av_ts2timestr(filtered_frame->pts, &enc->time_base),
float_pts,
enc->time_base.num, enc->time_base.den);
}
do_video_out(of, ost, filtered_frame, float_pts);
break;
case AVMEDIA_TYPE_AUDIO:
if (!(enc->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE) &&
enc->channels != filtered_frame->channels) {
av_log(NULL, AV_LOG_ERROR,
"Audio filter graph output is not normalized and encoder does not support parameter changes\n");
break;
}
do_audio_out(of, ost, filtered_frame);
break;
default:
// TODO support subtitle filters
av_assert0(0);
}
av_frame_unref(filtered_frame);
}
}
return 0;
}
static void print_final_stats(int64_t total_size)
{
uint64_t video_size = 0, audio_size = 0, extra_size = 0, other_size = 0;
uint64_t subtitle_size = 0;
uint64_t data_size = 0;
float percent = -1.0;
int i, j;
int pass1_used = 1;
for (i = 0; i < nb_output_streams; i++) {
OutputStream *ost = output_streams[i];
switch (ost->enc_ctx->codec_type) {
case AVMEDIA_TYPE_VIDEO: video_size += ost->data_size; break;
case AVMEDIA_TYPE_AUDIO: audio_size += ost->data_size; break;
case AVMEDIA_TYPE_SUBTITLE: subtitle_size += ost->data_size; break;
default: other_size += ost->data_size; break;
}
extra_size += ost->enc_ctx->extradata_size;
data_size += ost->data_size;
if ( (ost->enc_ctx->flags & (AV_CODEC_FLAG_PASS1 | AV_CODEC_FLAG_PASS2))
!= AV_CODEC_FLAG_PASS1)
pass1_used = 0;
}
if (data_size && total_size>0 && total_size >= data_size)
percent = 100.0 * (total_size - data_size) / data_size;
av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB subtitle:%1.0fkB other streams:%1.0fkB global headers:%1.0fkB muxing overhead: ",
video_size / 1024.0,
audio_size / 1024.0,
subtitle_size / 1024.0,
other_size / 1024.0,
extra_size / 1024.0);
if (percent >= 0.0)
av_log(NULL, AV_LOG_INFO, "%f%%", percent);
else
av_log(NULL, AV_LOG_INFO, "unknown");
av_log(NULL, AV_LOG_INFO, "\n");
/* print verbose per-stream stats */
for (i = 0; i < nb_input_files; i++) {
InputFile *f = input_files[i];
uint64_t total_packets = 0, total_size = 0;
av_log(NULL, AV_LOG_VERBOSE, "Input file #%d (%s):\n",
i, f->ctx->url);
for (j = 0; j < f->nb_streams; j++) {
InputStream *ist = input_streams[f->ist_index + j];
enum AVMediaType type = ist->dec_ctx->codec_type;
total_size += ist->data_size;
total_packets += ist->nb_packets;
av_log(NULL, AV_LOG_VERBOSE, " Input stream #%d:%d (%s): ",
i, j, media_type_string(type));
av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets read (%"PRIu64" bytes); ",
ist->nb_packets, ist->data_size);
if (ist->decoding_needed) {
av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames decoded",
ist->frames_decoded);
if (type == AVMEDIA_TYPE_AUDIO)
av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ist->samples_decoded);
av_log(NULL, AV_LOG_VERBOSE, "; ");
}
av_log(NULL, AV_LOG_VERBOSE, "\n");
}
av_log(NULL, AV_LOG_VERBOSE, " Total: %"PRIu64" packets (%"PRIu64" bytes) demuxed\n",
total_packets, total_size);
}
for (i = 0; i < nb_output_files; i++) {
OutputFile *of = output_files[i];
uint64_t total_packets = 0, total_size = 0;
av_log(NULL, AV_LOG_VERBOSE, "Output file #%d (%s):\n",
i, of->ctx->url);
for (j = 0; j < of->ctx->nb_streams; j++) {
OutputStream *ost = output_streams[of->ost_index + j];
enum AVMediaType type = ost->enc_ctx->codec_type;
total_size += ost->data_size;
total_packets += ost->packets_written;
av_log(NULL, AV_LOG_VERBOSE, " Output stream #%d:%d (%s): ",
i, j, media_type_string(type));
if (ost->encoding_needed) {
av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames encoded",
ost->frames_encoded);
if (type == AVMEDIA_TYPE_AUDIO)
av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ost->samples_encoded);
av_log(NULL, AV_LOG_VERBOSE, "; ");
}
av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets muxed (%"PRIu64" bytes); ",
ost->packets_written, ost->data_size);
av_log(NULL, AV_LOG_VERBOSE, "\n");
}
av_log(NULL, AV_LOG_VERBOSE, " Total: %"PRIu64" packets (%"PRIu64" bytes) muxed\n",
total_packets, total_size);
}
if(video_size + data_size + audio_size + subtitle_size + extra_size == 0){
av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded ");
if (pass1_used) {
av_log(NULL, AV_LOG_WARNING, "\n");
} else {
av_log(NULL, AV_LOG_WARNING, "(check -ss / -t / -frames parameters if used)\n");
}
}
}
static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
{
AVBPrint buf, buf_script;
OutputStream *ost;
AVFormatContext *oc;
int64_t total_size;
AVCodecContext *enc;
int frame_number, vid, i;
double bitrate;
double speed;
int64_t pts = INT64_MIN + 1;
static int64_t last_time = -1;
static int qp_histogram[52];
int hours, mins, secs, us;
const char *hours_sign;
int ret;
float t;
if (!print_stats && !is_last_report && !progress_avio)
return;
if (!is_last_report) {
if (last_time == -1) {
last_time = cur_time;
return;
}
if ((cur_time - last_time) < 500000)
return;
last_time = cur_time;
}
t = (cur_time-timer_start) / 1000000.0;
oc = output_files[0]->ctx;
total_size = avio_size(oc->pb);
if (total_size <= 0) // FIXME improve avio_size() so it works with non seekable output too
total_size = avio_tell(oc->pb);
vid = 0;
av_bprint_init(&buf, 0, AV_BPRINT_SIZE_AUTOMATIC);
av_bprint_init(&buf_script, 0, AV_BPRINT_SIZE_AUTOMATIC);
for (i = 0; i < nb_output_streams; i++) {
float q = -1;
ost = output_streams[i];
enc = ost->enc_ctx;
if (!ost->stream_copy)
q = ost->quality / (float) FF_QP2LAMBDA;
if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
av_bprintf(&buf, "q=%2.1f ", q);
av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
ost->file_index, ost->index, q);
}
if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
float fps;
frame_number = ost->frame_number;
fps = t > 1 ? frame_number / t : 0;
av_bprintf(&buf, "frame=%5d fps=%3.*f q=%3.1f ",
frame_number, fps < 9.95, fps, q);
av_bprintf(&buf_script, "frame=%d\n", frame_number);
av_bprintf(&buf_script, "fps=%.2f\n", fps);
av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
ost->file_index, ost->index, q);
if (is_last_report)
av_bprintf(&buf, "L");
if (qp_hist) {
int j;
int qp = lrintf(q);
if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
qp_histogram[qp]++;
for (j = 0; j < 32; j++)
av_bprintf(&buf, "%X", av_log2(qp_histogram[j] + 1));
}
if ((enc->flags & AV_CODEC_FLAG_PSNR) && (ost->pict_type != AV_PICTURE_TYPE_NONE || is_last_report)) {
int j;
double error, error_sum = 0;
double scale, scale_sum = 0;
double p;
char type[3] = { 'Y','U','V' };
av_bprintf(&buf, "PSNR=");
for (j = 0; j < 3; j++) {
if (is_last_report) {
error = enc->error[j];
scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
} else {
error = ost->error[j];
scale = enc->width * enc->height * 255.0 * 255.0;
}
if (j)
scale /= 4;
error_sum += error;
scale_sum += scale;
p = psnr(error / scale);
av_bprintf(&buf, "%c:%2.2f ", type[j], p);
av_bprintf(&buf_script, "stream_%d_%d_psnr_%c=%2.2f\n",
ost->file_index, ost->index, type[j] | 32, p);
}
p = psnr(error_sum / scale_sum);
av_bprintf(&buf, "*:%2.2f ", psnr(error_sum / scale_sum));
av_bprintf(&buf_script, "stream_%d_%d_psnr_all=%2.2f\n",
ost->file_index, ost->index, p);
}
vid = 1;
}
/* compute min output value */
if (av_stream_get_end_pts(ost->st) != AV_NOPTS_VALUE)
pts = FFMAX(pts, av_rescale_q(av_stream_get_end_pts(ost->st),
ost->st->time_base, AV_TIME_BASE_Q));
if (is_last_report)
nb_frames_drop += ost->last_dropped;
}
secs = FFABS(pts) / AV_TIME_BASE;
us = FFABS(pts) % AV_TIME_BASE;
mins = secs / 60;
secs %= 60;
hours = mins / 60;
mins %= 60;
hours_sign = (pts < 0) ? "-" : "";
bitrate = pts && total_size >= 0 ? total_size * 8 / (pts / 1000.0) : -1;
speed = t != 0.0 ? (double)pts / AV_TIME_BASE / t : -1;
if (total_size < 0) av_bprintf(&buf, "size=N/A time=");
else av_bprintf(&buf, "size=%8.0fkB time=", total_size / 1024.0);
if (pts == AV_NOPTS_VALUE) {
av_bprintf(&buf, "N/A ");
} else {
av_bprintf(&buf, "%s%02d:%02d:%02d.%02d ",
hours_sign, hours, mins, secs, (100 * us) / AV_TIME_BASE);
}
if (bitrate < 0) {
av_bprintf(&buf, "bitrate=N/A");
av_bprintf(&buf_script, "bitrate=N/A\n");
}else{
av_bprintf(&buf, "bitrate=%6.1fkbits/s", bitrate);
av_bprintf(&buf_script, "bitrate=%6.1fkbits/s\n", bitrate);
}
if (total_size < 0) av_bprintf(&buf_script, "total_size=N/A\n");
else av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
if (pts == AV_NOPTS_VALUE) {
av_bprintf(&buf_script, "out_time_us=N/A\n");
av_bprintf(&buf_script, "out_time_ms=N/A\n");
av_bprintf(&buf_script, "out_time=N/A\n");
} else {
av_bprintf(&buf_script, "out_time_us=%"PRId64"\n", pts);
av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
av_bprintf(&buf_script, "out_time=%s%02d:%02d:%02d.%06d\n",
hours_sign, hours, mins, secs, us);
}
if (nb_frames_dup || nb_frames_drop)
av_bprintf(&buf, " dup=%d drop=%d", nb_frames_dup, nb_frames_drop);
av_bprintf(&buf_script, "dup_frames=%d\n", nb_frames_dup);
av_bprintf(&buf_script, "drop_frames=%d\n", nb_frames_drop);
if (speed < 0) {
av_bprintf(&buf, " speed=N/A");
av_bprintf(&buf_script, "speed=N/A\n");
} else {
av_bprintf(&buf, " speed=%4.3gx", speed);
av_bprintf(&buf_script, "speed=%4.3gx\n", speed);
}
if (print_stats || is_last_report) {
const char end = is_last_report ? '\n' : '\r';
if (print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
fprintf(stderr, "%s %c", buf.str, end);
} else
av_log(NULL, AV_LOG_INFO, "%s %c", buf.str, end);
fflush(stderr);
}
av_bprint_finalize(&buf, NULL);
if (progress_avio) {
av_bprintf(&buf_script, "progress=%s\n",
is_last_report ? "end" : "continue");
avio_write(progress_avio, buf_script.str,
FFMIN(buf_script.len, buf_script.size - 1));
avio_flush(progress_avio);
av_bprint_finalize(&buf_script, NULL);
if (is_last_report) {
if ((ret = avio_closep(&progress_avio)) < 0)
av_log(NULL, AV_LOG_ERROR,
"Error closing progress log, loss of information possible: %s\n", av_err2str(ret));
}
}
if (is_last_report)
print_final_stats(total_size);
}
static void ifilter_parameters_from_codecpar(InputFilter *ifilter, AVCodecParameters *par)
{
// We never got any input. Set a fake format, which will
// come from libavformat.
ifilter->format = par->format;
ifilter->sample_rate = par->sample_rate;
ifilter->channels = par->channels;
ifilter->channel_layout = par->channel_layout;
ifilter->width = par->width;
ifilter->height = par->height;
ifilter->sample_aspect_ratio = par->sample_aspect_ratio;
}
static void flush_encoders(void)
{
int i, ret;
for (i = 0; i < nb_output_streams; i++) {
OutputStream *ost = output_streams[i];
AVCodecContext *enc = ost->enc_ctx;
OutputFile *of = output_files[ost->file_index];
if (!ost->encoding_needed)
continue;
// Try to enable encoding with no input frames.
// Maybe we should just let encoding fail instead.
if (!ost->initialized) {
FilterGraph *fg = ost->filter->graph;
char error[1024] = "";
av_log(NULL, AV_LOG_WARNING,
"Finishing stream %d:%d without any data written to it.\n",
ost->file_index, ost->st->index);
if (ost->filter && !fg->graph) {
int x;
for (x = 0; x < fg->nb_inputs; x++) {
InputFilter *ifilter = fg->inputs[x];
if (ifilter->format < 0)
ifilter_parameters_from_codecpar(ifilter, ifilter->ist->st->codecpar);
}
if (!ifilter_has_all_input_formats(fg))
continue;
ret = configure_filtergraph(fg);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Error configuring filter graph\n");
exit_program(1);
}
finish_output_stream(ost);
}
ret = init_output_stream(ost, error, sizeof(error));
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Error initializing output stream %d:%d -- %s\n",
ost->file_index, ost->index, error);
exit_program(1);
}
}
if (enc->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
continue;
if (enc->codec_type != AVMEDIA_TYPE_VIDEO && enc->codec_type != AVMEDIA_TYPE_AUDIO)
continue;
for (;;) {
const char *desc = NULL;
AVPacket pkt;
int pkt_size;
switch (enc->codec_type) {
case AVMEDIA_TYPE_AUDIO:
desc = "audio";
break;
case AVMEDIA_TYPE_VIDEO:
desc = "video";
break;
default:
av_assert0(0);
}
av_init_packet(&pkt);
pkt.data = NULL;
pkt.size = 0;
update_benchmark(NULL);
while ((ret = avcodec_receive_packet(enc, &pkt)) == AVERROR(EAGAIN)) {
ret = avcodec_send_frame(enc, NULL);
if (ret < 0) {
av_log(NULL, AV_LOG_FATAL, "%s encoding failed: %s\n",
desc,
av_err2str(ret));
exit_program(1);
}
}
update_benchmark("flush_%s %d.%d", desc, ost->file_index, ost->index);
if (ret < 0 && ret != AVERROR_EOF) {
av_log(NULL, AV_LOG_FATAL, "%s encoding failed: %s\n",
desc,
av_err2str(ret));
exit_program(1);
}
if (ost->logfile && enc->stats_out) {
fprintf(ost->logfile, "%s", enc->stats_out);
}
if (ret == AVERROR_EOF) {
output_packet(of, &pkt, ost, 1);
break;
}
if (ost->finished & MUXER_FINISHED) {
av_packet_unref(&pkt);
continue;
}
av_packet_rescale_ts(&pkt, enc->time_base, ost->mux_timebase);
pkt_size = pkt.size;
output_packet(of, &pkt, ost, 0);
if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO && vstats_filename) {
do_video_stats(ost, pkt_size);
}
}
}
}
/*
* Check whether a packet from ist should be written into ost at this time
*/
static int check_output_constraints(InputStream *ist, OutputStream *ost)
{
OutputFile *of = output_files[ost->file_index];
int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
if (ost->source_index != ist_index)
return 0;
if (ost->finished)
return 0;
if (of->start_time != AV_NOPTS_VALUE && ist->pts < of->start_time)
return 0;
return 1;
}
static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
{
OutputFile *of = output_files[ost->file_index];
InputFile *f = input_files [ist->file_index];
int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ost->mux_timebase);
AVPacket opkt = { 0 };
av_init_packet(&opkt);
// EOF: flush output bitstream filters.
if (!pkt) {
output_packet(of, &opkt, ost, 1);
return;
}
if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
!ost->copy_initial_nonkeyframes)
return;
if (!ost->frame_number && !ost->copy_prior_start) {
int64_t comp_start = start_time;
if (copy_ts && f->start_time != AV_NOPTS_VALUE)
comp_start = FFMAX(start_time, f->start_time + f->ts_offset);
if (pkt->pts == AV_NOPTS_VALUE ?
ist->pts < comp_start :
pkt->pts < av_rescale_q(comp_start, AV_TIME_BASE_Q, ist->st->time_base))
return;
}
if (of->recording_time != INT64_MAX &&
ist->pts >= of->recording_time + start_time) {
close_output_stream(ost);
return;
}
if (f->recording_time != INT64_MAX) {
start_time = f->ctx->start_time;
if (f->start_time != AV_NOPTS_VALUE && copy_ts)
start_time += f->start_time;
if (ist->pts >= f->recording_time + start_time) {
close_output_stream(ost);
return;
}
}
/* force the input stream PTS */
if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
ost->sync_opts++;
if (pkt->pts != AV_NOPTS_VALUE)
opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->mux_timebase) - ost_tb_start_time;
else
opkt.pts = AV_NOPTS_VALUE;
if (pkt->dts == AV_NOPTS_VALUE)
opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->mux_timebase);
else
opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->mux_timebase);
opkt.dts -= ost_tb_start_time;
if (ost->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && pkt->dts != AV_NOPTS_VALUE) {
int duration = av_get_audio_frame_duration(ist->dec_ctx, pkt->size);
if(!duration)
duration = ist->dec_ctx->frame_size;
opkt.dts = opkt.pts = av_rescale_delta(ist->st->time_base, pkt->dts,
(AVRational){1, ist->dec_ctx->sample_rate}, duration, &ist->filter_in_rescale_delta_last,
ost->mux_timebase) - ost_tb_start_time;
}
opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->mux_timebase);
opkt.flags = pkt->flags;
if (pkt->buf) {
opkt.buf = av_buffer_ref(pkt->buf);
if (!opkt.buf)
exit_program(1);
}
opkt.data = pkt->data;
opkt.size = pkt->size;
av_copy_packet_side_data(&opkt, pkt);
output_packet(of, &opkt, ost, 0);
}
int guess_input_channel_layout(InputStream *ist)
{
AVCodecContext *dec = ist->dec_ctx;
if (!dec->channel_layout) {
char layout_name[256];
if (dec->channels > ist->guess_layout_max)
return 0;
dec->channel_layout = av_get_default_channel_layout(dec->channels);
if (!dec->channel_layout)
return 0;
av_get_channel_layout_string(layout_name, sizeof(layout_name),
dec->channels, dec->channel_layout);
av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
"#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
}
return 1;
}
static void check_decode_result(InputStream *ist, int *got_output, int ret)
{
if (*got_output || ret<0)
decode_error_stat[ret<0] ++;
if (ret < 0 && exit_on_error)
exit_program(1);
if (*got_output && ist) {
if (ist->decoded_frame->decode_error_flags || (ist->decoded_frame->flags & AV_FRAME_FLAG_CORRUPT)) {
av_log(NULL, exit_on_error ? AV_LOG_FATAL : AV_LOG_WARNING,
"%s: corrupt decoded frame in stream %d\n", input_files[ist->file_index]->ctx->url, ist->st->index);
if (exit_on_error)
exit_program(1);
}
}
}
// Filters can be configured only if the formats of all inputs are known.
static int ifilter_has_all_input_formats(FilterGraph *fg)
{
int i;
for (i = 0; i < fg->nb_inputs; i++) {
if (fg->inputs[i]->format < 0 && (fg->inputs[i]->type == AVMEDIA_TYPE_AUDIO ||
fg->inputs[i]->type == AVMEDIA_TYPE_VIDEO))
return 0;
}
return 1;
}
static int ifilter_send_frame(InputFilter *ifilter, AVFrame *frame)
{
FilterGraph *fg = ifilter->graph;
int need_reinit, ret, i;
/* determine if the parameters for this input changed */
need_reinit = ifilter->format != frame->format;
switch (ifilter->ist->st->codecpar->codec_type) {
case AVMEDIA_TYPE_AUDIO:
need_reinit |= ifilter->sample_rate != frame->sample_rate ||
ifilter->channels != frame->channels ||
ifilter->channel_layout != frame->channel_layout;
break;
case AVMEDIA_TYPE_VIDEO:
need_reinit |= ifilter->width != frame->width ||
ifilter->height != frame->height;
break;
}
if (!ifilter->ist->reinit_filters && fg->graph)
need_reinit = 0;
if (!!ifilter->hw_frames_ctx != !!frame->hw_frames_ctx ||
(ifilter->hw_frames_ctx && ifilter->hw_frames_ctx->data != frame->hw_frames_ctx->data))
need_reinit = 1;
if (need_reinit) {
ret = ifilter_parameters_from_frame(ifilter, frame);
if (ret < 0)
return ret;
}
/* (re)init the graph if possible, otherwise buffer the frame and return */
if (need_reinit || !fg->graph) {
for (i = 0; i < fg->nb_inputs; i++) {
if (!ifilter_has_all_input_formats(fg)) {
AVFrame *tmp = av_frame_clone(frame);
if (!tmp)
return AVERROR(ENOMEM);
av_frame_unref(frame);
if (!av_fifo_space(ifilter->frame_queue)) {
ret = av_fifo_realloc2(ifilter->frame_queue, 2 * av_fifo_size(ifilter->frame_queue));
if (ret < 0) {
av_frame_free(&tmp);
return ret;
}
}
av_fifo_generic_write(ifilter->frame_queue, &tmp, sizeof(tmp), NULL);
return 0;
}
}
ret = reap_filters(1);
if (ret < 0 && ret != AVERROR_EOF) {
av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", av_err2str(ret));
return ret;
}
ret = configure_filtergraph(fg);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Error reinitializing filters!\n");
return ret;
}
}
ret = av_buffersrc_add_frame_flags(ifilter->filter, frame, AV_BUFFERSRC_FLAG_PUSH);
if (ret < 0) {
if (ret != AVERROR_EOF)
av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", av_err2str(ret));
return ret;
}
return 0;
}
static int ifilter_send_eof(InputFilter *ifilter, int64_t pts)
{
int ret;
ifilter->eof = 1;
if (ifilter->filter) {
ret = av_buffersrc_close(ifilter->filter, pts, AV_BUFFERSRC_FLAG_PUSH);
if (ret < 0)
return ret;
} else {
// the filtergraph was never configured
if (ifilter->format < 0)
ifilter_parameters_from_codecpar(ifilter, ifilter->ist->st->codecpar);
if (ifilter->format < 0 && (ifilter->type == AVMEDIA_TYPE_AUDIO || ifilter->type == AVMEDIA_TYPE_VIDEO)) {
av_log(NULL, AV_LOG_ERROR, "Cannot determine format of input stream %d:%d after EOF\n", ifilter->ist->file_index, ifilter->ist->st->index);
return AVERROR_INVALIDDATA;
}
}
return 0;
}
// This does not quite work like avcodec_decode_audio4/avcodec_decode_video2.
// There is the following difference: if you got a frame, you must call
// it again with pkt=NULL. pkt==NULL is treated differently from pkt->size==0
// (pkt==NULL means get more output, pkt->size==0 is a flush/drain packet)
static int decode(AVCodecContext *avctx, AVFrame *frame, int *got_frame, AVPacket *pkt)
{
int ret;
*got_frame = 0;
if (pkt) {
ret = avcodec_send_packet(avctx, pkt);
// In particular, we don't expect AVERROR(EAGAIN), because we read all
// decoded frames with avcodec_receive_frame() until done.
if (ret < 0 && ret != AVERROR_EOF)
return ret;
}
ret = avcodec_receive_frame(avctx, frame);
if (ret < 0 && ret != AVERROR(EAGAIN))
return ret;
if (ret >= 0)
*got_frame = 1;
return 0;
}
static int send_frame_to_filters(InputStream *ist, AVFrame *decoded_frame)
{
int i, ret;
AVFrame *f;
av_assert1(ist->nb_filters > 0); /* ensure ret is initialized */
for (i = 0; i < ist->nb_filters; i++) {
if (i < ist->nb_filters - 1) {
f = ist->filter_frame;
ret = av_frame_ref(f, decoded_frame);
if (ret < 0)
break;
} else
f = decoded_frame;
ret = ifilter_send_frame(ist->filters[i], f);
if (ret == AVERROR_EOF)
ret = 0; /* ignore */
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR,
"Failed to inject frame into filter network: %s\n", av_err2str(ret));
break;
}
}
return ret;
}
static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output,
int *decode_failed)
{
AVFrame *decoded_frame;
AVCodecContext *avctx = ist->dec_ctx;
int ret, err = 0;
AVRational decoded_frame_tb;
if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
return AVERROR(ENOMEM);
if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
return AVERROR(ENOMEM);
decoded_frame = ist->decoded_frame;
update_benchmark(NULL);
ret = decode(avctx, decoded_frame, got_output, pkt);
update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
if (ret < 0)
*decode_failed = 1;
if (ret >= 0 && avctx->sample_rate <= 0) {
av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
ret = AVERROR_INVALIDDATA;
}
if (ret != AVERROR_EOF)
check_decode_result(ist, got_output, ret);
if (!*got_output || ret < 0)
return ret;
ist->samples_decoded += decoded_frame->nb_samples;
ist->frames_decoded++;
/* increment next_dts to use for the case where the input stream does not
have timestamps or there are multiple frames in the packet */
ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
avctx->sample_rate;
ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
avctx->sample_rate;
if (decoded_frame->pts != AV_NOPTS_VALUE) {
decoded_frame_tb = ist->st->time_base;
} else if (pkt && pkt->pts != AV_NOPTS_VALUE) {
decoded_frame->pts = pkt->pts;
decoded_frame_tb = ist->st->time_base;
}else {
decoded_frame->pts = ist->dts;
decoded_frame_tb = AV_TIME_BASE_Q;
}
if (decoded_frame->pts != AV_NOPTS_VALUE)
decoded_frame->pts = av_rescale_delta(decoded_frame_tb, decoded_frame->pts,
(AVRational){1, avctx->sample_rate}, decoded_frame->nb_samples, &ist->filter_in_rescale_delta_last,
(AVRational){1, avctx->sample_rate});
ist->nb_samples = decoded_frame->nb_samples;
err = send_frame_to_filters(ist, decoded_frame);
av_frame_unref(ist->filter_frame);
av_frame_unref(decoded_frame);
return err < 0 ? err : ret;
}
static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *duration_pts, int eof,
int *decode_failed)
{
AVFrame *decoded_frame;
int i, ret = 0, err = 0;
int64_t best_effort_timestamp;
int64_t dts = AV_NOPTS_VALUE;
AVPacket avpkt;
// With fate-indeo3-2, we're getting 0-sized packets before EOF for some
// reason. This seems like a semi-critical bug. Don't trigger EOF, and
// skip the packet.
if (!eof && pkt && pkt->size == 0)
return 0;
if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
return AVERROR(ENOMEM);
if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
return AVERROR(ENOMEM);
decoded_frame = ist->decoded_frame;
if (ist->dts != AV_NOPTS_VALUE)
dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
if (pkt) {
avpkt = *pkt;
avpkt.dts = dts; // ffmpeg.c probably shouldn't do this
}
// The old code used to set dts on the drain packet, which does not work
// with the new API anymore.
if (eof) {
void *new = av_realloc_array(ist->dts_buffer, ist->nb_dts_buffer + 1, sizeof(ist->dts_buffer[0]));
if (!new)
return AVERROR(ENOMEM);
ist->dts_buffer = new;
ist->dts_buffer[ist->nb_dts_buffer++] = dts;
}
update_benchmark(NULL);
ret = decode(ist->dec_ctx, decoded_frame, got_output, pkt ? &avpkt : NULL);
update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
if (ret < 0)
*decode_failed = 1;
// The following line may be required in some cases where there is no parser
// or the parser does not has_b_frames correctly
if (ist->st->codecpar->video_delay < ist->dec_ctx->has_b_frames) {
if (ist->dec_ctx->codec_id == AV_CODEC_ID_H264) {
ist->st->codecpar->video_delay = ist->dec_ctx->has_b_frames;
} else
av_log(ist->dec_ctx, AV_LOG_WARNING,
"video_delay is larger in decoder than demuxer %d > %d.\n"
"If you want to help, upload a sample "
"of this file to ftp://upload.ffmpeg.org/incoming/ "
"and contact the ffmpeg-devel mailing list. ([email protected])\n",
ist->dec_ctx->has_b_frames,
ist->st->codecpar->video_delay);
}
if (ret != AVERROR_EOF)
check_decode_result(ist, got_output, ret);
if (*got_output && ret >= 0) {
if (ist->dec_ctx->width != decoded_frame->width ||
ist->dec_ctx->height != decoded_frame->height ||
ist->dec_ctx->pix_fmt != decoded_frame->format) {
av_log(NULL, AV_LOG_DEBUG, "Frame parameters mismatch context %d,%d,%d != %d,%d,%d\n",
decoded_frame->width,
decoded_frame->height,
decoded_frame->format,
ist->dec_ctx->width,
ist->dec_ctx->height,
ist->dec_ctx->pix_fmt);
}
}
if (!*got_output || ret < 0)
return ret;
if(ist->top_field_first>=0)
decoded_frame->top_field_first = ist->top_field_first;
ist->frames_decoded++;
if (ist->hwaccel_retrieve_data && decoded_frame->format == ist->hwaccel_pix_fmt) {
err = ist->hwaccel_retrieve_data(ist->dec_ctx, decoded_frame);
if (err < 0)
goto fail;
}
ist->hwaccel_retrieved_pix_fmt = decoded_frame->format;
best_effort_timestamp= decoded_frame->best_effort_timestamp;
*duration_pts = decoded_frame->pkt_duration;
if (ist->framerate.num)
best_effort_timestamp = ist->cfr_next_pts++;
if (eof && best_effort_timestamp == AV_NOPTS_VALUE && ist->nb_dts_buffer > 0) {
best_effort_timestamp = ist->dts_buffer[0];
for (i = 0; i < ist->nb_dts_buffer - 1; i++)
ist->dts_buffer[i] = ist->dts_buffer[i + 1];
ist->nb_dts_buffer--;
}
if(best_effort_timestamp != AV_NOPTS_VALUE) {
int64_t ts = av_rescale_q(decoded_frame->pts = best_effort_timestamp, ist->st->time_base, AV_TIME_BASE_Q);
if (ts != AV_NOPTS_VALUE)
ist->next_pts = ist->pts = ts;
}
if (debug_ts) {
av_log(NULL, AV_LOG_INFO, "decoder -> ist_index:%d type:video "
"frame_pts:%s frame_pts_time:%s best_effort_ts:%"PRId64" best_effort_ts_time:%s keyframe:%d frame_type:%d time_base:%d/%d\n",
ist->st->index, av_ts2str(decoded_frame->pts),
av_ts2timestr(decoded_frame->pts, &ist->st->time_base),
best_effort_timestamp,
av_ts2timestr(best_effort_timestamp, &ist->st->time_base),
decoded_frame->key_frame, decoded_frame->pict_type,
ist->st->time_base.num, ist->st->time_base.den);
}
if (ist->st->sample_aspect_ratio.num)
decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
err = send_frame_to_filters(ist, decoded_frame);
fail:
av_frame_unref(ist->filter_frame);
av_frame_unref(decoded_frame);
return err < 0 ? err : ret;
}
static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output,
int *decode_failed)
{
AVSubtitle subtitle;
int free_sub = 1;
int i, ret = avcodec_decode_subtitle2(ist->dec_ctx,
&subtitle, got_output, pkt);
check_decode_result(NULL, got_output, ret);
if (ret < 0 || !*got_output) {
*decode_failed = 1;
if (!pkt->size)
sub2video_flush(ist);
return ret;
}
if (ist->fix_sub_duration) {
int end = 1;
if (ist->prev_sub.got_output) {
end = av_rescale(subtitle.pts - ist->prev_sub.subtitle.pts,
1000, AV_TIME_BASE);
if (end < ist->prev_sub.subtitle.end_display_time) {
av_log(ist->dec_ctx, AV_LOG_DEBUG,
"Subtitle duration reduced from %"PRId32" to %d%s\n",
ist->prev_sub.subtitle.end_display_time, end,
end <= 0 ? ", dropping it" : "");
ist->prev_sub.subtitle.end_display_time = end;
}
}
FFSWAP(int, *got_output, ist->prev_sub.got_output);
FFSWAP(int, ret, ist->prev_sub.ret);
FFSWAP(AVSubtitle, subtitle, ist->prev_sub.subtitle);
if (end <= 0)
goto out;
}
if (!*got_output)
return ret;
if (ist->sub2video.frame) {
sub2video_update(ist, &subtitle);
} else if (ist->nb_filters) {
if (!ist->sub2video.sub_queue)
ist->sub2video.sub_queue = av_fifo_alloc(8 * sizeof(AVSubtitle));
if (!ist->sub2video.sub_queue)
exit_program(1);
if (!av_fifo_space(ist->sub2video.sub_queue)) {
ret = av_fifo_realloc2(ist->sub2video.sub_queue, 2 * av_fifo_size(ist->sub2video.sub_queue));
if (ret < 0)
exit_program(1);
}
av_fifo_generic_write(ist->sub2video.sub_queue, &subtitle, sizeof(subtitle), NULL);
free_sub = 0;
}
if (!subtitle.num_rects)
goto out;
ist->frames_decoded++;
for (i = 0; i < nb_output_streams; i++) {
OutputStream *ost = output_streams[i];
if (!check_output_constraints(ist, ost) || !ost->encoding_needed
|| ost->enc->type != AVMEDIA_TYPE_SUBTITLE)
continue;
do_subtitle_out(output_files[ost->file_index], ost, &subtitle);
}
out:
if (free_sub)
avsubtitle_free(&subtitle);
return ret;
}
static int send_filter_eof(InputStream *ist)
{
int i, ret;
/* TODO keep pts also in stream time base to avoid converting back */
int64_t pts = av_rescale_q_rnd(ist->pts, AV_TIME_BASE_Q, ist->st->time_base,
AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
for (i = 0; i < ist->nb_filters; i++) {
ret = ifilter_send_eof(ist->filters[i], pts);
if (ret < 0)
return ret;
}
return 0;
}
/* pkt = NULL means EOF (needed to flush decoder buffers) */
static int process_input_packet(InputStream *ist, const AVPacket *pkt, int no_eof)
{
int ret = 0, i;
int repeating = 0;
int eof_reached = 0;
AVPacket avpkt;
if (!ist->saw_first_ts) {
ist->dts = ist->st->avg_frame_rate.num ? - ist->dec_ctx->has_b_frames * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
ist->pts = 0;
if (pkt && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
}
ist->saw_first_ts = 1;
}
if (ist->next_dts == AV_NOPTS_VALUE)
ist->next_dts = ist->dts;
if (ist->next_pts == AV_NOPTS_VALUE)
ist->next_pts = ist->pts;
if (!pkt) {
/* EOF handling */
av_init_packet(&avpkt);
avpkt.data = NULL;
avpkt.size = 0;
} else {
avpkt = *pkt;
}
if (pkt && pkt->dts != AV_NOPTS_VALUE) {
ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
if (ist->dec_ctx->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
ist->next_pts = ist->pts = ist->dts;
}
// while we have more to decode or while the decoder did output something on EOF
while (ist->decoding_needed) {
int64_t duration_dts = 0;
int64_t duration_pts = 0;
int got_output = 0;
int decode_failed = 0;
ist->pts = ist->next_pts;
ist->dts = ist->next_dts;
switch (ist->dec_ctx->codec_type) {
case AVMEDIA_TYPE_AUDIO:
ret = decode_audio (ist, repeating ? NULL : &avpkt, &got_output,
&decode_failed);
break;
case AVMEDIA_TYPE_VIDEO:
ret = decode_video (ist, repeating ? NULL : &avpkt, &got_output, &duration_pts, !pkt,
&decode_failed);
if (!repeating || !pkt || got_output) {
if (pkt && pkt->duration) {
duration_dts = av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
} else if(ist->dec_ctx->framerate.num != 0 && ist->dec_ctx->framerate.den != 0) {
int ticks= av_stream_get_parser(ist->st) ? av_stream_get_parser(ist->st)->repeat_pict+1 : ist->dec_ctx->ticks_per_frame;
duration_dts = ((int64_t)AV_TIME_BASE *
ist->dec_ctx->framerate.den * ticks) /
ist->dec_ctx->framerate.num / ist->dec_ctx->ticks_per_frame;
}
if(ist->dts != AV_NOPTS_VALUE && duration_dts) {
ist->next_dts += duration_dts;
}else
ist->next_dts = AV_NOPTS_VALUE;
}
if (got_output) {
if (duration_pts > 0) {
ist->next_pts += av_rescale_q(duration_pts, ist->st->time_base, AV_TIME_BASE_Q);
} else {
ist->next_pts += duration_dts;
}
}
break;
case AVMEDIA_TYPE_SUBTITLE:
if (repeating)
break;
ret = transcode_subtitles(ist, &avpkt, &got_output, &decode_failed);
if (!pkt && ret >= 0)
ret = AVERROR_EOF;
break;
default:
return -1;
}
if (ret == AVERROR_EOF) {
eof_reached = 1;
break;
}
if (ret < 0) {
if (decode_failed) {
av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",
ist->file_index, ist->st->index, av_err2str(ret));
} else {
av_log(NULL, AV_LOG_FATAL, "Error while processing the decoded "
"data for stream #%d:%d\n", ist->file_index, ist->st->index);
}
if (!decode_failed || exit_on_error)
exit_program(1);
break;
}
if (got_output)
ist->got_output = 1;
if (!got_output)
break;
// During draining, we might get multiple output frames in this loop.
// ffmpeg.c does not drain the filter chain on configuration changes,
// which means if we send multiple frames at once to the filters, and
// one of those frames changes configuration, the buffered frames will
// be lost. This can upset certain FATE tests.
// Decode only 1 frame per call on EOF to appease these FATE tests.
// The ideal solution would be to rewrite decoding to use the new
// decoding API in a better way.
if (!pkt)
break;
repeating = 1;
}
/* after flushing, send an EOF on all the filter inputs attached to the stream */
/* except when looping we need to flush but not to send an EOF */
if (!pkt && ist->decoding_needed && eof_reached && !no_eof) {
int ret = send_filter_eof(ist);
if (ret < 0) {
av_log(NULL, AV_LOG_FATAL, "Error marking filters as finished\n");
exit_program(1);
}
}
/* handle stream copy */
if (!ist->decoding_needed && pkt) {
ist->dts = ist->next_dts;
switch (ist->dec_ctx->codec_type) {
case AVMEDIA_TYPE_AUDIO:
av_assert1(pkt->duration >= 0);
if (ist->dec_ctx->sample_rate) {
ist->next_dts += ((int64_t)AV_TIME_BASE * ist->dec_ctx->frame_size) /
ist->dec_ctx->sample_rate;
} else {
ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
}
break;
case AVMEDIA_TYPE_VIDEO:
if (ist->framerate.num) {
// TODO: Remove work-around for c99-to-c89 issue 7
AVRational time_base_q = AV_TIME_BASE_Q;
int64_t next_dts = av_rescale_q(ist->next_dts, time_base_q, av_inv_q(ist->framerate));
ist->next_dts = av_rescale_q(next_dts + 1, av_inv_q(ist->framerate), time_base_q);
} else if (pkt->duration) {
ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
} else if(ist->dec_ctx->framerate.num != 0) {
int ticks= av_stream_get_parser(ist->st) ? av_stream_get_parser(ist->st)->repeat_pict + 1 : ist->dec_ctx->ticks_per_frame;
ist->next_dts += ((int64_t)AV_TIME_BASE *
ist->dec_ctx->framerate.den * ticks) /
ist->dec_ctx->framerate.num / ist->dec_ctx->ticks_per_frame;
}
break;
}
ist->pts = ist->dts;
ist->next_pts = ist->next_dts;
}
for (i = 0; i < nb_output_streams; i++) {
OutputStream *ost = output_streams[i];
if (!check_output_constraints(ist, ost) || ost->encoding_needed)
continue;
do_streamcopy(ist, ost, pkt);
}
return !eof_reached;
}
static void print_sdp(void)
{
char sdp[16384];
int i;
int j;
AVIOContext *sdp_pb;
AVFormatContext **avc;
for (i = 0; i < nb_output_files; i++) {
if (!output_files[i]->header_written)
return;
}
avc = av_malloc_array(nb_output_files, sizeof(*avc));
if (!avc)
exit_program(1);
for (i = 0, j = 0; i < nb_output_files; i++) {
if (!strcmp(output_files[i]->ctx->oformat->name, "rtp")) {
avc[j] = output_files[i]->ctx;
j++;
}
}
if (!j)
goto fail;
av_sdp_create(avc, j, sdp, sizeof(sdp));
if (!sdp_filename) {
printf("SDP:\n%s\n", sdp);
fflush(stdout);
} else {
if (avio_open2(&sdp_pb, sdp_filename, AVIO_FLAG_WRITE, &int_cb, NULL) < 0) {
av_log(NULL, AV_LOG_ERROR, "Failed to open sdp file '%s'\n", sdp_filename);
} else {
avio_printf(sdp_pb, "SDP:\n%s", sdp);
avio_closep(&sdp_pb);
av_freep(&sdp_filename);
}
}
fail:
av_freep(&avc);
}
static enum AVPixelFormat get_format(AVCodecContext *s, const enum AVPixelFormat *pix_fmts)
{
InputStream *ist = s->opaque;
const enum AVPixelFormat *p;
int ret;
for (p = pix_fmts; *p != AV_PIX_FMT_NONE; p++) {
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p);
const AVCodecHWConfig *config = NULL;
int i;
if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
break;
if (ist->hwaccel_id == HWACCEL_GENERIC ||
ist->hwaccel_id == HWACCEL_AUTO) {
for (i = 0;; i++) {
config = avcodec_get_hw_config(s->codec, i);
if (!config)
break;
if (!(config->methods &
AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
continue;
if (config->pix_fmt == *p)
break;
}
}
if (config) {
if (config->device_type != ist->hwaccel_device_type) {
// Different hwaccel offered, ignore.
continue;
}
ret = hwaccel_decode_init(s);
if (ret < 0) {
if (ist->hwaccel_id == HWACCEL_GENERIC) {
av_log(NULL, AV_LOG_FATAL,
"%s hwaccel requested for input stream #%d:%d, "
"but cannot be initialized.\n",
av_hwdevice_get_type_name(config->device_type),
ist->file_index, ist->st->index);
return AV_PIX_FMT_NONE;
}
continue;
}
} else {
const HWAccel *hwaccel = NULL;
int i;
for (i = 0; hwaccels[i].name; i++) {
if (hwaccels[i].pix_fmt == *p) {
hwaccel = &hwaccels[i];
break;
}
}
if (!hwaccel) {
// No hwaccel supporting this pixfmt.
continue;
}
if (hwaccel->id != ist->hwaccel_id) {
// Does not match requested hwaccel.
continue;
}
ret = hwaccel->init(s);
if (ret < 0) {
av_log(NULL, AV_LOG_FATAL,
"%s hwaccel requested for input stream #%d:%d, "
"but cannot be initialized.\n", hwaccel->name,
ist->file_index, ist->st->index);
return AV_PIX_FMT_NONE;
}
}
if (ist->hw_frames_ctx) {
s->hw_frames_ctx = av_buffer_ref(ist->hw_frames_ctx);
if (!s->hw_frames_ctx)
return AV_PIX_FMT_NONE;
}
ist->hwaccel_pix_fmt = *p;
break;
}
return *p;
}
static int get_buffer(AVCodecContext *s, AVFrame *frame, int flags)
{
InputStream *ist = s->opaque;
if (ist->hwaccel_get_buffer && frame->format == ist->hwaccel_pix_fmt)
return ist->hwaccel_get_buffer(s, frame, flags);
return avcodec_default_get_buffer2(s, frame, flags);
}
static int init_input_stream(int ist_index, char *error, int error_len)
{
int ret;
InputStream *ist = input_streams[ist_index];
if (ist->decoding_needed) {
AVCodec *codec = ist->dec;
if (!codec) {
snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
avcodec_get_name(ist->dec_ctx->codec_id), ist->file_index, ist->st->index);
return AVERROR(EINVAL);
}
ist->dec_ctx->opaque = ist;
ist->dec_ctx->get_format = get_format;
ist->dec_ctx->get_buffer2 = get_buffer;
ist->dec_ctx->thread_safe_callbacks = 1;
av_opt_set_int(ist->dec_ctx, "refcounted_frames", 1, 0);
if (ist->dec_ctx->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
(ist->decoding_needed & DECODING_FOR_OST)) {
av_dict_set(&ist->decoder_opts, "compute_edt", "1", AV_DICT_DONT_OVERWRITE);
if (ist->decoding_needed & DECODING_FOR_FILTER)
av_log(NULL, AV_LOG_WARNING, "Warning using DVB subtitles for filtering and output at the same time is not fully supported, also see -compute_edt [0|1]\n");
}
av_dict_set(&ist->decoder_opts, "sub_text_format", "ass", AV_DICT_DONT_OVERWRITE);
/* Useful for subtitles retiming by lavf (FIXME), skipping samples in
* audio, and video decoders such as cuvid or mediacodec */
ist->dec_ctx->pkt_timebase = ist->st->time_base;
if (!av_dict_get(ist->decoder_opts, "threads", NULL, 0))
av_dict_set(&ist->decoder_opts, "threads", "auto", 0);
/* Attached pics are sparse, therefore we would not want to delay their decoding till EOF. */
if (ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC)
av_dict_set(&ist->decoder_opts, "threads", "1", 0);
ret = hw_device_setup_for_decode(ist);
if (ret < 0) {
snprintf(error, error_len, "Device setup failed for "
"decoder on input stream #%d:%d : %s",
ist->file_index, ist->st->index, av_err2str(ret));
return ret;
}
if ((ret = avcodec_open2(ist->dec_ctx, codec, &ist->decoder_opts)) < 0) {
if (ret == AVERROR_EXPERIMENTAL)
abort_codec_experimental(codec, 0);
snprintf(error, error_len,
"Error while opening decoder for input stream "
"#%d:%d : %s",
ist->file_index, ist->st->index, av_err2str(ret));
return ret;
}
assert_avoptions(ist->decoder_opts);
}
ist->next_pts = AV_NOPTS_VALUE;
ist->next_dts = AV_NOPTS_VALUE;
return 0;
}
static InputStream *get_input_stream(OutputStream *ost)
{
if (ost->source_index >= 0)
return input_streams[ost->source_index];
return NULL;
}
static int compare_int64(const void *a, const void *b)
{
return FFDIFFSIGN(*(const int64_t *)a, *(const int64_t *)b);
}
/* open the muxer when all the streams are initialized */
static int check_init_output_file(OutputFile *of, int file_index)
{
int ret, i;
for (i = 0; i < of->ctx->nb_streams; i++) {
OutputStream *ost = output_streams[of->ost_index + i];
if (!ost->initialized)
return 0;
}
of->ctx->interrupt_callback = int_cb;
ret = avformat_write_header(of->ctx, &of->opts);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR,
"Could not write header for output file #%d "
"(incorrect codec parameters ?): %s\n",
file_index, av_err2str(ret));
return ret;
}
//assert_avoptions(of->opts);
of->header_written = 1;
av_dump_format(of->ctx, file_index, of->ctx->url, 1);
if (sdp_filename || want_sdp)
print_sdp();
/* flush the muxing queues */
for (i = 0; i < of->ctx->nb_streams; i++) {
OutputStream *ost = output_streams[of->ost_index + i];
/* try to improve muxing time_base (only possible if nothing has been written yet) */
if (!av_fifo_size(ost->muxing_queue))
ost->mux_timebase = ost->st->time_base;
while (av_fifo_size(ost->muxing_queue)) {
AVPacket pkt;
av_fifo_generic_read(ost->muxing_queue, &pkt, sizeof(pkt), NULL);
write_packet(of, &pkt, ost, 1);
}
}
return 0;
}
static int init_output_bsfs(OutputStream *ost)
{
AVBSFContext *ctx;
int i, ret;
if (!ost->nb_bitstream_filters)
return 0;
for (i = 0; i < ost->nb_bitstream_filters; i++) {
ctx = ost->bsf_ctx[i];
ret = avcodec_parameters_copy(ctx->par_in,
i ? ost->bsf_ctx[i - 1]->par_out : ost->st->codecpar);
if (ret < 0)
return ret;
ctx->time_base_in = i ? ost->bsf_ctx[i - 1]->time_base_out : ost->st->time_base;
ret = av_bsf_init(ctx);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Error initializing bitstream filter: %s\n",
ost->bsf_ctx[i]->filter->name);
return ret;
}
}
ctx = ost->bsf_ctx[ost->nb_bitstream_filters - 1];
ret = avcodec_parameters_copy(ost->st->codecpar, ctx->par_out);
if (ret < 0)
return ret;
ost->st->time_base = ctx->time_base_out;
return 0;
}
static int init_output_stream_streamcopy(OutputStream *ost)
{
OutputFile *of = output_files[ost->file_index];
InputStream *ist = get_input_stream(ost);
AVCodecParameters *par_dst = ost->st->codecpar;
AVCodecParameters *par_src = ost->ref_par;
AVRational sar;
int i, ret;
uint32_t codec_tag = par_dst->codec_tag;
av_assert0(ist && !ost->filter);
ret = avcodec_parameters_to_context(ost->enc_ctx, ist->st->codecpar);
if (ret >= 0)
ret = av_opt_set_dict(ost->enc_ctx, &ost->encoder_opts);
if (ret < 0) {
av_log(NULL, AV_LOG_FATAL,
"Error setting up codec context options.\n");
return ret;
}
ret = avcodec_parameters_from_context(par_src, ost->enc_ctx);
if (ret < 0) {
av_log(NULL, AV_LOG_FATAL,
"Error getting reference codec parameters.\n");
return ret;
}
if (!codec_tag) {
unsigned int codec_tag_tmp;
if (!of->ctx->oformat->codec_tag ||
av_codec_get_id (of->ctx->oformat->codec_tag, par_src->codec_tag) == par_src->codec_id ||
!av_codec_get_tag2(of->ctx->oformat->codec_tag, par_src->codec_id, &codec_tag_tmp))
codec_tag = par_src->codec_tag;
}
ret = avcodec_parameters_copy(par_dst, par_src);
if (ret < 0)
return ret;
par_dst->codec_tag = codec_tag;
if (!ost->frame_rate.num)
ost->frame_rate = ist->framerate;
ost->st->avg_frame_rate = ost->frame_rate;
ret = avformat_transfer_internal_stream_timing_info(of->ctx->oformat, ost->st, ist->st, copy_tb);
if (ret < 0)
return ret;
// copy timebase while removing common factors
if (ost->st->time_base.num <= 0 || ost->st->time_base.den <= 0)
ost->st->time_base = av_add_q(av_stream_get_codec_timebase(ost->st), (AVRational){0, 1});
// copy estimated duration as a hint to the muxer
if (ost->st->duration <= 0 && ist->st->duration > 0)
ost->st->duration = av_rescale_q(ist->st->duration, ist->st->time_base, ost->st->time_base);
// copy disposition
ost->st->disposition = ist->st->disposition;
if (ist->st->nb_side_data) {
for (i = 0; i < ist->st->nb_side_data; i++) {
const AVPacketSideData *sd_src = &ist->st->side_data[i];
uint8_t *dst_data;
dst_data = av_stream_new_side_data(ost->st, sd_src->type, sd_src->size);
if (!dst_data)
return AVERROR(ENOMEM);
memcpy(dst_data, sd_src->data, sd_src->size);
}
}
if (ost->rotate_overridden) {
uint8_t *sd = av_stream_new_side_data(ost->st, AV_PKT_DATA_DISPLAYMATRIX,
sizeof(int32_t) * 9);
if (sd)
av_display_rotation_set((int32_t *)sd, -ost->rotate_override_value);
}
switch (par_dst->codec_type) {
case AVMEDIA_TYPE_AUDIO:
if (audio_volume != 256) {
av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
exit_program(1);
}
if((par_dst->block_align == 1 || par_dst->block_align == 1152 || par_dst->block_align == 576) && par_dst->codec_id == AV_CODEC_ID_MP3)
par_dst->block_align= 0;
if(par_dst->codec_id == AV_CODEC_ID_AC3)
par_dst->block_align= 0;
break;
case AVMEDIA_TYPE_VIDEO:
if (ost->frame_aspect_ratio.num) { // overridden by the -aspect cli option
sar =
av_mul_q(ost->frame_aspect_ratio,
(AVRational){ par_dst->height, par_dst->width });
av_log(NULL, AV_LOG_WARNING, "Overriding aspect ratio "
"with stream copy may produce invalid files\n");
}
else if (ist->st->sample_aspect_ratio.num)
sar = ist->st->sample_aspect_ratio;
else
sar = par_src->sample_aspect_ratio;
ost->st->sample_aspect_ratio = par_dst->sample_aspect_ratio = sar;
ost->st->avg_frame_rate = ist->st->avg_frame_rate;
ost->st->r_frame_rate = ist->st->r_frame_rate;
break;
}
ost->mux_timebase = ist->st->time_base;
return 0;
}
static void set_encoder_id(OutputFile *of, OutputStream *ost)
{
AVDictionaryEntry *e;
uint8_t *encoder_string;
int encoder_string_len;
int format_flags = 0;
int codec_flags = ost->enc_ctx->flags;
if (av_dict_get(ost->st->metadata, "encoder", NULL, 0))
return;
e = av_dict_get(of->opts, "fflags", NULL, 0);
if (e) {
const AVOption *o = av_opt_find(of->ctx, "fflags", NULL, 0, 0);
if (!o)
return;
av_opt_eval_flags(of->ctx, o, e->value, &format_flags);
}
e = av_dict_get(ost->encoder_opts, "flags", NULL, 0);
if (e) {
const AVOption *o = av_opt_find(ost->enc_ctx, "flags", NULL, 0, 0);
if (!o)
return;
av_opt_eval_flags(ost->enc_ctx, o, e->value, &codec_flags);
}
encoder_string_len = sizeof(LIBAVCODEC_IDENT) + strlen(ost->enc->name) + 2;
encoder_string = av_mallocz(encoder_string_len);
if (!encoder_string)
exit_program(1);
if (!(format_flags & AVFMT_FLAG_BITEXACT) && !(codec_flags & AV_CODEC_FLAG_BITEXACT))
av_strlcpy(encoder_string, LIBAVCODEC_IDENT " ", encoder_string_len);
else
av_strlcpy(encoder_string, "Lavc ", encoder_string_len);
av_strlcat(encoder_string, ost->enc->name, encoder_string_len);
av_dict_set(&ost->st->metadata, "encoder", encoder_string,
AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_OVERWRITE);
}
static void parse_forced_key_frames(char *kf, OutputStream *ost,
AVCodecContext *avctx)
{
char *p;
int n = 1, i, size, index = 0;
int64_t t, *pts;
for (p = kf; *p; p++)
if (*p == ',')
n++;
size = n;
pts = av_malloc_array(size, sizeof(*pts));
if (!pts) {
av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
exit_program(1);
}
p = kf;
for (i = 0; i < n; i++) {
char *next = strchr(p, ',');
if (next)
*next++ = 0;
if (!memcmp(p, "chapters", 8)) {
AVFormatContext *avf = output_files[ost->file_index]->ctx;
int j;
if (avf->nb_chapters > INT_MAX - size ||
!(pts = av_realloc_f(pts, size += avf->nb_chapters - 1,
sizeof(*pts)))) {
av_log(NULL, AV_LOG_FATAL,
"Could not allocate forced key frames array.\n");
exit_program(1);
}
t = p[8] ? parse_time_or_die("force_key_frames", p + 8, 1) : 0;
t = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
for (j = 0; j < avf->nb_chapters; j++) {
AVChapter *c = avf->chapters[j];
av_assert1(index < size);
pts[index++] = av_rescale_q(c->start, c->time_base,
avctx->time_base) + t;
}
} else {
t = parse_time_or_die("force_key_frames", p, 1);
av_assert1(index < size);
pts[index++] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
}
p = next;
}
av_assert0(index == size);
qsort(pts, size, sizeof(*pts), compare_int64);
ost->forced_kf_count = size;
ost->forced_kf_pts = pts;
}
static void init_encoder_time_base(OutputStream *ost, AVRational default_time_base)
{
InputStream *ist = get_input_stream(ost);
AVCodecContext *enc_ctx = ost->enc_ctx;
AVFormatContext *oc;
if (ost->enc_timebase.num > 0) {
enc_ctx->time_base = ost->enc_timebase;
return;
}
if (ost->enc_timebase.num < 0) {
if (ist) {
enc_ctx->time_base = ist->st->time_base;
return;
}
oc = output_files[ost->file_index]->ctx;
av_log(oc, AV_LOG_WARNING, "Input stream data not available, using default time base\n");
}
enc_ctx->time_base = default_time_base;
}
static int init_output_stream_encode(OutputStream *ost)
{
InputStream *ist = get_input_stream(ost);
AVCodecContext *enc_ctx = ost->enc_ctx;
AVCodecContext *dec_ctx = NULL;
AVFormatContext *oc = output_files[ost->file_index]->ctx;
int j, ret;
set_encoder_id(output_files[ost->file_index], ost);
// Muxers use AV_PKT_DATA_DISPLAYMATRIX to signal rotation. On the other
// hand, the legacy API makes demuxers set "rotate" metadata entries,
// which have to be filtered out to prevent leaking them to output files.
av_dict_set(&ost->st->metadata, "rotate", NULL, 0);
if (ist) {
ost->st->disposition = ist->st->disposition;
dec_ctx = ist->dec_ctx;
enc_ctx->chroma_sample_location = dec_ctx->chroma_sample_location;
} else {
for (j = 0; j < oc->nb_streams; j++) {
AVStream *st = oc->streams[j];
if (st != ost->st && st->codecpar->codec_type == ost->st->codecpar->codec_type)
break;
}
if (j == oc->nb_streams)
if (ost->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO ||
ost->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
ost->st->disposition = AV_DISPOSITION_DEFAULT;
}
if (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
if (!ost->frame_rate.num)
ost->frame_rate = av_buffersink_get_frame_rate(ost->filter->filter);
if (ist && !ost->frame_rate.num)
ost->frame_rate = ist->framerate;
if (ist && !ost->frame_rate.num)
ost->frame_rate = ist->st->r_frame_rate;
if (ist && !ost->frame_rate.num) {
ost->frame_rate = (AVRational){25, 1};
av_log(NULL, AV_LOG_WARNING,
"No information "
"about the input framerate is available. Falling "
"back to a default value of 25fps for output stream #%d:%d. Use the -r option "
"if you want a different framerate.\n",
ost->file_index, ost->index);
}
if (ost->enc->supported_framerates && !ost->force_fps) {
int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
ost->frame_rate = ost->enc->supported_framerates[idx];
}
// reduce frame rate for mpeg4 to be within the spec limits
if (enc_ctx->codec_id == AV_CODEC_ID_MPEG4) {
av_reduce(&ost->frame_rate.num, &ost->frame_rate.den,
ost->frame_rate.num, ost->frame_rate.den, 65535);
}
}
switch (enc_ctx->codec_type) {
case AVMEDIA_TYPE_AUDIO:
enc_ctx->sample_fmt = av_buffersink_get_format(ost->filter->filter);
if (dec_ctx)
enc_ctx->bits_per_raw_sample = FFMIN(dec_ctx->bits_per_raw_sample,
av_get_bytes_per_sample(enc_ctx->sample_fmt) << 3);
enc_ctx->sample_rate = av_buffersink_get_sample_rate(ost->filter->filter);
enc_ctx->channel_layout = av_buffersink_get_channel_layout(ost->filter->filter);
enc_ctx->channels = av_buffersink_get_channels(ost->filter->filter);
init_encoder_time_base(ost, av_make_q(1, enc_ctx->sample_rate));
break;
case AVMEDIA_TYPE_VIDEO:
init_encoder_time_base(ost, av_inv_q(ost->frame_rate));
if (!(enc_ctx->time_base.num && enc_ctx->time_base.den))
enc_ctx->time_base = av_buffersink_get_time_base(ost->filter->filter);
if ( av_q2d(enc_ctx->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
&& (video_sync_method == VSYNC_CFR || video_sync_method == VSYNC_VSCFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
"Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
}
for (j = 0; j < ost->forced_kf_count; j++)
ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
AV_TIME_BASE_Q,
enc_ctx->time_base);
enc_ctx->width = av_buffersink_get_w(ost->filter->filter);
enc_ctx->height = av_buffersink_get_h(ost->filter->filter);
enc_ctx->sample_aspect_ratio = ost->st->sample_aspect_ratio =
ost->frame_aspect_ratio.num ? // overridden by the -aspect cli option
av_mul_q(ost->frame_aspect_ratio, (AVRational){ enc_ctx->height, enc_ctx->width }) :
av_buffersink_get_sample_aspect_ratio(ost->filter->filter);
enc_ctx->pix_fmt = av_buffersink_get_format(ost->filter->filter);
if (dec_ctx)
enc_ctx->bits_per_raw_sample = FFMIN(dec_ctx->bits_per_raw_sample,
av_pix_fmt_desc_get(enc_ctx->pix_fmt)->comp[0].depth);
enc_ctx->framerate = ost->frame_rate;
ost->st->avg_frame_rate = ost->frame_rate;
if (!dec_ctx ||
enc_ctx->width != dec_ctx->width ||
enc_ctx->height != dec_ctx->height ||
enc_ctx->pix_fmt != dec_ctx->pix_fmt) {
enc_ctx->bits_per_raw_sample = frame_bits_per_raw_sample;
}
if (ost->top_field_first == 0) {
enc_ctx->field_order = AV_FIELD_BB;
} else if (ost->top_field_first == 1) {
enc_ctx->field_order = AV_FIELD_TT;
}
if (ost->forced_keyframes) {
if (!strncmp(ost->forced_keyframes, "expr:", 5)) {
ret = av_expr_parse(&ost->forced_keyframes_pexpr, ost->forced_keyframes+5,
forced_keyframes_const_names, NULL, NULL, NULL, NULL, 0, NULL);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR,
"Invalid force_key_frames expression '%s'\n", ost->forced_keyframes+5);
return ret;
}
ost->forced_keyframes_expr_const_values[FKF_N] = 0;
ost->forced_keyframes_expr_const_values[FKF_N_FORCED] = 0;
ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] = NAN;
ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] = NAN;
// Don't parse the 'forced_keyframes' in case of 'keep-source-keyframes',
// parse it only for static kf timings
} else if(strncmp(ost->forced_keyframes, "source", 6)) {
parse_forced_key_frames(ost->forced_keyframes, ost, ost->enc_ctx);
}
}
break;
case AVMEDIA_TYPE_SUBTITLE:
enc_ctx->time_base = AV_TIME_BASE_Q;
if (!enc_ctx->width) {
enc_ctx->width = input_streams[ost->source_index]->st->codecpar->width;
enc_ctx->height = input_streams[ost->source_index]->st->codecpar->height;
}
break;
case AVMEDIA_TYPE_DATA:
break;
default:
abort();
break;
}
ost->mux_timebase = enc_ctx->time_base;
return 0;
}
static int init_output_stream(OutputStream *ost, char *error, int error_len)
{
int ret = 0;
if (ost->encoding_needed) {
AVCodec *codec = ost->enc;
AVCodecContext *dec = NULL;
InputStream *ist;
ret = init_output_stream_encode(ost);
if (ret < 0)
return ret;
if ((ist = get_input_stream(ost)))
dec = ist->dec_ctx;
if (dec && dec->subtitle_header) {
/* ASS code assumes this buffer is null terminated so add extra byte. */
ost->enc_ctx->subtitle_header = av_mallocz(dec->subtitle_header_size + 1);
if (!ost->enc_ctx->subtitle_header)
return AVERROR(ENOMEM);
memcpy(ost->enc_ctx->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
ost->enc_ctx->subtitle_header_size = dec->subtitle_header_size;
}
if (!av_dict_get(ost->encoder_opts, "threads", NULL, 0))
av_dict_set(&ost->encoder_opts, "threads", "auto", 0);
if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
!codec->defaults &&
!av_dict_get(ost->encoder_opts, "b", NULL, 0) &&
!av_dict_get(ost->encoder_opts, "ab", NULL, 0))
av_dict_set(&ost->encoder_opts, "b", "128000", 0);
if (ost->filter && av_buffersink_get_hw_frames_ctx(ost->filter->filter) &&
((AVHWFramesContext*)av_buffersink_get_hw_frames_ctx(ost->filter->filter)->data)->format ==
av_buffersink_get_format(ost->filter->filter)) {
ost->enc_ctx->hw_frames_ctx = av_buffer_ref(av_buffersink_get_hw_frames_ctx(ost->filter->filter));
if (!ost->enc_ctx->hw_frames_ctx)
return AVERROR(ENOMEM);
} else {
ret = hw_device_setup_for_encode(ost);
if (ret < 0) {
snprintf(error, error_len, "Device setup failed for "
"encoder on output stream #%d:%d : %s",
ost->file_index, ost->index, av_err2str(ret));
return ret;
}
}
if (ist && ist->dec->type == AVMEDIA_TYPE_SUBTITLE && ost->enc->type == AVMEDIA_TYPE_SUBTITLE) {
int input_props = 0, output_props = 0;
AVCodecDescriptor const *input_descriptor =
avcodec_descriptor_get(dec->codec_id);
AVCodecDescriptor const *output_descriptor =
avcodec_descriptor_get(ost->enc_ctx->codec_id);
if (input_descriptor)
input_props = input_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
if (output_descriptor)
output_props = output_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
if (input_props && output_props && input_props != output_props) {
snprintf(error, error_len,
"Subtitle encoding currently only possible from text to text "
"or bitmap to bitmap");
return AVERROR_INVALIDDATA;
}
}
if ((ret = avcodec_open2(ost->enc_ctx, codec, &ost->encoder_opts)) < 0) {
if (ret == AVERROR_EXPERIMENTAL)
abort_codec_experimental(codec, 1);
snprintf(error, error_len,
"Error while opening encoder for output stream #%d:%d - "
"maybe incorrect parameters such as bit_rate, rate, width or height",
ost->file_index, ost->index);
return ret;
}
if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
!(ost->enc->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE))
av_buffersink_set_frame_size(ost->filter->filter,
ost->enc_ctx->frame_size);
assert_avoptions(ost->encoder_opts);
if (ost->enc_ctx->bit_rate && ost->enc_ctx->bit_rate < 1000 &&
ost->enc_ctx->codec_id != AV_CODEC_ID_CODEC2 /* don't complain about 700 bit/s modes */)
av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
" It takes bits/s as argument, not kbits/s\n");
ret = avcodec_parameters_from_context(ost->st->codecpar, ost->enc_ctx);
if (ret < 0) {
av_log(NULL, AV_LOG_FATAL,
"Error initializing the output stream codec context.\n");
exit_program(1);
}
/*
* FIXME: ost->st->codec should't be needed here anymore.
*/
ret = avcodec_copy_context(ost->st->codec, ost->enc_ctx);
if (ret < 0)
return ret;
if (ost->enc_ctx->nb_coded_side_data) {
int i;
for (i = 0; i < ost->enc_ctx->nb_coded_side_data; i++) {
const AVPacketSideData *sd_src = &ost->enc_ctx->coded_side_data[i];
uint8_t *dst_data;
dst_data = av_stream_new_side_data(ost->st, sd_src->type, sd_src->size);
if (!dst_data)
return AVERROR(ENOMEM);
memcpy(dst_data, sd_src->data, sd_src->size);
}
}
/*
* Add global input side data. For now this is naive, and copies it
* from the input stream's global side data. All side data should
* really be funneled over AVFrame and libavfilter, then added back to
* packet side data, and then potentially using the first packet for
* global side data.
*/
if (ist) {
int i;
for (i = 0; i < ist->st->nb_side_data; i++) {
AVPacketSideData *sd = &ist->st->side_data[i];
uint8_t *dst = av_stream_new_side_data(ost->st, sd->type, sd->size);
if (!dst)
return AVERROR(ENOMEM);
memcpy(dst, sd->data, sd->size);
if (ist->autorotate && sd->type == AV_PKT_DATA_DISPLAYMATRIX)
av_display_rotation_set((uint32_t *)dst, 0);
}
}
// copy timebase while removing common factors
if (ost->st->time_base.num <= 0 || ost->st->time_base.den <= 0)
ost->st->time_base = av_add_q(ost->enc_ctx->time_base, (AVRational){0, 1});
// copy estimated duration as a hint to the muxer
if (ost->st->duration <= 0 && ist && ist->st->duration > 0)
ost->st->duration = av_rescale_q(ist->st->duration, ist->st->time_base, ost->st->time_base);
ost->st->codec->codec= ost->enc_ctx->codec;
} else if (ost->stream_copy) {
ret = init_output_stream_streamcopy(ost);
if (ret < 0)
return ret;
}
// parse user provided disposition, and update stream values
if (ost->disposition) {
static const AVOption opts[] = {
{ "disposition" , NULL, 0, AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT64_MIN, INT64_MAX, .unit = "flags" },
{ "default" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DEFAULT }, .unit = "flags" },
{ "dub" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DUB }, .unit = "flags" },
{ "original" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_ORIGINAL }, .unit = "flags" },
{ "comment" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_COMMENT }, .unit = "flags" },
{ "lyrics" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_LYRICS }, .unit = "flags" },
{ "karaoke" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_KARAOKE }, .unit = "flags" },
{ "forced" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_FORCED }, .unit = "flags" },
{ "hearing_impaired" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_HEARING_IMPAIRED }, .unit = "flags" },
{ "visual_impaired" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_VISUAL_IMPAIRED }, .unit = "flags" },
{ "clean_effects" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CLEAN_EFFECTS }, .unit = "flags" },
{ "attached_pic" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_ATTACHED_PIC }, .unit = "flags" },
{ "captions" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CAPTIONS }, .unit = "flags" },
{ "descriptions" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DESCRIPTIONS }, .unit = "flags" },
{ "dependent" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DEPENDENT }, .unit = "flags" },
{ "metadata" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_METADATA }, .unit = "flags" },
{ NULL },
};
static const AVClass class = {
.class_name = "",
.item_name = av_default_item_name,
.option = opts,
.version = LIBAVUTIL_VERSION_INT,
};
const AVClass *pclass = &class;
ret = av_opt_eval_flags(&pclass, &opts[0], ost->disposition, &ost->st->disposition);
if (ret < 0)
return ret;
}
/* initialize bitstream filters for the output stream
* needs to be done here, because the codec id for streamcopy is not
* known until now */
ret = init_output_bsfs(ost);
if (ret < 0)
return ret;
ost->initialized = 1;
ret = check_init_output_file(output_files[ost->file_index], ost->file_index);
if (ret < 0)
return ret;
return ret;
}
static void report_new_stream(int input_index, AVPacket *pkt)
{
InputFile *file = input_files[input_index];
AVStream *st = file->ctx->streams[pkt->stream_index];
if (pkt->stream_index < file->nb_streams_warn)
return;
av_log(file->ctx, AV_LOG_WARNING,
"New %s stream %d:%d at pos:%"PRId64" and DTS:%ss\n",
av_get_media_type_string(st->codecpar->codec_type),
input_index, pkt->stream_index,
pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
file->nb_streams_warn = pkt->stream_index + 1;
}
static int transcode_init(void)
{
int ret = 0, i, j, k;
AVFormatContext *oc;
OutputStream *ost;
InputStream *ist;
char error[1024] = {0};
for (i = 0; i < nb_filtergraphs; i++) {
FilterGraph *fg = filtergraphs[i];
for (j = 0; j < fg->nb_outputs; j++) {
OutputFilter *ofilter = fg->outputs[j];
if (!ofilter->ost || ofilter->ost->source_index >= 0)
continue;
if (fg->nb_inputs != 1)
continue;
for (k = nb_input_streams-1; k >= 0 ; k--)
if (fg->inputs[0]->ist == input_streams[k])
break;
ofilter->ost->source_index = k;
}
}
/* init framerate emulation */
for (i = 0; i < nb_input_files; i++) {
InputFile *ifile = input_files[i];
if (ifile->rate_emu)
for (j = 0; j < ifile->nb_streams; j++)
input_streams[j + ifile->ist_index]->start = av_gettime_relative();
}
/* init input streams */
for (i = 0; i < nb_input_streams; i++)
if ((ret = init_input_stream(i, error, sizeof(error))) < 0) {
for (i = 0; i < nb_output_streams; i++) {
ost = output_streams[i];
avcodec_close(ost->enc_ctx);
}
goto dump_format;
}
/* open each encoder */
for (i = 0; i < nb_output_streams; i++) {
// skip streams fed from filtergraphs until we have a frame for them
if (output_streams[i]->filter)
continue;
ret = init_output_stream(output_streams[i], error, sizeof(error));
if (ret < 0)
goto dump_format;
}
/* discard unused programs */
for (i = 0; i < nb_input_files; i++) {
InputFile *ifile = input_files[i];
for (j = 0; j < ifile->ctx->nb_programs; j++) {
AVProgram *p = ifile->ctx->programs[j];
int discard = AVDISCARD_ALL;
for (k = 0; k < p->nb_stream_indexes; k++)
if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
discard = AVDISCARD_DEFAULT;
break;
}
p->discard = discard;
}
}
/* write headers for files with no streams */
for (i = 0; i < nb_output_files; i++) {
oc = output_files[i]->ctx;
if (oc->oformat->flags & AVFMT_NOSTREAMS && oc->nb_streams == 0) {
ret = check_init_output_file(output_files[i], i);
if (ret < 0)
goto dump_format;
}
}
dump_format:
/* dump the stream mapping */
av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
for (i = 0; i < nb_input_streams; i++) {
ist = input_streams[i];
for (j = 0; j < ist->nb_filters; j++) {
if (!filtergraph_is_simple(ist->filters[j]->graph)) {
av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
ist->filters[j]->name);
if (nb_filtergraphs > 1)
av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
av_log(NULL, AV_LOG_INFO, "\n");
}
}
}
for (i = 0; i < nb_output_streams; i++) {
ost = output_streams[i];
if (ost->attachment_filename) {
/* an attached file */
av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
ost->attachment_filename, ost->file_index, ost->index);
continue;
}
if (ost->filter && !filtergraph_is_simple(ost->filter->graph)) {
/* output from a complex graph */
av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
if (nb_filtergraphs > 1)
av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
ost->index, ost->enc ? ost->enc->name : "?");
continue;
}
av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
input_streams[ost->source_index]->file_index,
input_streams[ost->source_index]->st->index,
ost->file_index,
ost->index);
if (ost->sync_ist != input_streams[ost->source_index])
av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
ost->sync_ist->file_index,
ost->sync_ist->st->index);
if (ost->stream_copy)
av_log(NULL, AV_LOG_INFO, " (copy)");
else {
const AVCodec *in_codec = input_streams[ost->source_index]->dec;
const AVCodec *out_codec = ost->enc;
const char *decoder_name = "?";
const char *in_codec_name = "?";
const char *encoder_name = "?";
const char *out_codec_name = "?";
const AVCodecDescriptor *desc;
if (in_codec) {
decoder_name = in_codec->name;
desc = avcodec_descriptor_get(in_codec->id);
if (desc)
in_codec_name = desc->name;
if (!strcmp(decoder_name, in_codec_name))
decoder_name = "native";
}
if (out_codec) {
encoder_name = out_codec->name;
desc = avcodec_descriptor_get(out_codec->id);
if (desc)
out_codec_name = desc->name;
if (!strcmp(encoder_name, out_codec_name))
encoder_name = "native";
}
av_log(NULL, AV_LOG_INFO, " (%s (%s) -> %s (%s))",
in_codec_name, decoder_name,
out_codec_name, encoder_name);
}
av_log(NULL, AV_LOG_INFO, "\n");
}
if (ret) {
av_log(NULL, AV_LOG_ERROR, "%s\n", error);
return ret;
}
atomic_store(&transcode_init_done, 1);
return 0;
}
/* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
static int need_output(void)
{
int i;
for (i = 0; i < nb_output_streams; i++) {
OutputStream *ost = output_streams[i];
OutputFile *of = output_files[ost->file_index];
AVFormatContext *os = output_files[ost->file_index]->ctx;
if (ost->finished ||
(os->pb && avio_tell(os->pb) >= of->limit_filesize))
continue;
if (ost->frame_number >= ost->max_frames) {
int j;
for (j = 0; j < of->ctx->nb_streams; j++)
close_output_stream(output_streams[of->ost_index + j]);
continue;
}
return 1;
}
return 0;
}
/**
* Select the output stream to process.
*
* @return selected output stream, or NULL if none available
*/
static OutputStream *choose_output(void)
{
int i;
int64_t opts_min = INT64_MAX;
OutputStream *ost_min = NULL;
for (i = 0; i < nb_output_streams; i++) {
OutputStream *ost = output_streams[i];
int64_t opts = ost->st->cur_dts == AV_NOPTS_VALUE ? INT64_MIN :
av_rescale_q(ost->st->cur_dts, ost->st->time_base,
AV_TIME_BASE_Q);
if (ost->st->cur_dts == AV_NOPTS_VALUE)
av_log(NULL, AV_LOG_DEBUG,
"cur_dts is invalid st:%d (%d) [init:%d i_done:%d finish:%d] (this is harmless if it occurs once at the start per stream)\n",
ost->st->index, ost->st->id, ost->initialized, ost->inputs_done, ost->finished);
if (!ost->initialized && !ost->inputs_done)
return ost;
if (!ost->finished && opts < opts_min) {
opts_min = opts;
ost_min = ost->unavailable ? NULL : ost;
}
}
return ost_min;
}
static void set_tty_echo(int on)
{
#if HAVE_TERMIOS_H
struct termios tty;
if (tcgetattr(0, &tty) == 0) {
if (on) tty.c_lflag |= ECHO;
else tty.c_lflag &= ~ECHO;
tcsetattr(0, TCSANOW, &tty);
}
#endif
}
static int check_keyboard_interaction(int64_t cur_time)
{
int i, ret, key;
static int64_t last_time;
if (received_nb_signals)
return AVERROR_EXIT;
/* read_key() returns 0 on EOF */
if(cur_time - last_time >= 100000 && !run_as_daemon){
key = read_key();
last_time = cur_time;
}else
key = -1;
if (key == 'q')
return AVERROR_EXIT;
if (key == '+') av_log_set_level(av_log_get_level()+10);
if (key == '-') av_log_set_level(av_log_get_level()-10);
if (key == 's') qp_hist ^= 1;
if (key == 'h'){
if (do_hex_dump){
do_hex_dump = do_pkt_dump = 0;
} else if(do_pkt_dump){
do_hex_dump = 1;
} else
do_pkt_dump = 1;
av_log_set_level(AV_LOG_DEBUG);
}
if (key == 'c' || key == 'C'){
char buf[4096], target[64], command[256], arg[256] = {0};
double time;
int k, n = 0;
fprintf(stderr, "\nEnter command: <target>|all <time>|-1 <command>[ <argument>]\n");
i = 0;
set_tty_echo(1);
while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
if (k > 0)
buf[i++] = k;
buf[i] = 0;
set_tty_echo(0);
fprintf(stderr, "\n");
if (k > 0 &&
(n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
target, time, command, arg);
for (i = 0; i < nb_filtergraphs; i++) {
FilterGraph *fg = filtergraphs[i];
if (fg->graph) {
if (time < 0) {
ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
fprintf(stderr, "Command reply for stream %d: ret:%d res:\n%s", i, ret, buf);
} else if (key == 'c') {
fprintf(stderr, "Queuing commands only on filters supporting the specific command is unsupported\n");
ret = AVERROR_PATCHWELCOME;
} else {
ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
if (ret < 0)
fprintf(stderr, "Queuing command failed with error %s\n", av_err2str(ret));
}
}
}
} else {
av_log(NULL, AV_LOG_ERROR,
"Parse error, at least 3 arguments were expected, "
"only %d given in string '%s'\n", n, buf);
}
}
if (key == 'd' || key == 'D'){
int debug=0;
if(key == 'D') {
debug = input_streams[0]->st->codec->debug<<1;
if(!debug) debug = 1;
while(debug & (FF_DEBUG_DCT_COEFF
#if FF_API_DEBUG_MV
|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE
#endif
)) //unsupported, would just crash
debug += debug;
}else{
char buf[32];
int k = 0;
i = 0;
set_tty_echo(1);
while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
if (k > 0)
buf[i++] = k;
buf[i] = 0;
set_tty_echo(0);
fprintf(stderr, "\n");
if (k <= 0 || sscanf(buf, "%d", &debug)!=1)
fprintf(stderr,"error parsing debug value\n");
}
for(i=0;i<nb_input_streams;i++) {
input_streams[i]->st->codec->debug = debug;
}
for(i=0;i<nb_output_streams;i++) {
OutputStream *ost = output_streams[i];
ost->enc_ctx->debug = debug;
}
if(debug) av_log_set_level(AV_LOG_DEBUG);
fprintf(stderr,"debug=%d\n", debug);
}
if (key == '?'){
fprintf(stderr, "key function\n"
"? show this help\n"
"+ increase verbosity\n"
"- decrease verbosity\n"
"c Send command to first matching filter supporting it\n"
"C Send/Queue command to all matching filters\n"
"D cycle through available debug modes\n"
"h dump packets/hex press to cycle through the 3 states\n"
"q quit\n"
"s Show QP histogram\n"
);
}
return 0;
}
#if HAVE_THREADS
static void *input_thread(void *arg)
{
InputFile *f = arg;
unsigned flags = f->non_blocking ? AV_THREAD_MESSAGE_NONBLOCK : 0;
int ret = 0;
while (1) {
AVPacket pkt;
ret = av_read_frame(f->ctx, &pkt);
if (ret == AVERROR(EAGAIN)) {
av_usleep(10000);
continue;
}
if (ret < 0) {
av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
break;
}
ret = av_thread_message_queue_send(f->in_thread_queue, &pkt, flags);
if (flags && ret == AVERROR(EAGAIN)) {
flags = 0;
ret = av_thread_message_queue_send(f->in_thread_queue, &pkt, flags);
av_log(f->ctx, AV_LOG_WARNING,
"Thread message queue blocking; consider raising the "
"thread_queue_size option (current value: %d)\n",
f->thread_queue_size);
}
if (ret < 0) {
if (ret != AVERROR_EOF)
av_log(f->ctx, AV_LOG_ERROR,
"Unable to send packet to main thread: %s\n",
av_err2str(ret));
av_packet_unref(&pkt);
av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
break;
}
}
return NULL;
}
static void free_input_thread(int i)
{
InputFile *f = input_files[i];
AVPacket pkt;
if (!f || !f->in_thread_queue)
return;
av_thread_message_queue_set_err_send(f->in_thread_queue, AVERROR_EOF);
while (av_thread_message_queue_recv(f->in_thread_queue, &pkt, 0) >= 0)
av_packet_unref(&pkt);
pthread_join(f->thread, NULL);
f->joined = 1;
av_thread_message_queue_free(&f->in_thread_queue);
}
static void free_input_threads(void)
{
int i;
for (i = 0; i < nb_input_files; i++)
free_input_thread(i);
}
static int init_input_thread(int i)
{
int ret;
InputFile *f = input_files[i];
if (nb_input_files == 1)
return 0;
if (f->ctx->pb ? !f->ctx->pb->seekable :
strcmp(f->ctx->iformat->name, "lavfi"))
f->non_blocking = 1;
ret = av_thread_message_queue_alloc(&f->in_thread_queue,
f->thread_queue_size, sizeof(AVPacket));
if (ret < 0)
return ret;
if ((ret = pthread_create(&f->thread, NULL, input_thread, f))) {
av_log(NULL, AV_LOG_ERROR, "pthread_create failed: %s. Try to increase `ulimit -v` or decrease `ulimit -s`.\n", strerror(ret));
av_thread_message_queue_free(&f->in_thread_queue);
return AVERROR(ret);
}
return 0;
}
static int init_input_threads(void)
{
int i, ret;
for (i = 0; i < nb_input_files; i++) {
ret = init_input_thread(i);
if (ret < 0)
return ret;
}
return 0;
}
static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
{
return av_thread_message_queue_recv(f->in_thread_queue, pkt,
f->non_blocking ?
AV_THREAD_MESSAGE_NONBLOCK : 0);
}
#endif
static int get_input_packet(InputFile *f, AVPacket *pkt)
{
if (f->rate_emu) {
int i;
for (i = 0; i < f->nb_streams; i++) {
InputStream *ist = input_streams[f->ist_index + i];
int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
int64_t now = av_gettime_relative() - ist->start;
if (pts > now)
return AVERROR(EAGAIN);
}
}
#if HAVE_THREADS
if (nb_input_files > 1)
return get_input_packet_mt(f, pkt);
#endif
return av_read_frame(f->ctx, pkt);
}
static int got_eagain(void)
{
int i;
for (i = 0; i < nb_output_streams; i++)
if (output_streams[i]->unavailable)
return 1;
return 0;
}
static void reset_eagain(void)
{
int i;
for (i = 0; i < nb_input_files; i++)
input_files[i]->eagain = 0;
for (i = 0; i < nb_output_streams; i++)
output_streams[i]->unavailable = 0;
}
// set duration to max(tmp, duration) in a proper time base and return duration's time_base
static AVRational duration_max(int64_t tmp, int64_t *duration, AVRational tmp_time_base,
AVRational time_base)
{
int ret;
if (!*duration) {
*duration = tmp;
return tmp_time_base;
}
ret = av_compare_ts(*duration, time_base, tmp, tmp_time_base);
if (ret < 0) {
*duration = tmp;
return tmp_time_base;
}
return time_base;
}
static int seek_to_start(InputFile *ifile, AVFormatContext *is)
{
InputStream *ist;
AVCodecContext *avctx;
int i, ret, has_audio = 0;
int64_t duration = 0;
ret = av_seek_frame(is, -1, is->start_time, 0);
if (ret < 0)
return ret;
for (i = 0; i < ifile->nb_streams; i++) {
ist = input_streams[ifile->ist_index + i];
avctx = ist->dec_ctx;
/* duration is the length of the last frame in a stream
* when audio stream is present we don't care about
* last video frame length because it's not defined exactly */
if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && ist->nb_samples)
has_audio = 1;
}
for (i = 0; i < ifile->nb_streams; i++) {
ist = input_streams[ifile->ist_index + i];
avctx = ist->dec_ctx;
if (has_audio) {
if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && ist->nb_samples) {
AVRational sample_rate = {1, avctx->sample_rate};
duration = av_rescale_q(ist->nb_samples, sample_rate, ist->st->time_base);
} else {
continue;
}
} else {
if (ist->framerate.num) {
duration = av_rescale_q(1, av_inv_q(ist->framerate), ist->st->time_base);
} else if (ist->st->avg_frame_rate.num) {
duration = av_rescale_q(1, av_inv_q(ist->st->avg_frame_rate), ist->st->time_base);
} else {
duration = 1;
}
}
if (!ifile->duration)
ifile->time_base = ist->st->time_base;
/* the total duration of the stream, max_pts - min_pts is
* the duration of the stream without the last frame */
duration += ist->max_pts - ist->min_pts;
ifile->time_base = duration_max(duration, &ifile->duration, ist->st->time_base,
ifile->time_base);
}
if (ifile->loop > 0)
ifile->loop--;
return ret;
}
/*
* Return
* - 0 -- one packet was read and processed
* - AVERROR(EAGAIN) -- no packets were available for selected file,
* this function should be called again
* - AVERROR_EOF -- this function should not be called again
*/
static int process_input(int file_index)
{
InputFile *ifile = input_files[file_index];
AVFormatContext *is;
InputStream *ist;
AVPacket pkt;
int ret, thread_ret, i, j;
int64_t duration;
int64_t pkt_dts;
is = ifile->ctx;
ret = get_input_packet(ifile, &pkt);
if (ret == AVERROR(EAGAIN)) {
ifile->eagain = 1;
return ret;
}
if (ret < 0 && ifile->loop) {
AVCodecContext *avctx;
for (i = 0; i < ifile->nb_streams; i++) {
ist = input_streams[ifile->ist_index + i];
avctx = ist->dec_ctx;
if (ist->decoding_needed) {
ret = process_input_packet(ist, NULL, 1);
if (ret>0)
return 0;
avcodec_flush_buffers(avctx);
}
}
#if HAVE_THREADS
free_input_thread(file_index);
#endif
ret = seek_to_start(ifile, is);
#if HAVE_THREADS
thread_ret = init_input_thread(file_index);
if (thread_ret < 0)
return thread_ret;
#endif
if (ret < 0)
av_log(NULL, AV_LOG_WARNING, "Seek to start failed.\n");
else
ret = get_input_packet(ifile, &pkt);
if (ret == AVERROR(EAGAIN)) {
ifile->eagain = 1;
return ret;
}
}
if (ret < 0) {
if (ret != AVERROR_EOF) {
print_error(is->url, ret);
if (exit_on_error)
exit_program(1);
}
for (i = 0; i < ifile->nb_streams; i++) {
ist = input_streams[ifile->ist_index + i];
if (ist->decoding_needed) {
ret = process_input_packet(ist, NULL, 0);
if (ret>0)
return 0;
}
/* mark all outputs that don't go through lavfi as finished */
for (j = 0; j < nb_output_streams; j++) {
OutputStream *ost = output_streams[j];
if (ost->source_index == ifile->ist_index + i &&
(ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
finish_output_stream(ost);
}
}
ifile->eof_reached = 1;
return AVERROR(EAGAIN);
}
reset_eagain();
if (do_pkt_dump) {
av_pkt_dump_log2(NULL, AV_LOG_INFO, &pkt, do_hex_dump,
is->streams[pkt.stream_index]);
}
/* the following test is needed in case new streams appear
dynamically in stream : we ignore them */
if (pkt.stream_index >= ifile->nb_streams) {
report_new_stream(file_index, &pkt);
goto discard_packet;
}
ist = input_streams[ifile->ist_index + pkt.stream_index];
ist->data_size += pkt.size;
ist->nb_packets++;
if (ist->discard)
goto discard_packet;
if (pkt.flags & AV_PKT_FLAG_CORRUPT) {
av_log(NULL, exit_on_error ? AV_LOG_FATAL : AV_LOG_WARNING,
"%s: corrupt input packet in stream %d\n", is->url, pkt.stream_index);
if (exit_on_error)
exit_program(1);
}
if (debug_ts) {
av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
"next_dts:%s next_dts_time:%s next_pts:%s next_pts_time:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%s off_time:%s\n",
ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->dec_ctx->codec_type),
av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &AV_TIME_BASE_Q),
av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &AV_TIME_BASE_Q),
av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
av_ts2str(input_files[ist->file_index]->ts_offset),
av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
}
if(!ist->wrap_correction_done && is->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
int64_t stime, stime2;
// Correcting starttime based on the enabled streams
// FIXME this ideally should be done before the first use of starttime but we do not know which are the enabled streams at that point.
// so we instead do it here as part of discontinuity handling
if ( ist->next_dts == AV_NOPTS_VALUE
&& ifile->ts_offset == -is->start_time
&& (is->iformat->flags & AVFMT_TS_DISCONT)) {
int64_t new_start_time = INT64_MAX;
for (i=0; i<is->nb_streams; i++) {
AVStream *st = is->streams[i];
if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)
continue;
new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));
}
if (new_start_time > is->start_time) {
av_log(is, AV_LOG_VERBOSE, "Correcting start time by %"PRId64"\n", new_start_time - is->start_time);
ifile->ts_offset = -new_start_time;
}
}
stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q, ist->st->time_base);
stime2= stime + (1ULL<<ist->st->pts_wrap_bits);
ist->wrap_correction_done = 1;
if(stime2 > stime && pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
pkt.dts -= 1ULL<<ist->st->pts_wrap_bits;
ist->wrap_correction_done = 0;
}
if(stime2 > stime && pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
pkt.pts -= 1ULL<<ist->st->pts_wrap_bits;
ist->wrap_correction_done = 0;
}
}
/* add the stream-global side data to the first packet */
if (ist->nb_packets == 1) {
for (i = 0; i < ist->st->nb_side_data; i++) {
AVPacketSideData *src_sd = &ist->st->side_data[i];
uint8_t *dst_data;
if (src_sd->type == AV_PKT_DATA_DISPLAYMATRIX)
continue;
if (av_packet_get_side_data(&pkt, src_sd->type, NULL))
continue;
dst_data = av_packet_new_side_data(&pkt, src_sd->type, src_sd->size);
if (!dst_data)
exit_program(1);
memcpy(dst_data, src_sd->data, src_sd->size);
}
}
if (pkt.dts != AV_NOPTS_VALUE)
pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
if (pkt.pts != AV_NOPTS_VALUE)
pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
if (pkt.pts != AV_NOPTS_VALUE)
pkt.pts *= ist->ts_scale;
if (pkt.dts != AV_NOPTS_VALUE)
pkt.dts *= ist->ts_scale;
pkt_dts = av_rescale_q_rnd(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
pkt_dts != AV_NOPTS_VALUE && ist->next_dts == AV_NOPTS_VALUE && !copy_ts
&& (is->iformat->flags & AVFMT_TS_DISCONT) && ifile->last_ts != AV_NOPTS_VALUE) {
int64_t delta = pkt_dts - ifile->last_ts;
if (delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
delta > 1LL*dts_delta_threshold*AV_TIME_BASE){
ifile->ts_offset -= delta;
av_log(NULL, AV_LOG_DEBUG,
"Inter stream timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
delta, ifile->ts_offset);
pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
if (pkt.pts != AV_NOPTS_VALUE)
pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
}
}
duration = av_rescale_q(ifile->duration, ifile->time_base, ist->st->time_base);
if (pkt.pts != AV_NOPTS_VALUE) {
pkt.pts += duration;
ist->max_pts = FFMAX(pkt.pts, ist->max_pts);
ist->min_pts = FFMIN(pkt.pts, ist->min_pts);
}
if (pkt.dts != AV_NOPTS_VALUE)
pkt.dts += duration;
pkt_dts = av_rescale_q_rnd(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
pkt_dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
!copy_ts) {
int64_t delta = pkt_dts - ist->next_dts;
if (is->iformat->flags & AVFMT_TS_DISCONT) {
if (delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
delta > 1LL*dts_delta_threshold*AV_TIME_BASE ||
pkt_dts + AV_TIME_BASE/10 < FFMAX(ist->pts, ist->dts)) {
ifile->ts_offset -= delta;
av_log(NULL, AV_LOG_DEBUG,
"timestamp discontinuity for stream #%d:%d "
"(id=%d, type=%s): %"PRId64", new offset= %"PRId64"\n",
ist->file_index, ist->st->index, ist->st->id,
av_get_media_type_string(ist->dec_ctx->codec_type),
delta, ifile->ts_offset);
pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
if (pkt.pts != AV_NOPTS_VALUE)
pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
}
} else {
if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
delta > 1LL*dts_error_threshold*AV_TIME_BASE) {
av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
pkt.dts = AV_NOPTS_VALUE;
}
if (pkt.pts != AV_NOPTS_VALUE){
int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
delta = pkt_pts - ist->next_dts;
if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
delta > 1LL*dts_error_threshold*AV_TIME_BASE) {
av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
pkt.pts = AV_NOPTS_VALUE;
}
}
}
}
if (pkt.dts != AV_NOPTS_VALUE)
ifile->last_ts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
if (debug_ts) {
av_log(NULL, AV_LOG_INFO, "demuxer+ffmpeg -> ist_index:%d type:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%s off_time:%s\n",
ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->dec_ctx->codec_type),
av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
av_ts2str(input_files[ist->file_index]->ts_offset),
av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
}
sub2video_heartbeat(ist, pkt.pts);
process_input_packet(ist, &pkt, 0);
discard_packet:
av_packet_unref(&pkt);
return 0;
}
/**
* Perform a step of transcoding for the specified filter graph.
*
* @param[in] graph filter graph to consider
* @param[out] best_ist input stream where a frame would allow to continue
* @return 0 for success, <0 for error
*/
static int transcode_from_filter(FilterGraph *graph, InputStream **best_ist)
{
int i, ret;
int nb_requests, nb_requests_max = 0;
InputFilter *ifilter;
InputStream *ist;
*best_ist = NULL;
ret = avfilter_graph_request_oldest(graph->graph);
if (ret >= 0)
return reap_filters(0);
if (ret == AVERROR_EOF) {
ret = reap_filters(1);
for (i = 0; i < graph->nb_outputs; i++)
close_output_stream(graph->outputs[i]->ost);
return ret;
}
if (ret != AVERROR(EAGAIN))
return ret;
for (i = 0; i < graph->nb_inputs; i++) {
ifilter = graph->inputs[i];
ist = ifilter->ist;
if (input_files[ist->file_index]->eagain ||
input_files[ist->file_index]->eof_reached)
continue;
nb_requests = av_buffersrc_get_nb_failed_requests(ifilter->filter);
if (nb_requests > nb_requests_max) {
nb_requests_max = nb_requests;
*best_ist = ist;
}
}
if (!*best_ist)
for (i = 0; i < graph->nb_outputs; i++)
graph->outputs[i]->ost->unavailable = 1;
return 0;
}
/**
* Run a single step of transcoding.
*
* @return 0 for success, <0 for error
*/
static int transcode_step(void)
{
OutputStream *ost;
InputStream *ist = NULL;
int ret;
ost = choose_output();
if (!ost) {
if (got_eagain()) {
reset_eagain();
av_usleep(10000);
return 0;
}
av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
return AVERROR_EOF;
}
if (ost->filter && !ost->filter->graph->graph) {
if (ifilter_has_all_input_formats(ost->filter->graph)) {
ret = configure_filtergraph(ost->filter->graph);
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Error reinitializing filters!\n");
return ret;
}
}
}
if (ost->filter && ost->filter->graph->graph) {
if (!ost->initialized) {
char error[1024] = {0};
ret = init_output_stream(ost, error, sizeof(error));
if (ret < 0) {
av_log(NULL, AV_LOG_ERROR, "Error initializing output stream %d:%d -- %s\n",
ost->file_index, ost->index, error);
exit_program(1);
}
}
if ((ret = transcode_from_filter(ost->filter->graph, &ist)) < 0)
return ret;
if (!ist)
return 0;
} else if (ost->filter) {
int i;
for (i = 0; i < ost->filter->graph->nb_inputs; i++) {
InputFilter *ifilter = ost->filter->graph->inputs[i];
if (!ifilter->ist->got_output && !input_files[ifilter->ist->file_index]->eof_reached) {
ist = ifilter->ist;
break;
}
}
if (!ist) {
ost->inputs_done = 1;
return 0;
}
} else {
av_assert0(ost->source_index >= 0);
ist = input_streams[ost->source_index];
}
ret = process_input(ist->file_index);
if (ret == AVERROR(EAGAIN)) {
if (input_files[ist->file_index]->eagain)
ost->unavailable = 1;
return 0;
}
if (ret < 0)
return ret == AVERROR_EOF ? 0 : ret;
return reap_filters(0);
}
/*
* The following code is the main loop of the file converter
*/
static int transcode(void)
{
int ret, i;
AVFormatContext *os;
OutputStream *ost;
InputStream *ist;
int64_t timer_start;
int64_t total_packets_written = 0;
ret = transcode_init();
if (ret < 0)
goto fail;
if (stdin_interaction) {
av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
}
timer_start = av_gettime_relative();
#if HAVE_THREADS
if ((ret = init_input_threads()) < 0)
goto fail;
#endif
while (!received_sigterm) {
int64_t cur_time= av_gettime_relative();
/* if 'q' pressed, exits */
if (stdin_interaction)
if (check_keyboard_interaction(cur_time) < 0)
break;
/* check if there's any stream where output is still needed */
if (!need_output()) {
av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
break;
}
ret = transcode_step();
if (ret < 0 && ret != AVERROR_EOF) {
av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", av_err2str(ret));
break;
}
/* dump report by using the output first video and audio streams */
print_report(0, timer_start, cur_time);
}
#if HAVE_THREADS
free_input_threads();
#endif
/* at the end of stream, we must flush the decoder buffers */
for (i = 0; i < nb_input_streams; i++) {
ist = input_streams[i];
if (!input_files[ist->file_index]->eof_reached) {
process_input_packet(ist, NULL, 0);
}
}
flush_encoders();
term_exit();
/* write the trailer if needed and close file */
for (i = 0; i < nb_output_files; i++) {
os = output_files[i]->ctx;
if (!output_files[i]->header_written) {
av_log(NULL, AV_LOG_ERROR,
"Nothing was written into output file %d (%s), because "
"at least one of its streams received no packets.\n",
i, os->url);
continue;
}
if ((ret = av_write_trailer(os)) < 0) {
av_log(NULL, AV_LOG_ERROR, "Error writing trailer of %s: %s\n", os->url, av_err2str(ret));
if (exit_on_error)
exit_program(1);
}
}
/* dump report by using the first video and audio streams */
print_report(1, timer_start, av_gettime_relative());
/* close each encoder */
for (i = 0; i < nb_output_streams; i++) {
ost = output_streams[i];
if (ost->encoding_needed) {
av_freep(&ost->enc_ctx->stats_in);
}
total_packets_written += ost->packets_written;
}
if (!total_packets_written && (abort_on_flags & ABORT_ON_FLAG_EMPTY_OUTPUT)) {
av_log(NULL, AV_LOG_FATAL, "Empty output\n");
exit_program(1);
}
/* close each decoder */
for (i = 0; i < nb_input_streams; i++) {
ist = input_streams[i];
if (ist->decoding_needed) {
avcodec_close(ist->dec_ctx);
if (ist->hwaccel_uninit)
ist->hwaccel_uninit(ist->dec_ctx);
}
}
av_buffer_unref(&hw_device_ctx);
hw_device_free_all();
/* finished ! */
ret = 0;
fail:
#if HAVE_THREADS
free_input_threads();
#endif
if (output_streams) {
for (i = 0; i < nb_output_streams; i++) {
ost = output_streams[i];
if (ost) {
if (ost->logfile) {
if (fclose(ost->logfile))
av_log(NULL, AV_LOG_ERROR,
"Error closing logfile, loss of information possible: %s\n",
av_err2str(AVERROR(errno)));
ost->logfile = NULL;
}
av_freep(&ost->forced_kf_pts);
av_freep(&ost->apad);
av_freep(&ost->disposition);
av_dict_free(&ost->encoder_opts);
av_dict_free(&ost->sws_dict);
av_dict_free(&ost->swr_opts);
av_dict_free(&ost->resample_opts);
}
}
}
return ret;
}
static BenchmarkTimeStamps get_benchmark_time_stamps(void)
{
BenchmarkTimeStamps time_stamps = { av_gettime_relative() };
#if HAVE_GETRUSAGE
struct rusage rusage;
getrusage(RUSAGE_SELF, &rusage);
time_stamps.user_usec =
(rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
time_stamps.sys_usec =
(rusage.ru_stime.tv_sec * 1000000LL) + rusage.ru_stime.tv_usec;
#elif HAVE_GETPROCESSTIMES
HANDLE proc;
FILETIME c, e, k, u;
proc = GetCurrentProcess();
GetProcessTimes(proc, &c, &e, &k, &u);
time_stamps.user_usec =
((int64_t)u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
time_stamps.sys_usec =
((int64_t)k.dwHighDateTime << 32 | k.dwLowDateTime) / 10;
#else
time_stamps.user_usec = time_stamps.sys_usec = 0;
#endif
return time_stamps;
}
static int64_t getmaxrss(void)
{
#if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
struct rusage rusage;
getrusage(RUSAGE_SELF, &rusage);
return (int64_t)rusage.ru_maxrss * 1024;
#elif HAVE_GETPROCESSMEMORYINFO
HANDLE proc;
PROCESS_MEMORY_COUNTERS memcounters;
proc = GetCurrentProcess();
memcounters.cb = sizeof(memcounters);
GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
return memcounters.PeakPagefileUsage;
#else
return 0;
#endif
}
static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
{
}
int run(int argc, char **argv)
{
int i, ret;
BenchmarkTimeStamps ti;
main_return_code = 0;
init_dynload();
register_exit(ffmpeg_cleanup);
setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
av_log_set_flags(AV_LOG_SKIP_REPEATED);
parse_loglevel(argc, argv, options);
if (setjmp(jump_buf)) {
main_return_code = 1;
goto end;
}
if(argc>1 && !strcmp(argv[1], "-d")){
run_as_daemon=1;
av_log_set_callback(log_callback_null);
argc--;
argv++;
}
#if CONFIG_AVDEVICE
avdevice_register_all();
#endif
avformat_network_init();
show_banner(argc, argv, options);
/* parse options and open all input/output files */
ret = ffmpeg_parse_options(argc, argv);
if (ret < 0)
exit_program(1);
if (nb_output_files <= 0 && nb_input_files == 0) {
show_usage();
av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
exit_program(1);
}
/* file converter / grab */
if (nb_output_files <= 0) {
av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
exit_program(1);
}
for (i = 0; i < nb_output_files; i++) {
if (strcmp(output_files[i]->ctx->oformat->name, "rtp"))
want_sdp = 0;
}
current_time = ti = get_benchmark_time_stamps();
if (transcode() < 0)
exit_program(1);
if (do_benchmark) {
int64_t utime, stime, rtime;
current_time = get_benchmark_time_stamps();
utime = current_time.user_usec - ti.user_usec;
stime = current_time.sys_usec - ti.sys_usec;
rtime = current_time.real_usec - ti.real_usec;
av_log(NULL, AV_LOG_INFO,
"bench: utime=%0.3fs stime=%0.3fs rtime=%0.3fs\n",
utime / 1000000.0, stime / 1000000.0, rtime / 1000000.0);
}
av_log(NULL, AV_LOG_DEBUG, "%"PRIu64" frames successfully decoded, %"PRIu64" decoding errors\n",
decode_error_stat[0], decode_error_stat[1]);
if ((decode_error_stat[0] + decode_error_stat[1]) * max_error_rate < decode_error_stat[1])
exit_program(69);
// exit_program(received_nb_signals ? 255 : main_return_code);
end:
av_log(NULL, AV_LOG_INFO, "FFmpeg result=%d\n", main_return_code);
ffmpeg_cleanup(0);
return main_return_code;
}
|
813611.c | /* hyperloglog.c - Redis HyperLogLog probabilistic cardinality approximation.
* This file implements the algorithm and the exported Redis commands.
*
* Copyright (c) 2014, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "server.h"
#include <stdint.h>
#include <math.h>
/* The Redis HyperLogLog implementation is based on the following ideas:
*
* * The use of a 64 bit hash function as proposed in [1], in order to don't
* limited to cardinalities up to 10^9, at the cost of just 1 additional
* bit per register.
* * The use of 16384 6-bit registers for a great level of accuracy, using
* a total of 12k per key.
* * The use of the Redis string data type. No new type is introduced.
* * No attempt is made to compress the data structure as in [1]. Also the
* algorithm used is the original HyperLogLog Algorithm as in [2], with
* the only difference that a 64 bit hash function is used, so no correction
* is performed for values near 2^32 as in [1].
*
* [1] Heule, Nunkesser, Hall: HyperLogLog in Practice: Algorithmic
* Engineering of a State of The Art Cardinality Estimation Algorithm.
*
* [2] P. Flajolet, Éric Fusy, O. Gandouet, and F. Meunier. Hyperloglog: The
* analysis of a near-optimal cardinality estimation algorithm.
*
* Redis uses two representations:
*
* 1) A "dense" representation where every entry is represented by
* a 6-bit integer.
* 2) A "sparse" representation using run length compression suitable
* for representing HyperLogLogs with many registers set to 0 in
* a memory efficient way.
*
*
* HLL header
* ===
*
* Both the dense and sparse representation have a 16 byte header as follows:
*
* +------+---+-----+----------+
* | HYLL | E | N/U | Cardin. |
* +------+---+-----+----------+
*
* The first 4 bytes are a magic string set to the bytes "HYLL".
* "E" is one byte encoding, currently set to HLL_DENSE or
* HLL_SPARSE. N/U are three not used bytes.
*
* The "Cardin." field is a 64 bit integer stored in little endian format
* with the latest cardinality computed that can be reused if the data
* structure was not modified since the last computation (this is useful
* because there are high probabilities that HLLADD operations don't
* modify the actual data structure and hence the approximated cardinality).
*
* When the most significant bit in the most significant byte of the cached
* cardinality is set, it means that the data structure was modified and
* we can't reuse the cached value that must be recomputed.
*
* Dense representation
* ===
*
* The dense representation used by Redis is the following:
*
* +--------+--------+--------+------// //--+
* |11000000|22221111|33333322|55444444 .... |
* +--------+--------+--------+------// //--+
*
* The 6 bits counters are encoded one after the other starting from the
* LSB to the MSB, and using the next bytes as needed.
*
* Sparse representation
* ===
*
* The sparse representation encodes registers using a run length
* encoding composed of three opcodes, two using one byte, and one using
* of two bytes. The opcodes are called ZERO, XZERO and VAL.
*
* ZERO opcode is represented as 00xxxxxx. The 6-bit integer represented
* by the six bits 'xxxxxx', plus 1, means that there are N registers set
* to 0. This opcode can represent from 1 to 64 contiguous registers set
* to the value of 0.
*
* XZERO opcode is represented by two bytes 01xxxxxx yyyyyyyy. The 14-bit
* integer represented by the bits 'xxxxxx' as most significant bits and
* 'yyyyyyyy' as least significant bits, plus 1, means that there are N
* registers set to 0. This opcode can represent from 0 to 16384 contiguous
* registers set to the value of 0.
*
* VAL opcode is represented as 1vvvvvxx. It contains a 5-bit integer
* representing the value of a register, and a 2-bit integer representing
* the number of contiguous registers set to that value 'vvvvv'.
* To obtain the value and run length, the integers vvvvv and xx must be
* incremented by one. This opcode can represent values from 1 to 32,
* repeated from 1 to 4 times.
*
* The sparse representation can't represent registers with a value greater
* than 32, however it is very unlikely that we find such a register in an
* HLL with a cardinality where the sparse representation is still more
* memory efficient than the dense representation. When this happens the
* HLL is converted to the dense representation.
*
* The sparse representation is purely positional. For example a sparse
* representation of an empty HLL is just: XZERO:16384.
*
* An HLL having only 3 non-zero registers at position 1000, 1020, 1021
* respectively set to 2, 3, 3, is represented by the following three
* opcodes:
*
* XZERO:1000 (Registers 0-999 are set to 0)
* VAL:2,1 (1 register set to value 2, that is register 1000)
* ZERO:19 (Registers 1001-1019 set to 0)
* VAL:3,2 (2 registers set to value 3, that is registers 1020,1021)
* XZERO:15362 (Registers 1022-16383 set to 0)
*
* In the example the sparse representation used just 7 bytes instead
* of 12k in order to represent the HLL registers. In general for low
* cardinality there is a big win in terms of space efficiency, traded
* with CPU time since the sparse representation is slower to access:
*
* The following table shows average cardinality vs bytes used, 100
* samples per cardinality (when the set was not representable because
* of registers with too big value, the dense representation size was used
* as a sample).
*
* 100 267
* 200 485
* 300 678
* 400 859
* 500 1033
* 600 1205
* 700 1375
* 800 1544
* 900 1713
* 1000 1882
* 2000 3480
* 3000 4879
* 4000 6089
* 5000 7138
* 6000 8042
* 7000 8823
* 8000 9500
* 9000 10088
* 10000 10591
*
* The dense representation uses 12288 bytes, so there is a big win up to
* a cardinality of ~2000-3000. For bigger cardinalities the constant times
* involved in updating the sparse representation is not justified by the
* memory savings. The exact maximum length of the sparse representation
* when this implementation switches to the dense representation is
* configured via the define server.hll_sparse_max_bytes.
*/
struct hllhdr {
char magic[4]; /* "HYLL" */
uint8_t encoding; /* HLL_DENSE or HLL_SPARSE. */
uint8_t notused[3]; /* Reserved for future use, must be zero. */
uint8_t card[8]; /* Cached cardinality, little endian. */
uint8_t registers[]; /* Data bytes. */
};
/* The cached cardinality MSB is used to signal validity of the cached value. */
#define HLL_INVALIDATE_CACHE(hdr) (hdr)->card[7] |= (1<<7)
#define HLL_VALID_CACHE(hdr) (((hdr)->card[7] & (1<<7)) == 0)
#define HLL_P 14 /* The greater is P, the smaller the error. */
#define HLL_Q (64-HLL_P) /* The number of bits of the hash value used for
determining the number of leading zeros. */
#define HLL_REGISTERS (1<<HLL_P) /* With P=14, 16384 registers. */
#define HLL_P_MASK (HLL_REGISTERS-1) /* Mask to index register. */
#define HLL_BITS 6 /* Enough to count up to 63 leading zeroes. */
#define HLL_REGISTER_MAX ((1<<HLL_BITS)-1)
#define HLL_HDR_SIZE sizeof(struct hllhdr)
#define HLL_DENSE_SIZE (HLL_HDR_SIZE+((HLL_REGISTERS*HLL_BITS+7)/8))
#define HLL_DENSE 0 /* Dense encoding. */
#define HLL_SPARSE 1 /* Sparse encoding. */
#define HLL_RAW 255 /* Only used internally, never exposed. */
#define HLL_MAX_ENCODING 1
static char *invalid_hll_err = "-INVALIDOBJ Corrupted HLL object detected\r\n";
/* =========================== Low level bit macros ========================= */
/* Macros to access the dense representation.
*
* We need to get and set 6 bit counters in an array of 8 bit bytes.
* We use macros to make sure the code is inlined since speed is critical
* especially in order to compute the approximated cardinality in
* HLLCOUNT where we need to access all the registers at once.
* For the same reason we also want to avoid conditionals in this code path.
*
* +--------+--------+--------+------//
* |11000000|22221111|33333322|55444444
* +--------+--------+--------+------//
*
* Note: in the above representation the most significant bit (MSB)
* of every byte is on the left. We start using bits from the LSB to MSB,
* and so forth passing to the next byte.
*
* Example, we want to access to counter at pos = 1 ("111111" in the
* illustration above).
*
* The index of the first byte b0 containing our data is:
*
* b0 = 6 * pos / 8 = 0
*
* +--------+
* |11000000| <- Our byte at b0
* +--------+
*
* The position of the first bit (counting from the LSB = 0) in the byte
* is given by:
*
* fb = 6 * pos % 8 -> 6
*
* Right shift b0 of 'fb' bits.
*
* +--------+
* |11000000| <- Initial value of b0
* |00000011| <- After right shift of 6 pos.
* +--------+
*
* Left shift b1 of bits 8-fb bits (2 bits)
*
* +--------+
* |22221111| <- Initial value of b1
* |22111100| <- After left shift of 2 bits.
* +--------+
*
* OR the two bits, and finally AND with 111111 (63 in decimal) to
* clean the higher order bits we are not interested in:
*
* +--------+
* |00000011| <- b0 right shifted
* |22111100| <- b1 left shifted
* |22111111| <- b0 OR b1
* | 111111| <- (b0 OR b1) AND 63, our value.
* +--------+
*
* We can try with a different example, like pos = 0. In this case
* the 6-bit counter is actually contained in a single byte.
*
* b0 = 6 * pos / 8 = 0
*
* +--------+
* |11000000| <- Our byte at b0
* +--------+
*
* fb = 6 * pos % 8 = 0
*
* So we right shift of 0 bits (no shift in practice) and
* left shift the next byte of 8 bits, even if we don't use it,
* but this has the effect of clearing the bits so the result
* will not be affacted after the OR.
*
* -------------------------------------------------------------------------
*
* Setting the register is a bit more complex, let's assume that 'val'
* is the value we want to set, already in the right range.
*
* We need two steps, in one we need to clear the bits, and in the other
* we need to bitwise-OR the new bits.
*
* Let's try with 'pos' = 1, so our first byte at 'b' is 0,
*
* "fb" is 6 in this case.
*
* +--------+
* |11000000| <- Our byte at b0
* +--------+
*
* To create a AND-mask to clear the bits about this position, we just
* initialize the mask with the value 63, left shift it of "fs" bits,
* and finally invert the result.
*
* +--------+
* |00111111| <- "mask" starts at 63
* |11000000| <- "mask" after left shift of "ls" bits.
* |00111111| <- "mask" after invert.
* +--------+
*
* Now we can bitwise-AND the byte at "b" with the mask, and bitwise-OR
* it with "val" left-shifted of "ls" bits to set the new bits.
*
* Now let's focus on the next byte b1:
*
* +--------+
* |22221111| <- Initial value of b1
* +--------+
*
* To build the AND mask we start again with the 63 value, right shift
* it by 8-fb bits, and invert it.
*
* +--------+
* |00111111| <- "mask" set at 2&6-1
* |00001111| <- "mask" after the right shift by 8-fb = 2 bits
* |11110000| <- "mask" after bitwise not.
* +--------+
*
* Now we can mask it with b+1 to clear the old bits, and bitwise-OR
* with "val" left-shifted by "rs" bits to set the new value.
*/
/* Note: if we access the last counter, we will also access the b+1 byte
* that is out of the array, but sds strings always have an implicit null
* term, so the byte exists, and we can skip the conditional (or the need
* to allocate 1 byte more explicitly). */
/* Store the value of the register at position 'regnum' into variable 'target'.
* 'p' is an array of unsigned bytes. */
#define HLL_DENSE_GET_REGISTER(target,p,regnum) do { \
uint8_t *_p = (uint8_t*) p; \
unsigned long _byte = regnum*HLL_BITS/8; \
unsigned long _fb = regnum*HLL_BITS&7; \
unsigned long _fb8 = 8 - _fb; \
unsigned long b0 = _p[_byte]; \
unsigned long b1 = _p[_byte+1]; \
target = ((b0 >> _fb) | (b1 << _fb8)) & HLL_REGISTER_MAX; \
} while(0)
/* Set the value of the register at position 'regnum' to 'val'.
* 'p' is an array of unsigned bytes. */
#define HLL_DENSE_SET_REGISTER(p,regnum,val) do { \
uint8_t *_p = (uint8_t*) p; \
unsigned long _byte = regnum*HLL_BITS/8; \
unsigned long _fb = regnum*HLL_BITS&7; \
unsigned long _fb8 = 8 - _fb; \
unsigned long _v = val; \
_p[_byte] &= ~(HLL_REGISTER_MAX << _fb); \
_p[_byte] |= _v << _fb; \
_p[_byte+1] &= ~(HLL_REGISTER_MAX >> _fb8); \
_p[_byte+1] |= _v >> _fb8; \
} while(0)
/* Macros to access the sparse representation.
* The macros parameter is expected to be an uint8_t pointer. */
#define HLL_SPARSE_XZERO_BIT 0x40 /* 01xxxxxx */
#define HLL_SPARSE_VAL_BIT 0x80 /* 1vvvvvxx */
#define HLL_SPARSE_IS_ZERO(p) (((*(p)) & 0xc0) == 0) /* 00xxxxxx */
#define HLL_SPARSE_IS_XZERO(p) (((*(p)) & 0xc0) == HLL_SPARSE_XZERO_BIT)
#define HLL_SPARSE_IS_VAL(p) ((*(p)) & HLL_SPARSE_VAL_BIT)
#define HLL_SPARSE_ZERO_LEN(p) (((*(p)) & 0x3f)+1)
#define HLL_SPARSE_XZERO_LEN(p) (((((*(p)) & 0x3f) << 8) | (*((p)+1)))+1)
#define HLL_SPARSE_VAL_VALUE(p) ((((*(p)) >> 2) & 0x1f)+1)
#define HLL_SPARSE_VAL_LEN(p) (((*(p)) & 0x3)+1)
#define HLL_SPARSE_VAL_MAX_VALUE 32
#define HLL_SPARSE_VAL_MAX_LEN 4
#define HLL_SPARSE_ZERO_MAX_LEN 64
#define HLL_SPARSE_XZERO_MAX_LEN 16384
#define HLL_SPARSE_VAL_SET(p,val,len) do { \
*(p) = (((val)-1)<<2|((len)-1))|HLL_SPARSE_VAL_BIT; \
} while(0)
#define HLL_SPARSE_ZERO_SET(p,len) do { \
*(p) = (len)-1; \
} while(0)
#define HLL_SPARSE_XZERO_SET(p,len) do { \
int _l = (len)-1; \
*(p) = (_l>>8) | HLL_SPARSE_XZERO_BIT; \
*((p)+1) = (_l&0xff); \
} while(0)
#define HLL_ALPHA_INF 0.721347520444481703680 /* constant for 0.5/ln(2) */
/* ========================= HyperLogLog algorithm ========================= */
/* Our hash function is MurmurHash2, 64 bit version.
* It was modified for Redis in order to provide the same result in
* big and little endian archs (endian neutral). */
uint64_t MurmurHash64A (const void * key, int len, unsigned int seed) {
const uint64_t m = 0xc6a4a7935bd1e995;
const int r = 47;
uint64_t h = seed ^ (len * m);
const uint8_t *data = (const uint8_t *)key;
const uint8_t *end = data + (len-(len&7));
while(data != end) {
uint64_t k;
#if (BYTE_ORDER == LITTLE_ENDIAN)
#ifdef USE_ALIGNED_ACCESS
memcpy(&k,data,sizeof(uint64_t));
#else
k = *((uint64_t*)data);
#endif
#else
k = (uint64_t) data[0];
k |= (uint64_t) data[1] << 8;
k |= (uint64_t) data[2] << 16;
k |= (uint64_t) data[3] << 24;
k |= (uint64_t) data[4] << 32;
k |= (uint64_t) data[5] << 40;
k |= (uint64_t) data[6] << 48;
k |= (uint64_t) data[7] << 56;
#endif
k *= m;
k ^= k >> r;
k *= m;
h ^= k;
h *= m;
data += 8;
}
switch(len & 7) {
case 7: h ^= (uint64_t)data[6] << 48; /* fall-thru */
case 6: h ^= (uint64_t)data[5] << 40; /* fall-thru */
case 5: h ^= (uint64_t)data[4] << 32; /* fall-thru */
case 4: h ^= (uint64_t)data[3] << 24; /* fall-thru */
case 3: h ^= (uint64_t)data[2] << 16; /* fall-thru */
case 2: h ^= (uint64_t)data[1] << 8; /* fall-thru */
case 1: h ^= (uint64_t)data[0];
h *= m; /* fall-thru */
};
h ^= h >> r;
h *= m;
h ^= h >> r;
return h;
}
/* Given a string element to add to the HyperLogLog, returns the length
* of the pattern 000..1 of the element hash. As a side effect 'regp' is
* set to the register index this element hashes to. */
int hllPatLen(unsigned char *ele, size_t elesize, long *regp) {
uint64_t hash, bit, index;
int count;
/* Count the number of zeroes starting from bit HLL_REGISTERS
* (that is a power of two corresponding to the first bit we don't use
* as index). The max run can be 64-P+1 = Q+1 bits.
*
* Note that the final "1" ending the sequence of zeroes must be
* included in the count, so if we find "001" the count is 3, and
* the smallest count possible is no zeroes at all, just a 1 bit
* at the first position, that is a count of 1.
*
* This may sound like inefficient, but actually in the average case
* there are high probabilities to find a 1 after a few iterations. */
hash = MurmurHash64A(ele,elesize,0xadc83b19ULL);
index = hash & HLL_P_MASK; /* Register index. */
hash >>= HLL_P; /* Remove bits used to address the register. */
hash |= ((uint64_t)1<<HLL_Q); /* Make sure the loop terminates
and count will be <= Q+1. */
bit = 1;
count = 1; /* Initialized to 1 since we count the "00000...1" pattern. */
while((hash & bit) == 0) {
count++;
bit <<= 1;
}
*regp = (int) index;
return count;
}
/* ================== Dense representation implementation ================== */
/* Low level function to set the dense HLL register at 'index' to the
* specified value if the current value is smaller than 'count'.
*
* 'registers' is expected to have room for HLL_REGISTERS plus an
* additional byte on the right. This requirement is met by sds strings
* automatically since they are implicitly null terminated.
*
* The function always succeed, however if as a result of the operation
* the approximated cardinality changed, 1 is returned. Otherwise 0
* is returned. */
int hllDenseSet(uint8_t *registers, long index, uint8_t count) {
uint8_t oldcount;
HLL_DENSE_GET_REGISTER(oldcount,registers,index);
if (count > oldcount) {
HLL_DENSE_SET_REGISTER(registers,index,count);
return 1;
} else {
return 0;
}
}
/* "Add" the element in the dense hyperloglog data structure.
* Actually nothing is added, but the max 0 pattern counter of the subset
* the element belongs to is incremented if needed.
*
* This is just a wrapper to hllDenseSet(), performing the hashing of the
* element in order to retrieve the index and zero-run count. */
int hllDenseAdd(uint8_t *registers, unsigned char *ele, size_t elesize) {
long index;
uint8_t count = hllPatLen(ele,elesize,&index);
/* Update the register if this element produced a longer run of zeroes. */
return hllDenseSet(registers,index,count);
}
/* Compute the register histogram in the dense representation. */
void hllDenseRegHisto(uint8_t *registers, int* reghisto) {
int j;
/* Redis default is to use 16384 registers 6 bits each. The code works
* with other values by modifying the defines, but for our target value
* we take a faster path with unrolled loops. */
if (HLL_REGISTERS == 16384 && HLL_BITS == 6) {
uint8_t *r = registers;
unsigned long r0, r1, r2, r3, r4, r5, r6, r7, r8, r9,
r10, r11, r12, r13, r14, r15;
for (j = 0; j < 1024; j++) {
/* Handle 16 registers per iteration. */
r0 = r[0] & 63;
r1 = (r[0] >> 6 | r[1] << 2) & 63;
r2 = (r[1] >> 4 | r[2] << 4) & 63;
r3 = (r[2] >> 2) & 63;
r4 = r[3] & 63;
r5 = (r[3] >> 6 | r[4] << 2) & 63;
r6 = (r[4] >> 4 | r[5] << 4) & 63;
r7 = (r[5] >> 2) & 63;
r8 = r[6] & 63;
r9 = (r[6] >> 6 | r[7] << 2) & 63;
r10 = (r[7] >> 4 | r[8] << 4) & 63;
r11 = (r[8] >> 2) & 63;
r12 = r[9] & 63;
r13 = (r[9] >> 6 | r[10] << 2) & 63;
r14 = (r[10] >> 4 | r[11] << 4) & 63;
r15 = (r[11] >> 2) & 63;
reghisto[r0]++;
reghisto[r1]++;
reghisto[r2]++;
reghisto[r3]++;
reghisto[r4]++;
reghisto[r5]++;
reghisto[r6]++;
reghisto[r7]++;
reghisto[r8]++;
reghisto[r9]++;
reghisto[r10]++;
reghisto[r11]++;
reghisto[r12]++;
reghisto[r13]++;
reghisto[r14]++;
reghisto[r15]++;
r += 12;
}
} else {
for(j = 0; j < HLL_REGISTERS; j++) {
unsigned long reg;
HLL_DENSE_GET_REGISTER(reg,registers,j);
reghisto[reg]++;
}
}
}
/* ================== Sparse representation implementation ================= */
/* Convert the HLL with sparse representation given as input in its dense
* representation. Both representations are represented by SDS strings, and
* the input representation is freed as a side effect.
*
* The function returns C_OK if the sparse representation was valid,
* otherwise C_ERR is returned if the representation was corrupted. */
int hllSparseToDense(robj *o) {
sds sparse = o->ptr, dense;
struct hllhdr *hdr, *oldhdr = (struct hllhdr*)sparse;
int idx = 0, runlen, regval;
uint8_t *p = (uint8_t*)sparse, *end = p+sdslen(sparse);
/* If the representation is already the right one return ASAP. */
hdr = (struct hllhdr*) sparse;
if (hdr->encoding == HLL_DENSE) return C_OK;
/* Create a string of the right size filled with zero bytes.
* Note that the cached cardinality is set to 0 as a side effect
* that is exactly the cardinality of an empty HLL. */
dense = sdsnewlen(NULL,HLL_DENSE_SIZE);
hdr = (struct hllhdr*) dense;
*hdr = *oldhdr; /* This will copy the magic and cached cardinality. */
hdr->encoding = HLL_DENSE;
/* Now read the sparse representation and set non-zero registers
* accordingly. */
p += HLL_HDR_SIZE;
while(p < end) {
if (HLL_SPARSE_IS_ZERO(p)) {
runlen = HLL_SPARSE_ZERO_LEN(p);
idx += runlen;
p++;
} else if (HLL_SPARSE_IS_XZERO(p)) {
runlen = HLL_SPARSE_XZERO_LEN(p);
idx += runlen;
p += 2;
} else {
runlen = HLL_SPARSE_VAL_LEN(p);
regval = HLL_SPARSE_VAL_VALUE(p);
while(runlen--) {
HLL_DENSE_SET_REGISTER(hdr->registers,idx,regval);
idx++;
}
p++;
}
}
/* If the sparse representation was valid, we expect to find idx
* set to HLL_REGISTERS. */
if (idx != HLL_REGISTERS) {
sdsfree(dense);
return C_ERR;
}
/* Free the old representation and set the new one. */
sdsfree(o->ptr);
o->ptr = dense;
return C_OK;
}
/* Low level function to set the sparse HLL register at 'index' to the
* specified value if the current value is smaller than 'count'.
*
* The object 'o' is the String object holding the HLL. The function requires
* a reference to the object in order to be able to enlarge the string if
* needed.
*
* On success, the function returns 1 if the cardinality changed, or 0
* if the register for this element was not updated.
* On error (if the representation is invalid) -1 is returned.
*
* As a side effect the function may promote the HLL representation from
* sparse to dense: this happens when a register requires to be set to a value
* not representable with the sparse representation, or when the resulting
* size would be greater than server.hll_sparse_max_bytes. */
int hllSparseSet(robj *o, long index, uint8_t count) {
struct hllhdr *hdr;
uint8_t oldcount, *sparse, *end, *p, *prev, *next;
long first, span;
long is_zero = 0, is_xzero = 0, is_val = 0, runlen = 0;
/* If the count is too big to be representable by the sparse representation
* switch to dense representation. */
if (count > HLL_SPARSE_VAL_MAX_VALUE) goto promote;
/* When updating a sparse representation, sometimes we may need to
* enlarge the buffer for up to 3 bytes in the worst case (XZERO split
* into XZERO-VAL-XZERO). Make sure there is enough space right now
* so that the pointers we take during the execution of the function
* will be valid all the time. */
o->ptr = sdsMakeRoomFor(o->ptr,3);
/* Step 1: we need to locate the opcode we need to modify to check
* if a value update is actually needed. */
sparse = p = ((uint8_t*)o->ptr) + HLL_HDR_SIZE;
end = p + sdslen(o->ptr) - HLL_HDR_SIZE;
first = 0;
prev = NULL; /* Points to previos opcode at the end of the loop. */
next = NULL; /* Points to the next opcode at the end of the loop. */
span = 0;
while(p < end) {
long oplen;
/* Set span to the number of registers covered by this opcode.
*
* This is the most performance critical loop of the sparse
* representation. Sorting the conditionals from the most to the
* least frequent opcode in many-bytes sparse HLLs is faster. */
oplen = 1;
if (HLL_SPARSE_IS_ZERO(p)) {
span = HLL_SPARSE_ZERO_LEN(p);
} else if (HLL_SPARSE_IS_VAL(p)) {
span = HLL_SPARSE_VAL_LEN(p);
} else { /* XZERO. */
span = HLL_SPARSE_XZERO_LEN(p);
oplen = 2;
}
/* Break if this opcode covers the register as 'index'. */
if (index <= first+span-1) break;
prev = p;
p += oplen;
first += span;
}
if (span == 0) return -1; /* Invalid format. */
next = HLL_SPARSE_IS_XZERO(p) ? p+2 : p+1;
if (next >= end) next = NULL;
/* Cache current opcode type to avoid using the macro again and
* again for something that will not change.
* Also cache the run-length of the opcode. */
if (HLL_SPARSE_IS_ZERO(p)) {
is_zero = 1;
runlen = HLL_SPARSE_ZERO_LEN(p);
} else if (HLL_SPARSE_IS_XZERO(p)) {
is_xzero = 1;
runlen = HLL_SPARSE_XZERO_LEN(p);
} else {
is_val = 1;
runlen = HLL_SPARSE_VAL_LEN(p);
}
/* Step 2: After the loop:
*
* 'first' stores to the index of the first register covered
* by the current opcode, which is pointed by 'p'.
*
* 'next' ad 'prev' store respectively the next and previous opcode,
* or NULL if the opcode at 'p' is respectively the last or first.
*
* 'span' is set to the number of registers covered by the current
* opcode.
*
* There are different cases in order to update the data structure
* in place without generating it from scratch:
*
* A) If it is a VAL opcode already set to a value >= our 'count'
* no update is needed, regardless of the VAL run-length field.
* In this case PFADD returns 0 since no changes are performed.
*
* B) If it is a VAL opcode with len = 1 (representing only our
* register) and the value is less than 'count', we just update it
* since this is a trivial case. */
if (is_val) {
oldcount = HLL_SPARSE_VAL_VALUE(p);
/* Case A. */
if (oldcount >= count) return 0;
/* Case B. */
if (runlen == 1) {
HLL_SPARSE_VAL_SET(p,count,1);
goto updated;
}
}
/* C) Another trivial to handle case is a ZERO opcode with a len of 1.
* We can just replace it with a VAL opcode with our value and len of 1. */
if (is_zero && runlen == 1) {
HLL_SPARSE_VAL_SET(p,count,1);
goto updated;
}
/* D) General case.
*
* The other cases are more complex: our register requires to be updated
* and is either currently represented by a VAL opcode with len > 1,
* by a ZERO opcode with len > 1, or by an XZERO opcode.
*
* In those cases the original opcode must be split into muliple
* opcodes. The worst case is an XZERO split in the middle resuling into
* XZERO - VAL - XZERO, so the resulting sequence max length is
* 5 bytes.
*
* We perform the split writing the new sequence into the 'new' buffer
* with 'newlen' as length. Later the new sequence is inserted in place
* of the old one, possibly moving what is on the right a few bytes
* if the new sequence is longer than the older one. */
uint8_t seq[5], *n = seq;
int last = first+span-1; /* Last register covered by the sequence. */
int len;
if (is_zero || is_xzero) {
/* Handle splitting of ZERO / XZERO. */
if (index != first) {
len = index-first;
if (len > HLL_SPARSE_ZERO_MAX_LEN) {
HLL_SPARSE_XZERO_SET(n,len);
n += 2;
} else {
HLL_SPARSE_ZERO_SET(n,len);
n++;
}
}
HLL_SPARSE_VAL_SET(n,count,1);
n++;
if (index != last) {
len = last-index;
if (len > HLL_SPARSE_ZERO_MAX_LEN) {
HLL_SPARSE_XZERO_SET(n,len);
n += 2;
} else {
HLL_SPARSE_ZERO_SET(n,len);
n++;
}
}
} else {
/* Handle splitting of VAL. */
int curval = HLL_SPARSE_VAL_VALUE(p);
if (index != first) {
len = index-first;
HLL_SPARSE_VAL_SET(n,curval,len);
n++;
}
HLL_SPARSE_VAL_SET(n,count,1);
n++;
if (index != last) {
len = last-index;
HLL_SPARSE_VAL_SET(n,curval,len);
n++;
}
}
/* Step 3: substitute the new sequence with the old one.
*
* Note that we already allocated space on the sds string
* calling sdsMakeRoomFor(). */
int seqlen = n-seq;
int oldlen = is_xzero ? 2 : 1;
int deltalen = seqlen-oldlen;
if (deltalen > 0 &&
sdslen(o->ptr)+deltalen > server.hll_sparse_max_bytes) goto promote;
if (deltalen && next) memmove(next+deltalen,next,end-next);
sdsIncrLen(o->ptr,deltalen);
memcpy(p,seq,seqlen);
end += deltalen;
updated:
/* Step 4: Merge adjacent values if possible.
*
* The representation was updated, however the resulting representation
* may not be optimal: adjacent VAL opcodes can sometimes be merged into
* a single one. */
p = prev ? prev : sparse;
int scanlen = 5; /* Scan up to 5 upcodes starting from prev. */
while (p < end && scanlen--) {
if (HLL_SPARSE_IS_XZERO(p)) {
p += 2;
continue;
} else if (HLL_SPARSE_IS_ZERO(p)) {
p++;
continue;
}
/* We need two adjacent VAL opcodes to try a merge, having
* the same value, and a len that fits the VAL opcode max len. */
if (p+1 < end && HLL_SPARSE_IS_VAL(p+1)) {
int v1 = HLL_SPARSE_VAL_VALUE(p);
int v2 = HLL_SPARSE_VAL_VALUE(p+1);
if (v1 == v2) {
int len = HLL_SPARSE_VAL_LEN(p)+HLL_SPARSE_VAL_LEN(p+1);
if (len <= HLL_SPARSE_VAL_MAX_LEN) {
HLL_SPARSE_VAL_SET(p+1,v1,len);
memmove(p,p+1,end-p);
sdsIncrLen(o->ptr,-1);
end--;
/* After a merge we reiterate without incrementing 'p'
* in order to try to merge the just merged value with
* a value on its right. */
continue;
}
}
}
p++;
}
/* Invalidate the cached cardinality. */
hdr = o->ptr;
HLL_INVALIDATE_CACHE(hdr);
return 1;
promote: /* Promote to dense representation. */
if (hllSparseToDense(o) == C_ERR) return -1; /* Corrupted HLL. */
hdr = o->ptr;
/* We need to call hllDenseAdd() to perform the operation after the
* conversion. However the result must be 1, since if we need to
* convert from sparse to dense a register requires to be updated.
*
* Note that this in turn means that PFADD will make sure the command
* is propagated to slaves / AOF, so if there is a sparse -> dense
* convertion, it will be performed in all the slaves as well. */
int dense_retval = hllDenseSet(hdr->registers,index,count);
serverAssert(dense_retval == 1);
return dense_retval;
}
/* "Add" the element in the sparse hyperloglog data structure.
* Actually nothing is added, but the max 0 pattern counter of the subset
* the element belongs to is incremented if needed.
*
* This function is actually a wrapper for hllSparseSet(), it only performs
* the hashshing of the elmenet to obtain the index and zeros run length. */
int hllSparseAdd(robj *o, unsigned char *ele, size_t elesize) {
long index;
uint8_t count = hllPatLen(ele,elesize,&index);
/* Update the register if this element produced a longer run of zeroes. */
return hllSparseSet(o,index,count);
}
/* Compute the register histogram in the sparse representation. */
void hllSparseRegHisto(uint8_t *sparse, int sparselen, int *invalid, int* reghisto) {
int idx = 0, runlen, regval;
uint8_t *end = sparse+sparselen, *p = sparse;
while(p < end) {
if (HLL_SPARSE_IS_ZERO(p)) {
runlen = HLL_SPARSE_ZERO_LEN(p);
idx += runlen;
reghisto[0] += runlen;
p++;
} else if (HLL_SPARSE_IS_XZERO(p)) {
runlen = HLL_SPARSE_XZERO_LEN(p);
idx += runlen;
reghisto[0] += runlen;
p += 2;
} else {
runlen = HLL_SPARSE_VAL_LEN(p);
regval = HLL_SPARSE_VAL_VALUE(p);
idx += runlen;
reghisto[regval] += runlen;
p++;
}
}
if (idx != HLL_REGISTERS && invalid) *invalid = 1;
}
/* ========================= HyperLogLog Count ==============================
* This is the core of the algorithm where the approximated count is computed.
* The function uses the lower level hllDenseRegHisto() and hllSparseRegHisto()
* functions as helpers to compute histogram of register values part of the
* computation, which is representation-specific, while all the rest is common. */
/* Implements the register histogram calculation for uint8_t data type
* which is only used internally as speedup for PFCOUNT with multiple keys. */
void hllRawRegHisto(uint8_t *registers, int* reghisto) {
uint64_t *word = (uint64_t*) registers;
uint8_t *bytes;
int j;
for (j = 0; j < HLL_REGISTERS/8; j++) {
if (*word == 0) {
reghisto[0] += 8;
} else {
bytes = (uint8_t*) word;
reghisto[bytes[0]]++;
reghisto[bytes[1]]++;
reghisto[bytes[2]]++;
reghisto[bytes[3]]++;
reghisto[bytes[4]]++;
reghisto[bytes[5]]++;
reghisto[bytes[6]]++;
reghisto[bytes[7]]++;
}
word++;
}
}
/* Helper function sigma as defined in
* "New cardinality estimation algorithms for HyperLogLog sketches"
* Otmar Ertl, arXiv:1702.01284 */
double hllSigma(double x) {
if (x == 1.) return INFINITY;
double zPrime;
double y = 1;
double z = x;
do {
x *= x;
zPrime = z;
z += x * y;
y += y;
} while(zPrime != z);
return z;
}
/* Helper function tau as defined in
* "New cardinality estimation algorithms for HyperLogLog sketches"
* Otmar Ertl, arXiv:1702.01284 */
double hllTau(double x) {
if (x == 0. || x == 1.) return 0.;
double zPrime;
double y = 1.0;
double z = 1 - x;
do {
x = sqrt(x);
zPrime = z;
y *= 0.5;
z -= pow(1 - x, 2)*y;
} while(zPrime != z);
return z / 3;
}
/* Return the approximated cardinality of the set based on the harmonic
* mean of the registers values. 'hdr' points to the start of the SDS
* representing the String object holding the HLL representation.
*
* If the sparse representation of the HLL object is not valid, the integer
* pointed by 'invalid' is set to non-zero, otherwise it is left untouched.
*
* hllCount() supports a special internal-only encoding of HLL_RAW, that
* is, hdr->registers will point to an uint8_t array of HLL_REGISTERS element.
* This is useful in order to speedup PFCOUNT when called against multiple
* keys (no need to work with 6-bit integers encoding). */
uint64_t hllCount(struct hllhdr *hdr, int *invalid) {
double m = HLL_REGISTERS;
double E;
int j;
int reghisto[HLL_Q+2] = {0};
/* Compute register histogram */
if (hdr->encoding == HLL_DENSE) {
hllDenseRegHisto(hdr->registers,reghisto);
} else if (hdr->encoding == HLL_SPARSE) {
hllSparseRegHisto(hdr->registers,
sdslen((sds)hdr)-HLL_HDR_SIZE,invalid,reghisto);
} else if (hdr->encoding == HLL_RAW) {
hllRawRegHisto(hdr->registers,reghisto);
} else {
serverPanic("Unknown HyperLogLog encoding in hllCount()");
}
/* Estimate cardinality form register histogram. See:
* "New cardinality estimation algorithms for HyperLogLog sketches"
* Otmar Ertl, arXiv:1702.01284 */
double z = m * hllTau((m-reghisto[HLL_Q+1])/(double)m);
for (j = HLL_Q; j >= 1; --j) {
z += reghisto[j];
z *= 0.5;
}
z += m * hllSigma(reghisto[0]/(double)m);
E = llroundl(HLL_ALPHA_INF*m*m/z);
return (uint64_t) E;
}
/* Call hllDenseAdd() or hllSparseAdd() according to the HLL encoding. */
int hllAdd(robj *o, unsigned char *ele, size_t elesize) {
struct hllhdr *hdr = o->ptr;
switch(hdr->encoding) {
case HLL_DENSE: return hllDenseAdd(hdr->registers,ele,elesize);
case HLL_SPARSE: return hllSparseAdd(o,ele,elesize);
default: return -1; /* Invalid representation. */
}
}
/* Merge by computing MAX(registers[i],hll[i]) the HyperLogLog 'hll'
* with an array of uint8_t HLL_REGISTERS registers pointed by 'max'.
*
* The hll object must be already validated via isHLLObjectOrReply()
* or in some other way.
*
* If the HyperLogLog is sparse and is found to be invalid, C_ERR
* is returned, otherwise the function always succeeds. */
int hllMerge(uint8_t *max, robj *hll) {
struct hllhdr *hdr = hll->ptr;
int i;
if (hdr->encoding == HLL_DENSE) {
uint8_t val;
for (i = 0; i < HLL_REGISTERS; i++) {
HLL_DENSE_GET_REGISTER(val,hdr->registers,i);
if (val > max[i]) max[i] = val;
}
} else {
uint8_t *p = hll->ptr, *end = p + sdslen(hll->ptr);
long runlen, regval;
p += HLL_HDR_SIZE;
i = 0;
while(p < end) {
if (HLL_SPARSE_IS_ZERO(p)) {
runlen = HLL_SPARSE_ZERO_LEN(p);
i += runlen;
p++;
} else if (HLL_SPARSE_IS_XZERO(p)) {
runlen = HLL_SPARSE_XZERO_LEN(p);
i += runlen;
p += 2;
} else {
runlen = HLL_SPARSE_VAL_LEN(p);
regval = HLL_SPARSE_VAL_VALUE(p);
while(runlen--) {
if (regval > max[i]) max[i] = regval;
i++;
}
p++;
}
}
if (i != HLL_REGISTERS) return C_ERR;
}
return C_OK;
}
/* ========================== HyperLogLog commands ========================== */
/* Create an HLL object. We always create the HLL using sparse encoding.
* This will be upgraded to the dense representation as needed. */
robj *createHLLObject(void) {
robj *o;
struct hllhdr *hdr;
sds s;
uint8_t *p;
int sparselen = HLL_HDR_SIZE +
(((HLL_REGISTERS+(HLL_SPARSE_XZERO_MAX_LEN-1)) /
HLL_SPARSE_XZERO_MAX_LEN)*2);
int aux;
/* Populate the sparse representation with as many XZERO opcodes as
* needed to represent all the registers. */
aux = HLL_REGISTERS;
s = sdsnewlen(NULL,sparselen);
p = (uint8_t*)s + HLL_HDR_SIZE;
while(aux) {
int xzero = HLL_SPARSE_XZERO_MAX_LEN;
if (xzero > aux) xzero = aux;
HLL_SPARSE_XZERO_SET(p,xzero);
p += 2;
aux -= xzero;
}
serverAssert((p-(uint8_t*)s) == sparselen);
/* Create the actual object. */
o = createObject(OBJ_STRING,s);
hdr = o->ptr;
memcpy(hdr->magic,"HYLL",4);
hdr->encoding = HLL_SPARSE;
return o;
}
/* Check if the object is a String with a valid HLL representation.
* Return C_OK if this is true, otherwise reply to the client
* with an error and return C_ERR. */
int isHLLObjectOrReply(client *c, robj *o) {
struct hllhdr *hdr;
/* Key exists, check type */
if (checkType(c,o,OBJ_STRING))
return C_ERR; /* Error already sent. */
if (!sdsEncodedObject(o)) goto invalid;
if (stringObjectLen(o) < sizeof(*hdr)) goto invalid;
hdr = o->ptr;
/* Magic should be "HYLL". */
if (hdr->magic[0] != 'H' || hdr->magic[1] != 'Y' ||
hdr->magic[2] != 'L' || hdr->magic[3] != 'L') goto invalid;
if (hdr->encoding > HLL_MAX_ENCODING) goto invalid;
/* Dense representation string length should match exactly. */
if (hdr->encoding == HLL_DENSE &&
stringObjectLen(o) != HLL_DENSE_SIZE) goto invalid;
/* All tests passed. */
return C_OK;
invalid:
addReplySds(c,
sdsnew("-WRONGTYPE Key is not a valid "
"HyperLogLog string value.\r\n"));
return C_ERR;
}
/* PFADD var ele ele ele ... ele => :0 or :1 */
void pfaddCommand(client *c) {
robj *o = lookupKeyWrite(c->db,c->argv[1]);
struct hllhdr *hdr;
int updated = 0, j;
if (o == NULL) {
/* Create the key with a string value of the exact length to
* hold our HLL data structure. sdsnewlen() when NULL is passed
* is guaranteed to return bytes initialized to zero. */
o = createHLLObject();
dbAdd(c->db,c->argv[1],o);
updated++;
} else {
if (isHLLObjectOrReply(c,o) != C_OK) return;
o = dbUnshareStringValue(c->db,c->argv[1],o);
}
/* Perform the low level ADD operation for every element. */
for (j = 2; j < c->argc; j++) {
int retval = hllAdd(o, (unsigned char*)c->argv[j]->ptr,
sdslen(c->argv[j]->ptr));
switch(retval) {
case 1:
updated++;
break;
case -1:
addReplySds(c,sdsnew(invalid_hll_err));
return;
}
}
hdr = o->ptr;
if (updated) {
signalModifiedKey(c->db,c->argv[1]);
notifyKeyspaceEvent(NOTIFY_STRING,"pfadd",c->argv[1],c->db->id);
server.dirty++;
HLL_INVALIDATE_CACHE(hdr);
}
addReply(c, updated ? shared.cone : shared.czero);
}
/* PFCOUNT var -> approximated cardinality of set. */
void pfcountCommand(client *c) {
robj *o;
struct hllhdr *hdr;
uint64_t card;
/* Case 1: multi-key keys, cardinality of the union.
*
* When multiple keys are specified, PFCOUNT actually computes
* the cardinality of the merge of the N HLLs specified. */
if (c->argc > 2) {
uint8_t max[HLL_HDR_SIZE+HLL_REGISTERS], *registers;
int j;
/* Compute an HLL with M[i] = MAX(M[i]_j). */
memset(max,0,sizeof(max));
hdr = (struct hllhdr*) max;
hdr->encoding = HLL_RAW; /* Special internal-only encoding. */
registers = max + HLL_HDR_SIZE;
for (j = 1; j < c->argc; j++) {
/* Check type and size. */
robj *o = lookupKeyRead(c->db,c->argv[j]);
if (o == NULL) continue; /* Assume empty HLL for non existing var.*/
if (isHLLObjectOrReply(c,o) != C_OK) return;
/* Merge with this HLL with our 'max' HHL by setting max[i]
* to MAX(max[i],hll[i]). */
if (hllMerge(registers,o) == C_ERR) {
addReplySds(c,sdsnew(invalid_hll_err));
return;
}
}
/* Compute cardinality of the resulting set. */
addReplyLongLong(c,hllCount(hdr,NULL));
return;
}
/* Case 2: cardinality of the single HLL.
*
* The user specified a single key. Either return the cached value
* or compute one and update the cache. */
o = lookupKeyWrite(c->db,c->argv[1]);
if (o == NULL) {
/* No key? Cardinality is zero since no element was added, otherwise
* we would have a key as HLLADD creates it as a side effect. */
addReply(c,shared.czero);
} else {
if (isHLLObjectOrReply(c,o) != C_OK) return;
o = dbUnshareStringValue(c->db,c->argv[1],o);
/* Check if the cached cardinality is valid. */
hdr = o->ptr;
if (HLL_VALID_CACHE(hdr)) {
/* Just return the cached value. */
card = (uint64_t)hdr->card[0];
card |= (uint64_t)hdr->card[1] << 8;
card |= (uint64_t)hdr->card[2] << 16;
card |= (uint64_t)hdr->card[3] << 24;
card |= (uint64_t)hdr->card[4] << 32;
card |= (uint64_t)hdr->card[5] << 40;
card |= (uint64_t)hdr->card[6] << 48;
card |= (uint64_t)hdr->card[7] << 56;
} else {
int invalid = 0;
/* Recompute it and update the cached value. */
card = hllCount(hdr,&invalid);
if (invalid) {
addReplySds(c,sdsnew(invalid_hll_err));
return;
}
hdr->card[0] = card & 0xff;
hdr->card[1] = (card >> 8) & 0xff;
hdr->card[2] = (card >> 16) & 0xff;
hdr->card[3] = (card >> 24) & 0xff;
hdr->card[4] = (card >> 32) & 0xff;
hdr->card[5] = (card >> 40) & 0xff;
hdr->card[6] = (card >> 48) & 0xff;
hdr->card[7] = (card >> 56) & 0xff;
/* This is not considered a read-only command even if the
* data structure is not modified, since the cached value
* may be modified and given that the HLL is a Redis string
* we need to propagate the change. */
signalModifiedKey(c->db,c->argv[1]);
server.dirty++;
}
addReplyLongLong(c,card);
}
}
/* PFMERGE dest src1 src2 src3 ... srcN => OK */
void pfmergeCommand(client *c) {
uint8_t max[HLL_REGISTERS];
struct hllhdr *hdr;
int j;
int use_dense = 0; /* Use dense representation as target? */
/* Compute an HLL with M[i] = MAX(M[i]_j).
* We store the maximum into the max array of registers. We'll write
* it to the target variable later. */
memset(max,0,sizeof(max));
for (j = 1; j < c->argc; j++) {
/* Check type and size. */
robj *o = lookupKeyRead(c->db,c->argv[j]);
if (o == NULL) continue; /* Assume empty HLL for non existing var. */
if (isHLLObjectOrReply(c,o) != C_OK) return;
/* If at least one involved HLL is dense, use the dense representation
* as target ASAP to save time and avoid the conversion step. */
hdr = o->ptr;
if (hdr->encoding == HLL_DENSE) use_dense = 1;
/* Merge with this HLL with our 'max' HHL by setting max[i]
* to MAX(max[i],hll[i]). */
if (hllMerge(max,o) == C_ERR) {
addReplySds(c,sdsnew(invalid_hll_err));
return;
}
}
/* Create / unshare the destination key's value if needed. */
robj *o = lookupKeyWrite(c->db,c->argv[1]);
if (o == NULL) {
/* Create the key with a string value of the exact length to
* hold our HLL data structure. sdsnewlen() when NULL is passed
* is guaranteed to return bytes initialized to zero. */
o = createHLLObject();
dbAdd(c->db,c->argv[1],o);
} else {
/* If key exists we are sure it's of the right type/size
* since we checked when merging the different HLLs, so we
* don't check again. */
o = dbUnshareStringValue(c->db,c->argv[1],o);
}
/* Convert the destination object to dense representation if at least
* one of the inputs was dense. */
if (use_dense && hllSparseToDense(o) == C_ERR) {
addReplySds(c,sdsnew(invalid_hll_err));
return;
}
/* Write the resulting HLL to the destination HLL registers and
* invalidate the cached value. */
for (j = 0; j < HLL_REGISTERS; j++) {
if (max[j] == 0) continue;
hdr = o->ptr;
switch(hdr->encoding) {
case HLL_DENSE: hllDenseSet(hdr->registers,j,max[j]); break;
case HLL_SPARSE: hllSparseSet(o,j,max[j]); break;
}
}
hdr = o->ptr; /* o->ptr may be different now, as a side effect of
last hllSparseSet() call. */
HLL_INVALIDATE_CACHE(hdr);
signalModifiedKey(c->db,c->argv[1]);
/* We generate a PFADD event for PFMERGE for semantical simplicity
* since in theory this is a mass-add of elements. */
notifyKeyspaceEvent(NOTIFY_STRING,"pfadd",c->argv[1],c->db->id);
server.dirty++;
addReply(c,shared.ok);
}
/* ========================== Testing / Debugging ========================== */
/* PFSELFTEST
* This command performs a self-test of the HLL registers implementation.
* Something that is not easy to test from within the outside. */
#define HLL_TEST_CYCLES 1000
void pfselftestCommand(client *c) {
unsigned int j, i;
sds bitcounters = sdsnewlen(NULL,HLL_DENSE_SIZE);
struct hllhdr *hdr = (struct hllhdr*) bitcounters, *hdr2;
robj *o = NULL;
uint8_t bytecounters[HLL_REGISTERS];
/* Test 1: access registers.
* The test is conceived to test that the different counters of our data
* structure are accessible and that setting their values both result in
* the correct value to be retained and not affect adjacent values. */
for (j = 0; j < HLL_TEST_CYCLES; j++) {
/* Set the HLL counters and an array of unsigned byes of the
* same size to the same set of random values. */
for (i = 0; i < HLL_REGISTERS; i++) {
unsigned int r = rand() & HLL_REGISTER_MAX;
bytecounters[i] = r;
HLL_DENSE_SET_REGISTER(hdr->registers,i,r);
}
/* Check that we are able to retrieve the same values. */
for (i = 0; i < HLL_REGISTERS; i++) {
unsigned int val;
HLL_DENSE_GET_REGISTER(val,hdr->registers,i);
if (val != bytecounters[i]) {
addReplyErrorFormat(c,
"TESTFAILED Register %d should be %d but is %d",
i, (int) bytecounters[i], (int) val);
goto cleanup;
}
}
}
/* Test 2: approximation error.
* The test adds unique elements and check that the estimated value
* is always reasonable bounds.
*
* We check that the error is smaller than a few times than the expected
* standard error, to make it very unlikely for the test to fail because
* of a "bad" run.
*
* The test is performed with both dense and sparse HLLs at the same
* time also verifying that the computed cardinality is the same. */
memset(hdr->registers,0,HLL_DENSE_SIZE-HLL_HDR_SIZE);
o = createHLLObject();
double relerr = 1.04/sqrt(HLL_REGISTERS);
int64_t checkpoint = 1;
uint64_t seed = (uint64_t)rand() | (uint64_t)rand() << 32;
uint64_t ele;
for (j = 1; j <= 10000000; j++) {
ele = j ^ seed;
hllDenseAdd(hdr->registers,(unsigned char*)&ele,sizeof(ele));
hllAdd(o,(unsigned char*)&ele,sizeof(ele));
/* Make sure that for small cardinalities we use sparse
* encoding. */
if (j == checkpoint && j < server.hll_sparse_max_bytes/2) {
hdr2 = o->ptr;
if (hdr2->encoding != HLL_SPARSE) {
addReplyError(c, "TESTFAILED sparse encoding not used");
goto cleanup;
}
}
/* Check that dense and sparse representations agree. */
if (j == checkpoint && hllCount(hdr,NULL) != hllCount(o->ptr,NULL)) {
addReplyError(c, "TESTFAILED dense/sparse disagree");
goto cleanup;
}
/* Check error. */
if (j == checkpoint) {
int64_t abserr = checkpoint - (int64_t)hllCount(hdr,NULL);
uint64_t maxerr = ceil(relerr*6*checkpoint);
/* Adjust the max error we expect for cardinality 10
* since from time to time it is statistically likely to get
* much higher error due to collision, resulting into a false
* positive. */
if (j == 10) maxerr = 1;
if (abserr < 0) abserr = -abserr;
if (abserr > (int64_t)maxerr) {
addReplyErrorFormat(c,
"TESTFAILED Too big error. card:%llu abserr:%llu",
(unsigned long long) checkpoint,
(unsigned long long) abserr);
goto cleanup;
}
checkpoint *= 10;
}
}
/* Success! */
addReply(c,shared.ok);
cleanup:
sdsfree(bitcounters);
if (o) decrRefCount(o);
}
/* PFDEBUG <subcommand> <key> ... args ...
* Different debugging related operations about the HLL implementation. */
void pfdebugCommand(client *c) {
char *cmd = c->argv[1]->ptr;
struct hllhdr *hdr;
robj *o;
int j;
o = lookupKeyWrite(c->db,c->argv[2]);
if (o == NULL) {
addReplyError(c,"The specified key does not exist");
return;
}
if (isHLLObjectOrReply(c,o) != C_OK) return;
o = dbUnshareStringValue(c->db,c->argv[2],o);
hdr = o->ptr;
/* PFDEBUG GETREG <key> */
if (!strcasecmp(cmd,"getreg")) {
if (c->argc != 3) goto arityerr;
if (hdr->encoding == HLL_SPARSE) {
if (hllSparseToDense(o) == C_ERR) {
addReplySds(c,sdsnew(invalid_hll_err));
return;
}
server.dirty++; /* Force propagation on encoding change. */
}
hdr = o->ptr;
addReplyMultiBulkLen(c,HLL_REGISTERS);
for (j = 0; j < HLL_REGISTERS; j++) {
uint8_t val;
HLL_DENSE_GET_REGISTER(val,hdr->registers,j);
addReplyLongLong(c,val);
}
}
/* PFDEBUG DECODE <key> */
else if (!strcasecmp(cmd,"decode")) {
if (c->argc != 3) goto arityerr;
uint8_t *p = o->ptr, *end = p+sdslen(o->ptr);
sds decoded = sdsempty();
if (hdr->encoding != HLL_SPARSE) {
addReplyError(c,"HLL encoding is not sparse");
return;
}
p += HLL_HDR_SIZE;
while(p < end) {
int runlen, regval;
if (HLL_SPARSE_IS_ZERO(p)) {
runlen = HLL_SPARSE_ZERO_LEN(p);
p++;
decoded = sdscatprintf(decoded,"z:%d ",runlen);
} else if (HLL_SPARSE_IS_XZERO(p)) {
runlen = HLL_SPARSE_XZERO_LEN(p);
p += 2;
decoded = sdscatprintf(decoded,"Z:%d ",runlen);
} else {
runlen = HLL_SPARSE_VAL_LEN(p);
regval = HLL_SPARSE_VAL_VALUE(p);
p++;
decoded = sdscatprintf(decoded,"v:%d,%d ",regval,runlen);
}
}
decoded = sdstrim(decoded," ");
addReplyBulkCBuffer(c,decoded,sdslen(decoded));
sdsfree(decoded);
}
/* PFDEBUG ENCODING <key> */
else if (!strcasecmp(cmd,"encoding")) {
char *encodingstr[2] = {"dense","sparse"};
if (c->argc != 3) goto arityerr;
addReplyStatus(c,encodingstr[hdr->encoding]);
}
/* PFDEBUG TODENSE <key> */
else if (!strcasecmp(cmd,"todense")) {
int conv = 0;
if (c->argc != 3) goto arityerr;
if (hdr->encoding == HLL_SPARSE) {
if (hllSparseToDense(o) == C_ERR) {
addReplySds(c,sdsnew(invalid_hll_err));
return;
}
conv = 1;
server.dirty++; /* Force propagation on encoding change. */
}
addReply(c,conv ? shared.cone : shared.czero);
} else {
addReplyErrorFormat(c,"Unknown PFDEBUG subcommand '%s'", cmd);
}
return;
arityerr:
addReplyErrorFormat(c,
"Wrong number of arguments for the '%s' subcommand",cmd);
}
|
289562.c | #include <string.h>
#include "FSE.h"
void strtrim(char *dest, const char *src, size_t len)
{
while (src[--len] == ' ') { }
strncpy(dest, src, ++len);
dest[len] = '\0';
}
|
586269.c | /*-
* ng_etf.c Ethertype filter
*
* Copyright (c) 2001, FreeBSD Incorporated
* 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 unmodified, 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.
*
* Author: Julian Elischer <[email protected]>
*
* $FreeBSD: src/sys/netgraph/ng_etf.c,v 1.2 2002/05/31 23:48:02 archie Exp $
*/
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/mbuf.h>
#include <sys/malloc.h>
#include <sys/ctype.h>
#include <sys/errno.h>
#include <sys/queue.h>
#include <sys/syslog.h>
#include <net/ethernet.h>
#include <netgraph/ng_message.h>
#include <netgraph/ng_parse.h>
#include <netgraph/ng_etf.h>
#include <netgraph/netgraph.h>
/* If you do complicated mallocs you may want to do this */
/* and use it for your mallocs */
#ifdef NG_SEPARATE_MALLOC
MALLOC_DEFINE(M_NETGRAPH_ETF, "netgraph_etf", "netgraph etf node ");
#else
#define M_NETGRAPH_ETF M_NETGRAPH
#endif
/*
* This section contains the netgraph method declarations for the
* etf node. These methods define the netgraph 'type'.
*/
static ng_constructor_t ng_etf_constructor;
static ng_rcvmsg_t ng_etf_rcvmsg;
static ng_shutdown_t ng_etf_shutdown;
static ng_newhook_t ng_etf_newhook;
static ng_connect_t ng_etf_connect;
static ng_rcvdata_t ng_etf_rcvdata; /* note these are both ng_rcvdata_t */
static ng_disconnect_t ng_etf_disconnect;
/* Parse type for struct ng_etfstat */
static const struct ng_parse_struct_field ng_etf_stat_type_fields[]
= NG_ETF_STATS_TYPE_INFO;
static const struct ng_parse_type ng_etf_stat_type = {
&ng_parse_struct_type,
&ng_etf_stat_type_fields
};
/* Parse type for struct ng_setfilter */
static const struct ng_parse_struct_field ng_etf_filter_type_fields[]
= NG_ETF_FILTER_TYPE_INFO;
static const struct ng_parse_type ng_etf_filter_type = {
&ng_parse_struct_type,
&ng_etf_filter_type_fields
};
/* List of commands and how to convert arguments to/from ASCII */
static const struct ng_cmdlist ng_etf_cmdlist[] = {
{
NGM_ETF_COOKIE,
NGM_ETF_GET_STATUS,
"getstatus",
NULL,
&ng_etf_stat_type,
},
{
NGM_ETF_COOKIE,
NGM_ETF_SET_FLAG,
"setflag",
&ng_parse_int32_type,
NULL
},
{
NGM_ETF_COOKIE,
NGM_ETF_SET_FILTER,
"setfilter",
&ng_etf_filter_type,
NULL
},
{ 0 }
};
/* Netgraph node type descriptor */
static struct ng_type typestruct = {
NG_ABI_VERSION,
NG_ETF_NODE_TYPE,
NULL,
ng_etf_constructor,
ng_etf_rcvmsg,
ng_etf_shutdown,
ng_etf_newhook,
NULL,
ng_etf_connect,
ng_etf_rcvdata,
ng_etf_disconnect,
ng_etf_cmdlist
};
NETGRAPH_INIT(etf, &typestruct);
/* Information we store for each hook on each node */
struct ETF_hookinfo {
hook_p hook;
};
struct filter {
LIST_ENTRY(filter) next;
u_int16_t ethertype; /* network order ethertype */
hook_p match_hook; /* Hook to use on a match */
};
#define HASHSIZE 16 /* Dont change this without changing HASH() */
#define HASH(et) ((((et)>>12)+((et)>>8)+((et)>>4)+(et)) & 0x0f)
LIST_HEAD(filterhead, filter);
/* Information we store for each node */
struct ETF {
struct ETF_hookinfo downstream_hook;
struct ETF_hookinfo nomatch_hook;
node_p node; /* back pointer to node */
u_int packets_in; /* packets in from downstream */
u_int packets_out; /* packets out towards downstream */
u_int32_t flags;
struct filterhead hashtable[HASHSIZE];
};
typedef struct ETF *etf_p;
static struct filter *
ng_etf_findentry(etf_p etfp, u_int16_t ethertype)
{
struct filterhead *chain = etfp->hashtable + HASH(ethertype);
struct filter *fil;
LIST_FOREACH(fil, chain, next) {
if (fil->ethertype == ethertype) {
return (fil);
}
}
return (NULL);
}
/*
* Allocate the private data structure. The generic node has already
* been created. Link them together. We arrive with a reference to the node
* i.e. the reference count is incremented for us already.
*/
static int
ng_etf_constructor(node_p node)
{
etf_p privdata;
int i;
/* Initialize private descriptor */
MALLOC(privdata, etf_p, sizeof(*privdata), M_NETGRAPH_ETF,
M_NOWAIT | M_ZERO);
if (privdata == NULL)
return (ENOMEM);
for (i = 0; i < HASHSIZE; i++) {
LIST_INIT((privdata->hashtable + i));
}
/* Link structs together; this counts as our one reference to node */
NG_NODE_SET_PRIVATE(node, privdata);
privdata->node = node;
return (0);
}
/*
* Give our ok for a hook to be added...
* All names are ok. Two names are special.
*/
static int
ng_etf_newhook(node_p node, hook_p hook, const char *name)
{
const etf_p etfp = NG_NODE_PRIVATE(node);
struct ETF_hookinfo *hpriv;
if (strcmp(name, NG_ETF_HOOK_DOWNSTREAM) == 0) {
etfp->downstream_hook.hook = hook;
NG_HOOK_SET_PRIVATE(hook, &etfp->downstream_hook);
etfp->packets_in = 0;
etfp->packets_out = 0;
} else if (strcmp(name, NG_ETF_HOOK_NOMATCH) == 0) {
etfp->nomatch_hook.hook = hook;
NG_HOOK_SET_PRIVATE(hook, &etfp->nomatch_hook);
} else {
/*
* Any other hook name is valid and can
* later be associated with a filter rule.
*/
MALLOC(hpriv, struct ETF_hookinfo *, sizeof(*hpriv),
M_NETGRAPH_ETF, M_NOWAIT | M_ZERO);
if (hpriv == NULL) {
return (ENOMEM);
}
NG_HOOK_SET_PRIVATE(hook, hpriv);
hpriv->hook = hook;
}
return(0);
}
/*
* Get a netgraph control message.
* We actually recieve a queue item that has a pointer to the message.
* If we free the item, the message will be freed too, unless we remove
* it from the item using NGI_GET_MSG();
* The return address is also stored in the item, as an ng_ID_t,
* accessible as NGI_RETADDR(item);
* Check it is one we understand. If needed, send a response.
* We could save the address for an async action later, but don't here.
* Always free the message.
* The response should be in a malloc'd region that the caller can 'free'.
* The NG_MKRESPONSE macro does all this for us.
* A response is not required.
* Theoretically you could respond defferently to old message types if
* the cookie in the header didn't match what we consider to be current
* (so that old userland programs could continue to work).
*/
static int
ng_etf_rcvmsg(node_p node, item_p item, hook_p lasthook)
{
const etf_p etfp = NG_NODE_PRIVATE(node);
struct ng_mesg *resp = NULL;
int error = 0;
struct ng_mesg *msg;
NGI_GET_MSG(item, msg);
/* Deal with message according to cookie and command */
switch (msg->header.typecookie) {
case NGM_ETF_COOKIE:
switch (msg->header.cmd) {
case NGM_ETF_GET_STATUS:
{
struct ng_etfstat *stats;
NG_MKRESPONSE(resp, msg, sizeof(*stats), M_NOWAIT);
if (!resp) {
error = ENOMEM;
break;
}
stats = (struct ng_etfstat *) resp->data;
stats->packets_in = etfp->packets_in;
stats->packets_out = etfp->packets_out;
break;
}
case NGM_ETF_SET_FLAG:
if (msg->header.arglen != sizeof(u_int32_t)) {
error = EINVAL;
break;
}
etfp->flags = *((u_int32_t *) msg->data);
break;
case NGM_ETF_SET_FILTER:
{
struct ng_etffilter *f;
struct filter *fil;
hook_p hook;
/* Check message long enough for this command */
if (msg->header.arglen != sizeof(*f)) {
error = EINVAL;
break;
}
/* Make sure hook referenced exists */
f = (struct ng_etffilter *)msg->data;
hook = ng_findhook(node, f->matchhook);
if (hook == NULL) {
error = ENOENT;
break;
}
/* and is not the downstream hook */
if (hook == etfp->downstream_hook.hook) {
error = EINVAL;
break;
}
/* Check we don't already trap this ethertype */
if (ng_etf_findentry(etfp,
htons(f->ethertype))) {
error = EEXIST;
break;
}
/*
* Ok, make the filter and put it in the
* hashtable ready for matching.
*/
MALLOC(fil, struct filter *, sizeof(*fil),
M_NETGRAPH_ETF, M_NOWAIT | M_ZERO);
if (fil == NULL) {
return (ENOMEM);
}
fil->match_hook = hook;
fil->ethertype = htons(f->ethertype);
LIST_INSERT_HEAD( etfp->hashtable
+ HASH(fil->ethertype),
fil, next);
}
break;
default:
error = EINVAL; /* unknown command */
break;
}
break;
default:
error = EINVAL; /* unknown cookie type */
break;
}
/* Take care of synchronous response, if any */
NG_RESPOND_MSG(error, node, item, resp);
/* Free the message and return */
NG_FREE_MSG(msg);
return(error);
}
/*
* Receive data, and do something with it.
* Actually we receive a queue item which holds the data.
* If we free the item it wil also froo the data and metadata unless
* we have previously disassociated them using the NGI_GET_etf() macros.
* Possibly send it out on another link after processing.
* Possibly do something different if it comes from different
* hooks. the caller will never free m or meta, so
* if we use up this data or abort we must free BOTH of these.
*
* If we want, we may decide to force this data to be queued and reprocessed
* at the netgraph NETISR time.
* We would do that by setting the HK_QUEUE flag on our hook. We would do that
* in the connect() method.
*/
static int
ng_etf_rcvdata(hook_p hook, item_p item )
{
const etf_p etfp = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
struct ether_header *eh;
int error = 0;
struct mbuf *m;
u_int16_t ethertype;
struct filter *fil;
if (NG_HOOK_PRIVATE(hook) == NULL) { /* Shouldn't happen but.. */
NG_FREE_ITEM(item);
}
/*
* Everything not from the downstream hook goes to the
* downstream hook. But only if it matches the ethertype
* of the source hook. Un matching must go to/from 'nomatch'.
*/
/* Make sure we have an entire header */
NGI_GET_M(item, m);
if (m->m_len < sizeof(*eh) ) {
m = m_pullup(m, sizeof(*eh));
if (m == NULL) {
NG_FREE_ITEM(item);
return(EINVAL);
}
}
eh = mtod(m, struct ether_header *);
ethertype = eh->ether_type;
fil = ng_etf_findentry(etfp, ethertype);
/*
* if from downstream, select between a match hook or
* the nomatch hook
*/
if (hook == etfp->downstream_hook.hook) {
etfp->packets_in++;
if (fil && fil->match_hook) {
NG_FWD_NEW_DATA(error, item, fil->match_hook, m);
} else {
NG_FWD_NEW_DATA(error, item,etfp->nomatch_hook.hook, m);
}
} else {
/*
* It must be heading towards the downstream.
* Check that it's ethertype matches
* the filters for it's input hook.
* If it doesn't have one, check it's from nomatch.
*/
if ((fil && (fil->match_hook != hook))
|| ((fil == NULL) && (hook != etfp->nomatch_hook.hook))) {
NG_FREE_ITEM(item);
NG_FREE_M(m);
return (EPROTOTYPE);
}
NG_FWD_NEW_DATA( error, item, etfp->downstream_hook.hook, m);
if (error == 0) {
etfp->packets_out++;
}
}
return (error);
}
/*
* Do local shutdown processing..
* All our links and the name have already been removed.
*/
static int
ng_etf_shutdown(node_p node)
{
const etf_p privdata = NG_NODE_PRIVATE(node);
NG_NODE_SET_PRIVATE(node, NULL);
NG_NODE_UNREF(privdata->node);
FREE(privdata, M_NETGRAPH_ETF);
return (0);
}
/*
* This is called once we've already connected a new hook to the other node.
* It gives us a chance to balk at the last minute.
*/
static int
ng_etf_connect(hook_p hook)
{
return (0);
}
/*
* Hook disconnection
*
* For this type, removal of the last link destroys the node
*/
static int
ng_etf_disconnect(hook_p hook)
{
const etf_p etfp = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
int i;
struct filter *fil;
/* purge any rules that refer to this filter */
for (i = 0; i < HASHSIZE; i++) {
LIST_FOREACH(fil, (etfp->hashtable + i), next) {
if (fil->match_hook == hook) {
LIST_REMOVE(fil, next);
}
}
}
/* If it's not one of the special hooks, then free it */
if (hook == etfp->downstream_hook.hook) {
etfp->downstream_hook.hook = NULL;
} else if (hook == etfp->nomatch_hook.hook) {
etfp->nomatch_hook.hook = NULL;
} else {
if (NG_HOOK_PRIVATE(hook)) /* Paranoia */
FREE(NG_HOOK_PRIVATE(hook), M_NETGRAPH_ETF);
}
NG_HOOK_SET_PRIVATE(hook, NULL);
if ((NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook)) == 0)
&& (NG_NODE_IS_VALID(NG_HOOK_NODE(hook)))) /* already shutting down? */
ng_rmnode_self(NG_HOOK_NODE(hook));
return (0);
}
|
769879.c | /****************************************************************************
* libc/netdb/lib_dnsquery.c
* DNS host name to IP address resolver.
*
* The DNS resolver functions are used to lookup a hostname and map it to a
* numerical IP address.
*
* Copyright (C) 2007, 2009, 2012, 2014-2018 Gregory Nutt. All rights
* reserved.
* Author: Gregory Nutt <[email protected]>
*
* Based heavily on portions of uIP:
*
* Author: Adam Dunkels <[email protected]>
* Copyright (c) 2002-2003, Adam Dunkels.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <string.h>
#include <errno.h>
#include <debug.h>
#include <arpa/inet.h>
#include <nuttx/net/net.h>
#include <nuttx/net/dns.h>
#include "netdb/lib_dns.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* The maximum number of retries when asking for a name */
#define MAX_RETRIES 8
/* Buffer sizes
*
* The SEND_BUFFER_SIZE depends the configured DNS name size,
* sizeof(DNS query0 = Header (12 bytes) + DNS Name (Variable) +
* Query type (2 bytes) + Query Class (2 bytes)
*/
#define SEND_BUFFER_SIZE (32 + CONFIG_NETDB_DNSCLIENT_NAMESIZE)
#define RECV_BUFFER_SIZE CONFIG_NETDB_DNSCLIENT_MAXRESPONSE
/****************************************************************************
* Private Types
****************************************************************************/
struct dns_query_s
{
int sd; /* DNS server socket */
int result; /* Explanation of the failure */
FAR const char *hostname; /* Hostname to lookup */
FAR struct sockaddr *addr; /* Location to return host address */
FAR socklen_t *addrlen; /* Length of the address */
};
/****************************************************************************
* Private Data
****************************************************************************/
static uint8_t g_seqno; /* Sequence number of the next request */
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: dns_parse_name
*
* Description:
* Walk through a compact encoded DNS name and return the end of it.
*
* Input Parameters:
*
* query - A pointer to the starting byte of the name entry in the DNS
* response.
* queryend - A pointer to the byte after the last byte of the DNS response.
*
* Returned Value:
* Pointer to the first byte after the parsed name, or the value of
* `queryend` if the name did not fit into provided DNS response.
*
****************************************************************************/
static FAR uint8_t *dns_parse_name(FAR uint8_t *query, FAR uint8_t *queryend)
{
uint8_t n;
while (query < queryend)
{
n = *query++;
/* Check for a leading or trailing pointer.*/
if (n & 0xC0)
{
/* Eat second pointer byte and terminate search */
ninfo("Compressed answer\n");
query++;
break;
}
/* Check for final label with zero-length */
if (!n)
{
break;
}
/* Eat non-empty label */
query += n;
}
if (query >= queryend)
{
/* Always return `queryend` in case of errors */
nerr("ERROR: DNS response is too short\n");
query = queryend;
}
return query;
}
/****************************************************************************
* Name: dns_send_query
*
* Description:
* Runs through the list of names to see if there are any that have
* not yet been queried and, if so, sends out a query.
*
****************************************************************************/
static int dns_send_query(int sd, FAR const char *name,
FAR union dns_server_u *uaddr, uint16_t rectype)
{
register FAR struct dns_header_s *hdr;
FAR uint8_t *dest;
FAR uint8_t *nptr;
FAR const char *src;
uint8_t buffer[SEND_BUFFER_SIZE];
uint8_t seqno;
socklen_t addrlen;
int errcode;
int ret;
int n;
/* Increment the sequence number */
dns_semtake();
seqno = g_seqno++;
dns_semgive();
/* Initialize the request header */
hdr = (FAR struct dns_header_s *)buffer;
memset(hdr, 0, sizeof(struct dns_header_s));
hdr->id = htons(seqno);
hdr->flags1 = DNS_FLAG1_RD;
hdr->numquestions = HTONS(1);
dest = buffer + 12;
/* Convert hostname into suitable query format. */
src = name - 1;
do
{
/* Copy the name string */
src++;
nptr = dest++;
for (n = 0; *src != '.' && *src != 0; src++)
{
*dest++ = *(uint8_t *)src;
n++;
}
/* Pre-pend the name length */
*nptr = n;
}
while (*src != '\0');
/* Add NUL termination, DNS record type, and DNS class */
*dest++ = '\0'; /* NUL termination */
*dest++ = (rectype >> 8); /* DNS record type (big endian) */
*dest++ = (rectype & 0xff);
*dest++ = (DNS_CLASS_IN >> 8); /* DNS record class (big endian) */
*dest++ = (DNS_CLASS_IN & 0xff);
/* Send the request */
#ifdef CONFIG_NET_IPv4
#ifdef CONFIG_NET_IPv6
if (uaddr->ipv4.sin_family == AF_INET)
#endif
{
addrlen = sizeof(struct sockaddr_in);
}
#endif
#ifdef CONFIG_NET_IPv6
#ifdef CONFIG_NET_IPv4
else
#endif
{
addrlen = sizeof(struct sockaddr_in6);
}
#endif
ret = sendto(sd, buffer, dest - buffer, 0, &uaddr->addr, addrlen);
/* Return the negated errno value on sendto failure */
if (ret < 0)
{
errcode = get_errno();
nerr("ERROR: sendto failed: %d\n", errcode);
return -errcode;
}
return OK;
}
/****************************************************************************
* Name: dns_recv_response
*
* Description:
* Called when new UDP data arrives
*
****************************************************************************/
static int dns_recv_response(int sd, FAR struct sockaddr *addr,
FAR socklen_t *addrlen)
{
FAR uint8_t *nameptr;
FAR uint8_t *endofbuffer;
char buffer[RECV_BUFFER_SIZE];
FAR struct dns_answer_s *ans;
FAR struct dns_header_s *hdr;
#if 0 /* Not used */
uint8_t nquestions;
#endif
uint8_t nanswers;
int errcode;
int ret;
/* Receive the response */
ret = _NX_RECV(sd, buffer, RECV_BUFFER_SIZE, 0);
if (ret < 0)
{
errcode = -_NX_GETERRNO(ret);
nerr("ERROR: recv failed: %d\n", errcode);
return errcode;
}
if (ret < 12)
{
/* DNS header can't fit in received data */
nerr("ERROR: DNS response is too short\n");
return -EILSEQ;
}
hdr = (FAR struct dns_header_s *)buffer;
endofbuffer = (FAR uint8_t*)buffer + ret;
ninfo("ID %d\n", htons(hdr->id));
ninfo("Query %d\n", hdr->flags1 & DNS_FLAG1_RESPONSE);
ninfo("Error %d\n", hdr->flags2 & DNS_FLAG2_ERR_MASK);
ninfo("Num questions %d, answers %d, authrr %d, extrarr %d\n",
htons(hdr->numquestions), htons(hdr->numanswers),
htons(hdr->numauthrr), htons(hdr->numextrarr));
/* Check for error */
if ((hdr->flags2 & DNS_FLAG2_ERR_MASK) != 0)
{
nerr("ERROR: DNS reported error: flags2=%02x\n", hdr->flags2);
return -EPROTO;
}
/* We only care about the question(s) and the answers. The authrr
* and the extrarr are simply discarded.
*/
#if 0 /* Not used */
nquestions = htons(hdr->numquestions);
#endif
nanswers = htons(hdr->numanswers);
/* Skip the name in the question. TODO: This should really be
* checked against the name in the question, to be sure that they
* match.
*/
#if defined(CONFIG_DEBUG_NET) && defined(CONFIG_DEBUG_INFO)
{
int d = 64;
nameptr = dns_parse_name((uint8_t *)buffer + 12, endofbuffer);
if (nameptr == endofbuffer)
{
return -EILSEQ;
}
nameptr += 4;
for (; ; )
{
ninfo("%02X %02X %02X %02X %02X %02X %02X %02X \n",
nameptr[0], nameptr[1], nameptr[2], nameptr[3],
nameptr[4], nameptr[5], nameptr[6], nameptr[7]);
nameptr += 8;
d -= 8;
if (d < 0)
{
break;
}
}
}
#endif
nameptr = dns_parse_name((uint8_t *)buffer + 12, endofbuffer);
if (nameptr == endofbuffer)
{
return -EILSEQ;
}
nameptr += 4;
for (; nanswers > 0; nanswers--)
{
/* Each answer starts with a name */
nameptr = dns_parse_name(nameptr, endofbuffer);
if (nameptr == endofbuffer)
{
return -EILSEQ;
}
ans = (FAR struct dns_answer_s *)nameptr;
ninfo("Answer: type=%04x, class=%04x, ttl=%06x, length=%04x \n",
htons(ans->type), htons(ans->class),
(htons(ans->ttl[0]) << 16) | htons(ans->ttl[1]),
htons(ans->len));
/* Check for IPv4/6 address type and Internet class. Others are discarded. */
#ifdef CONFIG_NET_IPv4
if (ans->type == HTONS(DNS_RECTYPE_A) &&
ans->class == HTONS(DNS_CLASS_IN) &&
ans->len == HTONS(4) &&
nameptr + 10 + 4 <= endofbuffer)
{
ans->u.ipv4.s_addr = *(FAR uint32_t *)(nameptr + 10);
ninfo("IPv4 address: %d.%d.%d.%d\n",
(ans->u.ipv4.s_addr ) & 0xff,
(ans->u.ipv4.s_addr >> 8 ) & 0xff,
(ans->u.ipv4.s_addr >> 16) & 0xff,
(ans->u.ipv4.s_addr >> 24) & 0xff);
if (*addrlen >= sizeof(struct sockaddr_in))
{
FAR struct sockaddr_in *inaddr;
inaddr = (FAR struct sockaddr_in *)addr;
inaddr->sin_family = AF_INET;
inaddr->sin_port = 0;
inaddr->sin_addr.s_addr = ans->u.ipv4.s_addr;
*addrlen = sizeof(struct sockaddr_in);
return OK;
}
else
{
return -ERANGE;
}
}
else
#endif
#ifdef CONFIG_NET_IPv6
if (ans->type == HTONS(DNS_RECTYPE_AAAA) &&
ans->class == HTONS(DNS_CLASS_IN) &&
ans->len == HTONS(16) &&
nameptr + 10 + 16 <= endofbuffer)
{
memcpy(&ans->u.ipv6.s6_addr, nameptr + 10, 16);
ninfo("IPv6 address: %04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x\n",
htons(ans->u.ipv6.s6_addr[7]), htons(ans->u.ipv6.s6_addr[6]),
htons(ans->u.ipv6.s6_addr[5]), htons(ans->u.ipv6.s6_addr[4]),
htons(ans->u.ipv6.s6_addr[3]), htons(ans->u.ipv6.s6_addr[2]),
htons(ans->u.ipv6.s6_addr[1]), htons(ans->u.ipv6.s6_addr[0]));
if (*addrlen >= sizeof(struct sockaddr_in6))
{
FAR struct sockaddr_in6 *inaddr;
inaddr = (FAR struct sockaddr_in6 *)addr;
inaddr->sin6_family = AF_INET;
inaddr->sin6_port = 0;
memcpy(inaddr->sin6_addr.s6_addr, ans->u.ipv6.s6_addr, 16);
*addrlen = sizeof(struct sockaddr_in6);
return OK;
}
else
{
return -ERANGE;
}
}
else
#endif
{
nameptr = nameptr + 10 + htons(ans->len);
}
}
return -EADDRNOTAVAIL;
}
/****************************************************************************
* Name: dns_query_callback
*
* Description:
* Using the DNS information and this DNS server address, look up the
* hostname.
*
* Input Parameters:
* arg - Query arguements
* addr - DNS name server address
* addrlen - Length of the DNS name server address.
*
* Returned Value:
* Returns one (1) if the query was successful. Zero is returned in all
* other cases. The result field of the query structure is set to a
* negated errno value indicate the reason for the last failure (only).
*
****************************************************************************/
static int dns_query_callback(FAR void *arg, FAR struct sockaddr *addr,
FAR socklen_t addrlen)
{
FAR struct dns_query_s *query = (FAR struct dns_query_s *)arg;
int retries;
int ret;
/* Loop while receive timeout errors occur and there are remaining retries */
for (retries = 0; retries < 3; retries++)
{
#ifdef CONFIG_NET_IPv4
/* Is this an IPv4 address? */
if (addr->sa_family == AF_INET)
{
/* Yes.. verify the address size */
if (addrlen < sizeof(struct sockaddr_in))
{
/* Return zero to skip this address and try the next
* namserver address in resolv.conf.
*/
nerr("ERROR: Invalid IPv4 address size: %d\n", addrlen);
query->result = -EINVAL;
return 0;
}
/* Send the IPv4 query */
ret = dns_send_query(query->sd, query->hostname,
(FAR union dns_server_u *)addr,
DNS_RECTYPE_A);
if (ret < 0)
{
/* Return zero to skip this address and try the next
* namserver address in resolv.conf.
*/
nerr("ERROR: IPv4 dns_send_query failed: %d\n", ret);
query->result = ret;
return 0;
}
/* Obtain the IPv4 response */
ret = dns_recv_response(query->sd, query->addr, query->addrlen);
if (ret >= 0)
{
/* IPv4 response received successfully */
#if CONFIG_NETDB_DNSCLIENT_ENTRIES > 0
/* Save the answer in the DNS cache */
dns_save_answer(query->hostname, query->addr, *query->addrlen);
#endif
/* Return 1 to indicate to (1) stop the traversal, and (2)
* indicate that the address was found.
*/
return 1;
}
/* Handle errors */
nerr("ERROR: IPv4 dns_recv_response failed: %d\n", ret);
if (ret == -EADDRNOTAVAIL)
{
/* The IPv4 address is not available. Return zero to
* continue the tranversal with the next nameserver
* address in resolv.conf.
*/
query->result = -EADDRNOTAVAIL;
return 0;
}
else if (ret != -EAGAIN)
{
/* Some failure other than receive timeout occurred. Return
* zero to skip this address and try the next namserver
* address in resolv.conf.
*/
query->result = ret;
return 0;
}
}
else
#endif /* CONFIG_NET_IPv4 */
#ifdef CONFIG_NET_IPv6
/* Is this an IPv4 address? */
if (query->addr->sa_family == AF_INET6)
{
/* Yes.. verify the address size */
if (addrlen < sizeof(struct sockaddr_in6))
{
/* Return zero to skip this address and try the next
* namserver address in resolv.conf.
*/
nerr("ERROR: Invalid IPv6 address size: %d\n", addrlen);
query->result = -EINVAL;
return 0;
}
/* Send the IPv6 query */
ret = dns_send_query(query->sd, query->hostname,
(FAR union dns_server_u *)addr,
DNS_RECTYPE_AAAA);
if (ret < 0)
{
/* Return zero to skip this address and try the next
* namserver address in resolv.conf.
*/
nerr("ERROR: IPv6 dns_send_query failed: %d\n", ret);
query->result = ret;
return 0;
}
/* Obtain the IPv6 response */
ret = dns_recv_response(query->sd, query->addr, query->addrlen);
if (ret >= 0)
{
/* IPv6 response received successfully */
#if CONFIG_NETDB_DNSCLIENT_ENTRIES > 0
/* Save the answer in the DNS cache */
dns_save_answer(query->hostname, query->addr, *query->addrlen);
#endif
/* Return 1 to indicate to (1) stop the traversal, and (2)
* indicate that the address was found.
*/
return 1;
}
/* Handle errors */
nerr("ERROR: IPv6 dns_recv_response failed: %d\n", ret);
if (ret == -EADDRNOTAVAIL)
{
/* The IPv6 address is not available. Return zero to
* continue the tranversal with the next nameserver
* address in resolv.conf.
*/
query->result = -EADDRNOTAVAIL;
return 0;
}
else if (ret != -EAGAIN)
{
/* Some failure other than receive timeout occurred. Return
* zero to skip this address and try the next namserver
* address in resolv.conf.
*/
query->result = ret;
return 0;
}
}
else
#endif
{
/* Unsupported address family. Return zero to continue the
* tranversal with the next nameserver address in resolv.conf.
*/
return 0;
}
}
/* We tried three times and could not communicate with this nameserver.
* Perhaps it is down? Return zero to continue with the next address
* in the resolv.conf file.
*/
query->result = -ETIMEDOUT;
return 0;
}
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: dns_query
*
* Description:
* Using the DNS resolver socket (sd), look up the 'hostname', and
* return its IP address in 'ipaddr'
*
* Input Parameters:
* sd - The socket descriptor previously initialized by dsn_bind().
* hostname - The hostname string to be resolved.
* addr - The location to return the IP address associated with the
* hostname
* addrlen - On entry, the size of the buffer backing up the 'addr'
* pointer. On return, this location will hold the actual size of
* the returned address.
*
* Returned Value:
* Returns zero (OK) if the query was successful.
*
****************************************************************************/
int dns_query(int sd, FAR const char *hostname, FAR struct sockaddr *addr,
FAR socklen_t *addrlen)
{
FAR struct dns_query_s query;
int ret;
/* Set up the query info structure */
query.sd = sd;
query.result = -EADDRNOTAVAIL;
query.hostname = hostname;
query.addr = addr;
query.addrlen = addrlen;
/* Perform the query. dns_foreach_nameserver() will return:
*
* 1 - The query was successful.
* 0 - Look up failed
* <0 - Some other failure (?, shouldn't happen)
*/
ret = dns_foreach_nameserver(dns_query_callback, &query);
if (ret > 0)
{
/* The lookup was successful */
ret = OK;
}
else if (ret == 0)
{
ret = query.result;
}
return ret;
}
|
37391.c | /*
* Copyright (C) 2013 Realtek Semiconductor Corp.
* All Rights Reserved.
*
* Unless you and Realtek execute a separate written software license
* agreement governing use of this software, this software is licensed
* to you under the terms of the GNU General Public License version 2,
* available at https://www.gnu.org/licenses/old-licenses/gpl-2.0.txt
*
* $Revision: 76306 $
* $Date: 2017-03-08 15:13:58 +0800 (週三, 08 三月 2017) $
*
* Purpose : RTK switch high-level API for RTL8367/RTL8367C
* Feature : Here is a list of all functions and variables in rate module.
*
*/
#include <rtk_switch.h>
#include <rtk_error.h>
#include <rate.h>
#include <qos.h>
#include <string.h>
#include <rtl8367c_asicdrv.h>
#include <rtl8367c_asicdrv_meter.h>
#include <rtl8367c_asicdrv_inbwctrl.h>
#include <rtl8367c_asicdrv_scheduling.h>
/* Function Name:
* rtk_rate_shareMeter_set
* Description:
* Set meter configuration
* Input:
* index - shared meter index
* type - shared meter type
* rate - rate of share meter
* ifg_include - include IFG or not, ENABLE:include DISABLE:exclude
* Output:
* None
* Return:
* RT_ERR_OK - OK
* RT_ERR_FAILED - Failed
* RT_ERR_SMI - SMI access error
* RT_ERR_FILTER_METER_ID - Invalid meter
* RT_ERR_RATE - Invalid rate
* RT_ERR_INPUT - Invalid input parameters
* Note:
* The API can set shared meter rate and ifg include for each meter.
* The rate unit is 1 kbps and the range is from 8k to 1048568k if type is METER_TYPE_KBPS and
* the granularity of rate is 8 kbps.
* The rate unit is packets per second and the range is 1 ~ 0x1FFF if type is METER_TYPE_PPS.
* The ifg_include parameter is used
* for rate calculation with/without inter-frame-gap and preamble.
*/
rtk_api_ret_t rtk_rate_shareMeter_set(rtk_meter_id_t index, rtk_meter_type_t type, rtk_rate_t rate, rtk_enable_t ifg_include)
{
rtk_api_ret_t retVal;
/* Check initialization state */
RTK_CHK_INIT_STATE();
if (index > RTK_MAX_METER_ID)
return RT_ERR_FILTER_METER_ID;
if (type >= METER_TYPE_END)
return RT_ERR_INPUT;
if (ifg_include >= RTK_ENABLE_END)
return RT_ERR_INPUT;
switch (type)
{
case METER_TYPE_KBPS:
if (rate > RTL8367C_QOS_RATE_INPUT_MAX_HSG || rate < RTL8367C_QOS_RATE_INPUT_MIN)
return RT_ERR_RATE ;
if ((retVal = rtl8367c_setAsicShareMeter(index, rate >> 3, ifg_include)) != RT_ERR_OK)
return retVal;
break;
case METER_TYPE_PPS:
if (rate > RTL8367C_QOS_PPS_INPUT_MAX || rate < RTL8367C_QOS_PPS_INPUT_MIN)
return RT_ERR_RATE ;
if ((retVal = rtl8367c_setAsicShareMeter(index, rate, ifg_include)) != RT_ERR_OK)
return retVal;
break;
default:
return RT_ERR_INPUT;
}
/* Set Type */
if ((retVal = rtl8367c_setAsicShareMeterType(index, (rtk_uint32)type)) != RT_ERR_OK)
return retVal;
return RT_ERR_OK;
}
/* Function Name:
* rtk_rate_shareMeter_get
* Description:
* Get meter configuration
* Input:
* index - shared meter index
* Output:
* pType - Meter Type
* pRate - pointer of rate of share meter
* pIfg_include - include IFG or not, ENABLE:include DISABLE:exclude
* Return:
* RT_ERR_OK - OK
* RT_ERR_FAILED - Failed
* RT_ERR_SMI - SMI access error
* RT_ERR_FILTER_METER_ID - Invalid meter
* Note:
*
*/
rtk_api_ret_t rtk_rate_shareMeter_get(rtk_meter_id_t index, rtk_meter_type_t *pType, rtk_rate_t *pRate, rtk_enable_t *pIfg_include)
{
rtk_api_ret_t retVal;
rtk_uint32 regData;
/* Check initialization state */
RTK_CHK_INIT_STATE();
if (index > RTK_MAX_METER_ID)
return RT_ERR_FILTER_METER_ID;
if(NULL == pType)
return RT_ERR_NULL_POINTER;
if(NULL == pRate)
return RT_ERR_NULL_POINTER;
if(NULL == pIfg_include)
return RT_ERR_NULL_POINTER;
if ((retVal = rtl8367c_getAsicShareMeter(index, ®Data, pIfg_include)) != RT_ERR_OK)
return retVal;
if ((retVal = rtl8367c_getAsicShareMeterType(index, (rtk_uint32 *)pType)) != RT_ERR_OK)
return retVal;
if(*pType == METER_TYPE_KBPS)
*pRate = regData<<3;
else
*pRate = regData;
return RT_ERR_OK;
}
/* Function Name:
* rtk_rate_shareMeterBucket_set
* Description:
* Set meter Bucket Size
* Input:
* index - shared meter index
* bucket_size - Bucket Size
* Output:
* None.
* Return:
* RT_ERR_OK - OK
* RT_ERR_FAILED - Failed
* RT_ERR_INPUT - Error Input
* RT_ERR_SMI - SMI access error
* RT_ERR_FILTER_METER_ID - Invalid meter
* Note:
* The API can set shared meter bucket size.
*/
rtk_api_ret_t rtk_rate_shareMeterBucket_set(rtk_meter_id_t index, rtk_uint32 bucket_size)
{
rtk_api_ret_t retVal;
/* Check initialization state */
RTK_CHK_INIT_STATE();
if (index > RTK_MAX_METER_ID)
return RT_ERR_FILTER_METER_ID;
if(bucket_size > RTL8367C_METERBUCKETSIZEMAX)
return RT_ERR_INPUT;
if ((retVal = rtl8367c_setAsicShareMeterBucketSize(index, bucket_size)) != RT_ERR_OK)
return retVal;
return RT_ERR_OK;
}
/* Function Name:
* rtk_rate_shareMeterBucket_get
* Description:
* Get meter Bucket Size
* Input:
* index - shared meter index
* Output:
* pBucket_size - Bucket Size
* Return:
* RT_ERR_OK - OK
* RT_ERR_FAILED - Failed
* RT_ERR_SMI - SMI access error
* RT_ERR_FILTER_METER_ID - Invalid meter
* Note:
* The API can get shared meter bucket size.
*/
rtk_api_ret_t rtk_rate_shareMeterBucket_get(rtk_meter_id_t index, rtk_uint32 *pBucket_size)
{
rtk_api_ret_t retVal;
/* Check initialization state */
RTK_CHK_INIT_STATE();
if (index > RTK_MAX_METER_ID)
return RT_ERR_FILTER_METER_ID;
if(NULL == pBucket_size)
return RT_ERR_NULL_POINTER;
if ((retVal = rtl8367c_getAsicShareMeterBucketSize(index, pBucket_size)) != RT_ERR_OK)
return retVal;
return RT_ERR_OK;
}
/* Function Name:
* rtk_rate_igrBandwidthCtrlRate_set
* Description:
* Set port ingress bandwidth control
* Input:
* port - Port id
* rate - Rate of share meter
* ifg_include - include IFG or not, ENABLE:include DISABLE:exclude
* fc_enable - enable flow control or not, ENABLE:use flow control DISABLE:drop
* Output:
* None
* Return:
* RT_ERR_OK - OK
* RT_ERR_FAILED - Failed
* RT_ERR_SMI - SMI access error
* RT_ERR_PORT_ID - Invalid port number.
* RT_ERR_ENABLE - Invalid IFG parameter.
* RT_ERR_INBW_RATE - Invalid ingress rate parameter.
* Note:
* The rate unit is 1 kbps and the range is from 8k to 1048568k. The granularity of rate is 8 kbps.
* The ifg_include parameter is used for rate calculation with/without inter-frame-gap and preamble.
*/
rtk_api_ret_t rtk_rate_igrBandwidthCtrlRate_set(rtk_port_t port, rtk_rate_t rate, rtk_enable_t ifg_include, rtk_enable_t fc_enable)
{
rtk_api_ret_t retVal;
/* Check initialization state */
RTK_CHK_INIT_STATE();
/* Check Port Valid */
RTK_CHK_PORT_VALID(port);
if(ifg_include >= RTK_ENABLE_END)
return RT_ERR_INPUT;
if(fc_enable >= RTK_ENABLE_END)
return RT_ERR_INPUT;
if(rtk_switch_isHsgPort(port) == RT_ERR_OK)
{
if ((rate > RTL8367C_QOS_RATE_INPUT_MAX_HSG) || (rate < RTL8367C_QOS_RATE_INPUT_MIN))
return RT_ERR_QOS_EBW_RATE ;
}
else
{
if ((rate > RTL8367C_QOS_RATE_INPUT_MAX) || (rate < RTL8367C_QOS_RATE_INPUT_MIN))
return RT_ERR_QOS_EBW_RATE ;
}
if ((retVal = rtl8367c_setAsicPortIngressBandwidth(rtk_switch_port_L2P_get(port), rate>>3, ifg_include,fc_enable)) != RT_ERR_OK)
return retVal;
return RT_ERR_OK;
}
/* Function Name:
* rtk_rate_igrBandwidthCtrlRate_get
* Description:
* Get port ingress bandwidth control
* Input:
* port - Port id
* Output:
* pRate - Rate of share meter
* pIfg_include - Rate's calculation including IFG, ENABLE:include DISABLE:exclude
* pFc_enable - enable flow control or not, ENABLE:use flow control DISABLE:drop
* Return:
* RT_ERR_OK - OK
* RT_ERR_FAILED - Failed
* RT_ERR_SMI - SMI access error
* RT_ERR_PORT_ID - Invalid port number.
* RT_ERR_INPUT - Invalid input parameters.
* Note:
* The rate unit is 1 kbps and the range is from 8k to 1048568k. The granularity of rate is 8 kbps.
* The ifg_include parameter is used for rate calculation with/without inter-frame-gap and preamble.
*/
rtk_api_ret_t rtk_rate_igrBandwidthCtrlRate_get(rtk_port_t port, rtk_rate_t *pRate, rtk_enable_t *pIfg_include, rtk_enable_t *pFc_enable)
{
rtk_api_ret_t retVal;
rtk_uint32 regData;
/* Check initialization state */
RTK_CHK_INIT_STATE();
/* Check Port Valid */
RTK_CHK_PORT_VALID(port);
if(NULL == pIfg_include)
return RT_ERR_NULL_POINTER;
if(NULL == pFc_enable)
return RT_ERR_NULL_POINTER;
if ((retVal = rtl8367c_getAsicPortIngressBandwidth(rtk_switch_port_L2P_get(port), ®Data, pIfg_include, pFc_enable)) != RT_ERR_OK)
return retVal;
*pRate = regData<<3;
return RT_ERR_OK;
}
/* Function Name:
* rtk_rate_egrBandwidthCtrlRate_set
* Description:
* Set port egress bandwidth control
* Input:
* port - Port id
* rate - Rate of egress bandwidth
* ifg_include - include IFG or not, ENABLE:include DISABLE:exclude
* Output:
* None
* Return:
* RT_ERR_OK - OK
* RT_ERR_FAILED - Failed
* RT_ERR_SMI - SMI access error
* RT_ERR_PORT_ID - Invalid port number.
* RT_ERR_INPUT - Invalid input parameters.
* RT_ERR_QOS_EBW_RATE - Invalid egress bandwidth/rate
* Note:
* The rate unit is 1 kbps and the range is from 8k to 1048568k. The granularity of rate is 8 kbps.
* The ifg_include parameter is used for rate calculation with/without inter-frame-gap and preamble.
*/
rtk_api_ret_t rtk_rate_egrBandwidthCtrlRate_set( rtk_port_t port, rtk_rate_t rate, rtk_enable_t ifg_include)
{
rtk_api_ret_t retVal;
/* Check initialization state */
RTK_CHK_INIT_STATE();
/* Check Port Valid */
RTK_CHK_PORT_VALID(port);
if(rtk_switch_isHsgPort(port) == RT_ERR_OK)
{
if ((rate > RTL8367C_QOS_RATE_INPUT_MAX_HSG) || (rate < RTL8367C_QOS_RATE_INPUT_MIN))
return RT_ERR_QOS_EBW_RATE ;
}
else
{
if ((rate > RTL8367C_QOS_RATE_INPUT_MAX) || (rate < RTL8367C_QOS_RATE_INPUT_MIN))
return RT_ERR_QOS_EBW_RATE ;
}
if (ifg_include >= RTK_ENABLE_END)
return RT_ERR_ENABLE;
if ((retVal = rtl8367c_setAsicPortEgressRate(rtk_switch_port_L2P_get(port), rate>>3)) != RT_ERR_OK)
return retVal;
if ((retVal = rtl8367c_setAsicPortEgressRateIfg(ifg_include)) != RT_ERR_OK)
return retVal;
return RT_ERR_OK;
}
/* Function Name:
* rtk_rate_egrBandwidthCtrlRate_get
* Description:
* Get port egress bandwidth control
* Input:
* port - Port id
* Output:
* pRate - Rate of egress bandwidth
* pIfg_include - Rate's calculation including IFG, ENABLE:include DISABLE:exclude
* Return:
* RT_ERR_OK - OK
* RT_ERR_FAILED - Failed
* RT_ERR_SMI - SMI access error
* RT_ERR_PORT_ID - Invalid port number.
* RT_ERR_INPUT - Invalid input parameters.
* Note:
* The rate unit is 1 kbps and the range is from 8k to 1048568k. The granularity of rate is 8 kbps.
* The ifg_include parameter is used for rate calculation with/without inter-frame-gap and preamble.
*/
rtk_api_ret_t rtk_rate_egrBandwidthCtrlRate_get(rtk_port_t port, rtk_rate_t *pRate, rtk_enable_t *pIfg_include)
{
rtk_api_ret_t retVal;
rtk_uint32 regData;
/* Check initialization state */
RTK_CHK_INIT_STATE();
/* Check Port Valid */
RTK_CHK_PORT_VALID(port);
if(NULL == pRate)
return RT_ERR_NULL_POINTER;
if(NULL == pIfg_include)
return RT_ERR_NULL_POINTER;
if ((retVal = rtl8367c_getAsicPortEgressRate(rtk_switch_port_L2P_get(port), ®Data)) != RT_ERR_OK)
return retVal;
*pRate = regData << 3;
if ((retVal = rtl8367c_getAsicPortEgressRateIfg((rtk_uint32*)pIfg_include)) != RT_ERR_OK)
return retVal;
return RT_ERR_OK;
}
/* Function Name:
* rtk_rate_egrQueueBwCtrlEnable_get
* Description:
* Get enable status of egress bandwidth control on specified queue.
* Input:
* unit - unit id
* port - port id
* queue - queue id
* Output:
* pEnable - Pointer to enable status of egress queue bandwidth control
* Return:
* RT_ERR_OK
* RT_ERR_FAILED
* RT_ERR_PORT_ID - invalid port id
* RT_ERR_QUEUE_ID - invalid queue id
* RT_ERR_NULL_POINTER - input parameter may be null pointer
* Note:
* None
*/
rtk_api_ret_t rtk_rate_egrQueueBwCtrlEnable_get(rtk_port_t port, rtk_qid_t queue, rtk_enable_t *pEnable)
{
rtk_api_ret_t retVal;
/* Check initialization state */
RTK_CHK_INIT_STATE();
/* Check Port Valid */
RTK_CHK_PORT_VALID(port);
/*for whole port function, the queue value should be 0xFF*/
if (queue != RTK_WHOLE_SYSTEM)
return RT_ERR_QUEUE_ID;
if(NULL == pEnable)
return RT_ERR_NULL_POINTER;
if ((retVal = rtl8367c_getAsicAprEnable(rtk_switch_port_L2P_get(port),pEnable))!=RT_ERR_OK)
return retVal;
return RT_ERR_OK;
}
/* Function Name:
* rtk_rate_egrQueueBwCtrlEnable_set
* Description:
* Set enable status of egress bandwidth control on specified queue.
* Input:
* port - port id
* queue - queue id
* enable - enable status of egress queue bandwidth control
* Output:
* None
* Return:
* RT_ERR_OK
* RT_ERR_FAILED
* RT_ERR_PORT_ID - invalid port id
* RT_ERR_QUEUE_ID - invalid queue id
* RT_ERR_INPUT - invalid input parameter
* Note:
* None
*/
rtk_api_ret_t rtk_rate_egrQueueBwCtrlEnable_set(rtk_port_t port, rtk_qid_t queue, rtk_enable_t enable)
{
rtk_api_ret_t retVal;
/* Check initialization state */
RTK_CHK_INIT_STATE();
/* Check Port Valid */
RTK_CHK_PORT_VALID(port);
/*for whole port function, the queue value should be 0xFF*/
if (queue != RTK_WHOLE_SYSTEM)
return RT_ERR_QUEUE_ID;
if (enable>=RTK_ENABLE_END)
return RT_ERR_INPUT;
if ((retVal = rtl8367c_setAsicAprEnable(rtk_switch_port_L2P_get(port), enable))!=RT_ERR_OK)
return retVal;
return RT_ERR_OK;
}
/* Function Name:
* rtk_rate_egrQueueBwCtrlRate_get
* Description:
* Get rate of egress bandwidth control on specified queue.
* Input:
* port - port id
* queue - queue id
* pIndex - shared meter index
* Output:
* pRate - pointer to rate of egress queue bandwidth control
* Return:
* RT_ERR_OK
* RT_ERR_FAILED
* RT_ERR_PORT_ID - invalid port id
* RT_ERR_QUEUE_ID - invalid queue id
* RT_ERR_FILTER_METER_ID - Invalid meter id
* Note:
* The actual rate control is set in shared meters.
* The unit of granularity is 8Kbps.
*/
rtk_api_ret_t rtk_rate_egrQueueBwCtrlRate_get(rtk_port_t port, rtk_qid_t queue, rtk_meter_id_t *pIndex)
{
rtk_api_ret_t retVal;
rtk_uint32 offset_idx;
rtk_uint32 phy_port;
/* Check initialization state */
RTK_CHK_INIT_STATE();
/* Check Port Valid */
RTK_CHK_PORT_VALID(port);
if (queue >= RTK_MAX_NUM_OF_QUEUE)
return RT_ERR_QUEUE_ID;
if(NULL == pIndex)
return RT_ERR_NULL_POINTER;
phy_port = rtk_switch_port_L2P_get(port);
if ((retVal=rtl8367c_getAsicAprMeter(phy_port, queue,&offset_idx))!=RT_ERR_OK)
return retVal;
*pIndex = offset_idx + ((phy_port%4)*8);
return RT_ERR_OK;
}
/* Function Name:
* rtk_rate_egrQueueBwCtrlRate_set
* Description:
* Set rate of egress bandwidth control on specified queue.
* Input:
* port - port id
* queue - queue id
* index - shared meter index
* Output:
* None
* Return:
* RT_ERR_OK
* RT_ERR_FAILED
* RT_ERR_PORT_ID - invalid port id
* RT_ERR_QUEUE_ID - invalid queue id
* RT_ERR_FILTER_METER_ID - Invalid meter id
* Note:
* The actual rate control is set in shared meters.
* The unit of granularity is 8Kbps.
*/
rtk_api_ret_t rtk_rate_egrQueueBwCtrlRate_set(rtk_port_t port, rtk_qid_t queue, rtk_meter_id_t index)
{
rtk_api_ret_t retVal;
rtk_uint32 offset_idx;
rtk_uint32 phy_port;
/* Check initialization state */
RTK_CHK_INIT_STATE();
/* Check Port Valid */
RTK_CHK_PORT_VALID(port);
if (queue >= RTK_MAX_NUM_OF_QUEUE)
return RT_ERR_QUEUE_ID;
if (index > RTK_MAX_METER_ID)
return RT_ERR_FILTER_METER_ID;
phy_port = rtk_switch_port_L2P_get(port);
if (index < ((phy_port%4)*8) || index > (7 + (phy_port%4)*8))
return RT_ERR_FILTER_METER_ID;
offset_idx = index - ((phy_port%4)*8);
if ((retVal=rtl8367c_setAsicAprMeter(phy_port,queue,offset_idx))!=RT_ERR_OK)
return retVal;
return RT_ERR_OK;
}
|