filename
stringlengths 3
9
| code
stringlengths 4
1.87M
|
---|---|
85687.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_unescape_args.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: abiri <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/03/25 20:37:10 by abiri #+# #+# */
/* Updated: 2019/03/25 20:43:28 by abiri ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
char *ft_strunescape(char *str)
{
char *result;
size_t counter;
size_t i;
counter = 0;
i = 0;
while (str[i])
{
if (str[i] == '\\' && str[i+1] != '\\')
counter--;
counter++;
i++;
}
ft_printf("Counter len is : %d\n", counter);
result = ft_memalloc(counter + 1);
i = -1;
counter = 0;
while (str[++i])
{
if (str[i] == '\\' && str[i + 1] != '\\')
continue ;
result[counter++] = str[i];
}
return (result);
}
|
294836.c | // #include "ctl.h"
int n; int A; int R;
unsigned int pc;
inline int __phi() { return CAG(CIMP(CAP(A==1),CAF(CAP(R==1)))); }
inline int init() { A=0; R=0; }
int dobreak;
inline int body() {
dobreak = nondet();
while(1) {
if (dobreak > 0) break;
A = 1;
A = 0;
n = nondet();
while(1) {
if (!(n>0)) break;
/* ((n___old2 > loc_n)&&(loc_n>=0)) */
n--;
}
R = 1;
R=0;
dobreak = nondet();
}
while(1) { dummy=dummy; } L_return: return 0;
}
int main() { init(); body(); }
|
513039.c | /*
* %CopyrightBegin%
*
* Copyright Ericsson AB 2004-2013. 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.
*
* %CopyrightEnd%
*
*/
#include <stdio.h>
#include <stdlib.h>
#ifndef __WIN32__
# include <unistd.h>
#endif
#include <string.h>
#include <ctype.h>
#include <ic.h>
#include <erl_interface.h>
#include <ei.h>
#include "m_i__s.h"
/* OK */
void my_void_test(CORBA_Object oe_obj,
CORBA_Environment *oe_env)
{
/* printf("void test !\n"); */
}
m_i_void_test__rs* m_i_void_test__cb(CORBA_Object oe_obj,
CORBA_Environment *oe_env)
{
return (m_i_void_test__rs*) (my_void_test);
}
/* OK */
void my_long_test(CORBA_Object oe_obj,
long* a,
long* b,
long* c,
CORBA_Environment *oe_env)
{
/* printf("long test !\n"); */
}
m_i_long_test__rs* m_i_long_test__cb(CORBA_Object oe_obj,
long* a,
long* b,
long* c,
CORBA_Environment *oe_env)
{
*a = *b;
*c = *b;
return (m_i_long_test__rs*) (my_long_test);
}
/* OK */
void my_longlong_test(CORBA_Object oe_obj,
CORBA_long_long* a,
CORBA_long_long* b,
CORBA_long_long* c,
CORBA_Environment *oe_env)
{
/* printf("long test !\n"); */
}
m_i_longlong_test__rs* m_i_longlong_test__cb(CORBA_Object oe_obj,
CORBA_long_long* a,
CORBA_long_long* b,
CORBA_long_long* c,
CORBA_Environment *oe_env)
{
*a = *b;
*c = *b;
return (m_i_longlong_test__rs*) (my_longlong_test);
}
/* OK */
void my_ulong_test(CORBA_Object oe_obj,
unsigned long* a,
unsigned long* b,
unsigned long* c,
CORBA_Environment *oe_env)
{
/* printf("ulong test !\n"); */
}
m_i_ulong_test__rs* m_i_ulong_test__cb(CORBA_Object oe_obj,
unsigned long* a,
unsigned long* b,
unsigned long* c,
CORBA_Environment *oe_env)
{
*a = *b;
*c = *b;
return (m_i_ulong_test__rs*) (my_ulong_test);
}
/* OK */
void my_ulonglong_test(CORBA_Object oe_obj,
CORBA_unsigned_long_long* a,
CORBA_unsigned_long_long* b,
CORBA_unsigned_long_long* c,
CORBA_Environment *oe_env)
{
/* printf("ulong test !\n"); */
}
m_i_ulonglong_test__rs* m_i_ulonglong_test__cb(CORBA_Object oe_obj,
CORBA_unsigned_long_long* a,
CORBA_unsigned_long_long* b,
CORBA_unsigned_long_long* c,
CORBA_Environment *oe_env)
{
*a = *b;
*c = *b;
return (m_i_ulonglong_test__rs*) (my_ulonglong_test);
}
m_i_ushort_test__rs* m_i_ushort_test__cb(CORBA_Object oe_obj,
unsigned short* a,
unsigned short* b,
unsigned short* c,
CORBA_Environment *oe_env)
{
*a = *b;
*c = *b;
return (m_i_ushort_test__rs*) NULL;
}
/* OK */
void my_double_test(CORBA_Object oe_obj,
double* a,
double* b,
double* c,
CORBA_Environment *oe_env)
{
/* printf("double test !\n"); */
}
m_i_double_test__rs* m_i_double_test__cb(CORBA_Object oe_obj,
double* a,
double* b,
double* c,
CORBA_Environment *oe_env)
{
*a = *b;
*c = *b;
return (m_i_double_test__rs*) (my_double_test);
}
/* OK */
m_i_char_test__rs* m_i_char_test__cb(CORBA_Object oe_obj,
char* a,
char* b,
char* c,
CORBA_Environment *oe_env)
{
m_i_char_test__rs* rs = NULL;
*a = *b;
*c = *b;
return rs;
}
/* OK */
m_i_wchar_test__rs* m_i_wchar_test__cb(CORBA_Object oe_obj,
CORBA_wchar* a,
CORBA_wchar* b,
CORBA_wchar* c,
CORBA_Environment *oe_env)
{
m_i_wchar_test__rs* rs = NULL;
*a = *b;
*c = *b;
return rs;
}
/* OK */
m_i_octet_test__rs* m_i_octet_test__cb(CORBA_Object oe_obj,
char* a,
char* b,
char* c,
CORBA_Environment *oe_env)
{
m_i_octet_test__rs* rs = NULL;
*a = *b;
*c = *b;
return rs;
}
/* OK */
m_i_bool_test__rs* m_i_bool_test__cb(CORBA_Object oe_obj,
CORBA_boolean* a,
CORBA_boolean* b,
CORBA_boolean* c,
CORBA_Environment *oe_env)
{
m_i_bool_test__rs* rs = NULL;
*a = *b;
*c = *b;
return rs;
}
/* OK */
void my_struct_test(CORBA_Object oe_obj,
m_b* a,
m_b* b,
m_b* c,
CORBA_Environment *oe_env)
{
/* printf("struct test !\n"); */
}
m_i_struct_test__rs* m_i_struct_test__cb(CORBA_Object oe_obj,
m_b* a,
m_b* b,
m_b* c,
CORBA_Environment *oe_env)
{
*a = *b;
*c = *b;
return (m_i_struct_test__rs*) (my_struct_test);
}
/* OK */
m_i_struct2_test__rs* m_i_struct2_test__cb(CORBA_Object oe_obj,
m_es* a,
m_es* b,
m_es* c,
CORBA_Environment *oe_env)
{
m_i_struct2_test__rs* rs = NULL;
*a = *b;
*c = *b;
return rs;
}
/* OK */
/* XXX Commented out
m_i_struct3_test__rs* m_i_struct3_test__cb(CORBA_Object oe_obj,
m_simple* a,
m_simple* b,
m_simple* c,
CORBA_Environment *oe_env)
{
m_i_struct3_test__rs* rs = NULL;
*a = *b;
*c = *b;
return rs;
}
*/
/* OK */
m_i_seq1_test__rs* m_i_seq1_test__cb(CORBA_Object oe_obj,
m_bseq** a,
m_bseq* b,
m_bseq** c,
CORBA_Environment *oe_env)
{
m_i_seq1_test__rs* rs = NULL;
*a = b;
*c = b;
return rs;
}
/* OK */
m_i_seq2_test__rs* m_i_seq2_test__cb(CORBA_Object oe_obj,
m_aseq** a,
m_aseq* b,
m_aseq** c,
CORBA_Environment *oe_env)
{
m_i_seq2_test__rs* rs = NULL;
*a = b;
*c = b;
return rs;
}
/* OK */
m_i_seq3_test__rs* m_i_seq3_test__cb(CORBA_Object oe_obj,
m_lseq** a,
m_lseq* b,
m_lseq** c,
CORBA_Environment *oe_env)
{
m_i_seq3_test__rs* rs = NULL;
*a = b;
*c = b;
return rs;
}
/* OK */
m_i_seq4_test__rs* m_i_seq4_test__cb(CORBA_Object oe_obj,
m_ssstr3** a,
m_ssstr3* b,
m_ssstr3** c,
CORBA_Environment *oe_env)
{
m_i_seq4_test__rs* rs = NULL;
*a = b;
*c = b;
return rs;
}
/* OK */
m_i_seq5_test__rs* m_i_seq5_test__cb(CORBA_Object oe_obj,
m_ssarr3** a,
m_ssarr3* b,
m_ssarr3** c,
CORBA_Environment *oe_env)
{
m_i_seq5_test__rs* rs = NULL;
*a = b;
*c = b;
return rs;
}
/* OK */
m_i_array1_test__rs* m_i_array1_test__cb(CORBA_Object oe_obj,
m_arr1 a,
m_arr1 b,
m_arr1 c,
CORBA_Environment *oe_env)
{
int i;
m_i_array1_test__rs* rs = NULL;
for (i = 0; i < 500; i++) {
a[i] = b[i];
c[i] = b[i];
}
return rs;
}
/* OK */
m_i_array2_test__rs* m_i_array2_test__cb(CORBA_Object oe_obj,
m_dd a,
m_dd b,
m_dd c,
CORBA_Environment *oe_env)
{
int i,j;
m_i_array2_test__rs* rs = NULL;
for (i = 0; i < 2; i++)
for (j = 0; j < 3; j++) {
a[i][j] = b[i][j];
c[i][j] = b[i][j];
}
return rs;
}
/* OK */
m_i_enum_test__rs* m_i_enum_test__cb(CORBA_Object oe_obj,
m_fruit* a,
m_fruit* b,
m_fruit* c,
CORBA_Environment *oe_env)
{
m_i_enum_test__rs* rs = NULL;
*a = *b;
*c = *b;
return rs;
}
/* OK */
m_i_string1_test__rs* m_i_string1_test__cb(CORBA_Object oe_obj,
char ** a,
char * b,
char ** c,
CORBA_Environment *oe_env)
{
m_i_string1_test__rs* rs = NULL;
/*printf("\nString in ------> %s\n\n",b);*/
*a = b;
*c = b;
return rs;
}
/* OK */
m_i_string2_test__rs* m_i_string2_test__cb(CORBA_Object oe_obj,
m_sseq** a,
m_sseq* b,
m_sseq** c,
CORBA_Environment *oe_env)
{
m_i_string2_test__rs* rs = NULL;
*a = b;
*c = b;
return rs;
}
/* OK */
m_i_string3_test__rs* m_i_string3_test__cb(CORBA_Object oe_obj,
char ** a,
char * b,
char ** c,
CORBA_Environment *oe_env)
{
m_i_string3_test__rs* rs = NULL;
*a = b;
*c = b;
return rs;
}
m_i_string4_test__rs* m_i_string4_test__cb(CORBA_Object oe_obj,
m_strRec** a,
m_strRec* b,
m_strRec** c,
CORBA_Environment *oe_env)
{
*a = b;
*c = b;
return (m_i_string4_test__rs*) NULL;
}
/* OK */
m_i_wstring1_test__rs* m_i_wstring1_test__cb(CORBA_Object oe_obj,
CORBA_wchar ** a,
CORBA_wchar * b,
CORBA_wchar ** c,
CORBA_Environment *oe_env)
{
int tmp;
m_i_wstring1_test__rs* rs = NULL;
/*printf("\nString in ------> %s\n\n",b);*/
for(tmp = 0; tmp < 5; tmp++)
fprintf(stderr,"\np[%d] = %ld\n", tmp, b[tmp]);
*a = b;
*c = b;
return rs;
}
/* OK */
m_i_pid_test__rs* m_i_pid_test__cb(CORBA_Object oe_obj,
erlang_pid* a,
erlang_pid* b,
erlang_pid* c,
CORBA_Environment *oe_env)
{
m_i_pid_test__rs* rs = NULL;
*a = *b;
*c = *b;
return rs;
}
/* OK */
m_i_port_test__rs* m_i_port_test__cb(CORBA_Object oe_obj,
erlang_port* a,
erlang_port* b,
erlang_port* c,
CORBA_Environment *oe_env)
{
m_i_port_test__rs* rs = NULL;
strcpy((*a).node,(*b).node);
(*a).id = (*b).id;
(*a).creation = 0;
strcpy((*c).node,(*b).node);
(*c).id = (*b).id;
(*c).creation = 0;
return rs;
}
/* OK */
m_i_ref_test__rs* m_i_ref_test__cb(CORBA_Object oe_obj,
erlang_ref* a,
erlang_ref* b,
erlang_ref* c,
CORBA_Environment *oe_env)
{
m_i_ref_test__rs* rs = NULL;
strcpy((*a).node,(*b).node);
/*(*a).id = (*b).id;*/
(*a).len = (*b).len;
(*a).n[0] = (*b).n[0];
(*a).n[1] = (*b).n[1];
(*a).n[2] = (*b).n[2];
(*a).creation = 0;
strcpy((*c).node,(*b).node);
/*(*c).id = (*b).id;*/
(*c).len = (*b).len;
(*c).n[0] = (*b).n[0];
(*c).n[1] = (*b).n[1];
(*c).n[2] = (*b).n[2];
(*c).creation = 0;
return rs;
}
/* OK */
m_i_term_test__rs* m_i_term_test__cb(CORBA_Object oe_obj,
ETERM** a,
ETERM** b,
ETERM** c,
CORBA_Environment *oe_env)
{
m_i_term_test__rs* rs = NULL;
*a = *b;
*c = *b;
return rs;
}
m_i_typedef_test__rs* m_i_typedef_test__cb(CORBA_Object oe_obj,
long* a,
ETERM** b,
erlang_port* c,
ETERM** d ,
erlang_port* e,
CORBA_Environment *oe_env)
{
m_i_typedef_test__rs* rs = NULL;
*d = *b;
strcpy((*e).node,(*c).node);
(*e).id = (*c).id;
(*e).creation = 0;
*a = 4711;
return rs;
}
/* OK */
m_i_inline_sequence_test__rs* m_i_inline_sequence_test__cb(
CORBA_Object oe_obj,
m_s** a,
m_s* b,
m_s** c,
CORBA_Environment *oe_env)
{
m_i_inline_sequence_test__rs* rs = NULL;
*a = b;
*c = b;
return rs;
}
/* OK */
m_i_term_sequence_test__rs* m_i_term_sequence_test__cb(
CORBA_Object oe_obj,
m_etseq** a,
m_etseq* b,
m_etseq** c,
CORBA_Environment *oe_env)
{
m_i_term_sequence_test__rs* rs = NULL;
*a = b;
*c = b;
return rs;
}
/* OK */
m_i_term_struct_test__rs* m_i_term_struct_test__cb(CORBA_Object oe_obj,
m_et* a,
m_et* b,
m_et* c,
CORBA_Environment *oe_env)
{
m_i_term_struct_test__rs* rs = NULL;
*a = *b;
*c = *b;
return rs;
}
|
64049.c | #include <ree.h>
int compile_ree_unnecessary (ree_stream *stream, ree_builder *builder){
int character = get_ree_stream(stream);
if (character != '?')
return REE_SYNTAX_ERROR;
ree_node *nod;
int status1 = pop_ree_builder_node(builder, &nod);
if (status1)
return 1;
ree_node *node = allocate_node_from_ree_node_pool(builder->ree->pool);
if (node == NULL)
return REE_NOT_ENOUGH_MEMORY;
node->type = REE_UNNECESSARY_NODE;
node->unnecessary_node.unnecessary_node = nod;
int status10 = connect_to_ree_builder_node(node, builder);
if (status10)
return 1;
return 0;
}
|
886441.c | /*
* Copyright (c) 2008, 2009, 2010 Nicira Networks.
*
* 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 <config.h>
#include "stream-fd.h"
#include <assert.h>
#include <errno.h>
#include <poll.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include "fatal-signal.h"
#include "leak-checker.h"
#include "poll-loop.h"
#include "socket-util.h"
#include "stress.h"
#include "util.h"
#include "stream-provider.h"
#include "stream.h"
#include "vlog.h"
VLOG_DEFINE_THIS_MODULE(stream_fd);
/* Active file descriptor stream. */
struct stream_fd
{
struct stream stream;
int fd;
char *unlink_path;
};
static struct stream_class stream_fd_class;
static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(10, 25);
static void maybe_unlink_and_free(char *path);
/* Creates a new stream named 'name' that will send and receive data on 'fd'
* and stores a pointer to the stream in '*streamp'. Initial connection status
* 'connect_status' is interpreted as described for stream_init().
*
* When '*streamp' is closed, then 'unlink_path' (if nonnull) will be passed to
* fatal_signal_unlink_file_now() and then freed with free().
*
* Returns 0 if successful, otherwise a positive errno value. (The current
* implementation never fails.) */
int
new_fd_stream(const char *name, int fd, int connect_status,
char *unlink_path, struct stream **streamp)
{
struct stream_fd *s;
s = xmalloc(sizeof *s);
stream_init(&s->stream, &stream_fd_class, connect_status, name);
s->fd = fd;
s->unlink_path = unlink_path;
*streamp = &s->stream;
return 0;
}
static struct stream_fd *
stream_fd_cast(struct stream *stream)
{
stream_assert_class(stream, &stream_fd_class);
return CONTAINER_OF(stream, struct stream_fd, stream);
}
static void
fd_close(struct stream *stream)
{
struct stream_fd *s = stream_fd_cast(stream);
close(s->fd);
maybe_unlink_and_free(s->unlink_path);
free(s);
}
static int
fd_connect(struct stream *stream)
{
struct stream_fd *s = stream_fd_cast(stream);
return check_connection_completion(s->fd);
}
STRESS_OPTION(
stream_flaky_recv, "simulate failure of fd stream recvs",
100, 0, -1, 0);
static ssize_t
fd_recv(struct stream *stream, void *buffer, size_t n)
{
struct stream_fd *s = stream_fd_cast(stream);
ssize_t retval;
if (STRESS(stream_flaky_recv)) {
return -EIO;
}
retval = read(s->fd, buffer, n);
return retval >= 0 ? retval : -errno;
}
STRESS_OPTION(
stream_flaky_send, "simulate failure of fd stream sends",
100, 0, -1, 0);
static ssize_t
fd_send(struct stream *stream, const void *buffer, size_t n)
{
struct stream_fd *s = stream_fd_cast(stream);
ssize_t retval;
if (STRESS(stream_flaky_send)) {
return -EIO;
}
retval = write(s->fd, buffer, n);
return (retval > 0 ? retval
: retval == 0 ? -EAGAIN
: -errno);
}
static void
fd_wait(struct stream *stream, enum stream_wait_type wait)
{
struct stream_fd *s = stream_fd_cast(stream);
switch (wait) {
case STREAM_CONNECT:
case STREAM_SEND:
poll_fd_wait(s->fd, POLLOUT);
break;
case STREAM_RECV:
poll_fd_wait(s->fd, POLLIN);
break;
default:
NOT_REACHED();
}
}
static struct stream_class stream_fd_class = {
"fd", /* name */
NULL, /* open */
fd_close, /* close */
fd_connect, /* connect */
fd_recv, /* recv */
fd_send, /* send */
NULL, /* run */
NULL, /* run_wait */
fd_wait, /* wait */
};
/* Passive file descriptor stream. */
struct fd_pstream
{
struct pstream pstream;
int fd;
int (*accept_cb)(int fd, const struct sockaddr *, size_t sa_len,
struct stream **);
char *unlink_path;
};
static struct pstream_class fd_pstream_class;
static struct fd_pstream *
fd_pstream_cast(struct pstream *pstream)
{
pstream_assert_class(pstream, &fd_pstream_class);
return CONTAINER_OF(pstream, struct fd_pstream, pstream);
}
/* Creates a new pstream named 'name' that will accept new socket connections
* on 'fd' and stores a pointer to the stream in '*pstreamp'.
*
* When a connection has been accepted, 'accept_cb' will be called with the new
* socket fd 'fd' and the remote address of the connection 'sa' and 'sa_len'.
* accept_cb must return 0 if the connection is successful, in which case it
* must initialize '*streamp' to the new stream, or a positive errno value on
* error. In either case accept_cb takes ownership of the 'fd' passed in.
*
* When '*pstreamp' is closed, then 'unlink_path' (if nonnull) will be passed
* to fatal_signal_unlink_file_now() and freed with free().
*
* Returns 0 if successful, otherwise a positive errno value. (The current
* implementation never fails.) */
int
new_fd_pstream(const char *name, int fd,
int (*accept_cb)(int fd, const struct sockaddr *sa,
size_t sa_len, struct stream **streamp),
char *unlink_path, struct pstream **pstreamp)
{
struct fd_pstream *ps = xmalloc(sizeof *ps);
pstream_init(&ps->pstream, &fd_pstream_class, name);
ps->fd = fd;
ps->accept_cb = accept_cb;
ps->unlink_path = unlink_path;
*pstreamp = &ps->pstream;
return 0;
}
static void
pfd_close(struct pstream *pstream)
{
struct fd_pstream *ps = fd_pstream_cast(pstream);
close(ps->fd);
maybe_unlink_and_free(ps->unlink_path);
free(ps);
}
static int
pfd_accept(struct pstream *pstream, struct stream **new_streamp)
{
struct fd_pstream *ps = fd_pstream_cast(pstream);
struct sockaddr_storage ss;
socklen_t ss_len = sizeof ss;
int new_fd;
int retval;
new_fd = accept(ps->fd, (struct sockaddr *) &ss, &ss_len);
if (new_fd < 0) {
retval = errno;
if (retval != EAGAIN) {
VLOG_DBG_RL(&rl, "accept: %s", strerror(retval));
}
return retval;
}
retval = set_nonblocking(new_fd);
if (retval) {
close(new_fd);
return retval;
}
return ps->accept_cb(new_fd, (const struct sockaddr *) &ss, ss_len,
new_streamp);
}
static void
pfd_wait(struct pstream *pstream)
{
struct fd_pstream *ps = fd_pstream_cast(pstream);
poll_fd_wait(ps->fd, POLLIN);
}
static struct pstream_class fd_pstream_class = {
"pstream",
NULL,
pfd_close,
pfd_accept,
pfd_wait
};
/* Helper functions. */
static void
maybe_unlink_and_free(char *path)
{
if (path) {
fatal_signal_unlink_file_now(path);
free(path);
}
}
|
332001.c | /* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/**
* @todo "chain" the loggers - I should use the next logger instead of stderr
* @todo don't format into a temporary buffer, but directly into the
* destination buffer
*/
#include "config.h"
#include <stdarg.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <time.h>
#ifdef WIN32
#include <io.h>
#include <process.h>
#define getpid() _getpid()
#endif
#include <platform/platform.h>
#ifdef WIN32_H
#undef close
#endif
#include <memcached/extension.h>
#include <memcached/engine.h>
#include <memcached/syslog.h>
#include "extensions/protocol_extension.h"
/* Pointer to the server API */
static SERVER_HANDLE_V1 *sapi;
/* The current log level set by the user. We should ignore all log requests
* with a finer log level than this. We've registered a listener to update
* the log level when the user change it
*/
static EXTENSION_LOG_LEVEL current_log_level = EXTENSION_LOG_WARNING;
/* All messages above the current level shall be sent to stderr immediately */
static EXTENSION_LOG_LEVEL output_level = EXTENSION_LOG_WARNING;
/* To avoid the logfile to grow forever, we'll start logging to another
* file when we've added a certain amount of data to the logfile. You may
* tune this size by using the "cyclesize" configuration parameter. Use 100MB
* as the default (makes it a reasonable size to work with in your favorite
* editor ;-))
*/
static size_t cyclesz = 100 * 1024 * 1024;
/*
* We're using two buffers for logging. We'll be inserting data into one,
* while we're working on writing the other one to disk. Given that the disk
* is way slower than our CPU, we might end up in a situation that we'll be
* blocking the frontend threads if you're logging too much.
*/
static struct logbuffer {
/* Pointer to beginning of the datasegment of this buffer */
char *data;
/* The current offset of the buffer */
size_t offset;
} buffers[2];
/* The index in the buffers where we're currently inserting more data */
static int currbuffer;
/* If we should try to pretty-print the severity or not */
static bool prettyprint = false;
/* Are we running in a unit test (don't print warnings to stderr) */
static bool unit_test = false;
/* The size of the buffers (this may be tuned by the buffersize configuration
* parameter */
static size_t buffersz = 2048 * 1024;
/* The sleeptime between each forced flush of the buffer */
static size_t sleeptime = 60;
/* To avoid race condition we're protecting our shared resources with a
* single mutex. */
static cb_mutex_t mutex;
/* The thread performing the disk IO will be waiting for the input buffers
* to be filled by sleeping on the following condition variable. The
* frontend threads will notify the condition variable when the buffer is
* > 75% full
*/
static cb_cond_t cond;
/* In the "worst case scenarios" we're logging so much that the disk thread
* can't keep up with the the frontend threads. In these rare situations
* the frontend threads will block and wait for the flusher to free up log
* space
*/
static cb_cond_t space_cond;
static char hostname[256];
static pid_t pid;
/* To avoid the logs beeing flooded by the same log messages we try to
* de-duplicate the messages and instead print out:
* "message repeated xxx times"
*/
static struct {
/* The last message being added to the log */
char buffer[512];
/* The number of times we've seen this message */
int count;
/* The offset into the buffer for where the text start (after the
* timestamp)
*/
int offset;
} lastlog;
typedef void * HANDLE;
static HANDLE stdio_open(const char *path, const char *mode) {
HANDLE ret = fopen(path, mode);
if (ret) {
setbuf(ret, NULL);
}
return ret;
}
static void stdio_close(HANDLE handle) {
(void)fclose(handle);
}
static void stdio_flush(HANDLE handle) {
fflush(handle);
}
static ssize_t stdio_write(HANDLE handle, const void *ptr, size_t nbytes) {
return (ssize_t)fwrite(ptr, 1, nbytes, handle);
}
struct io_ops {
HANDLE (*open)(const char *path, const char *mode);
void (*close)(HANDLE handle);
void (*flush)(HANDLE handle);
ssize_t (*write)(HANDLE handle, const void *ptr, size_t nbytes);
} iops;
static const char *extension = "txt";
static void do_add_log_entry(const char *msg, size_t size) {
/* wait until there is room in the current buffer */
while ((buffers[currbuffer].offset + size) >= buffersz) {
if (!unit_test) {
fprintf(stderr, "WARNING: waiting for log space to be available\n");
}
cb_cond_wait(&space_cond, &mutex);
}
/* We could have performed the memcpy outside the locked region,
* but then we would need to handle the situation where we're
* flipping the ownership of the buffer (otherwise we could be
* writing rubbish to the file) */
memcpy(buffers[currbuffer].data + buffers[currbuffer].offset,
msg, size);
buffers[currbuffer].offset += size;
if (buffers[currbuffer].offset > (buffersz * 0.75)) {
/* we're getting full.. time get the logger to start doing stuff! */
cb_cond_signal(&cond);
}
}
static void flush_last_log(void) {
if (lastlog.count > 1) {
char buffer[80];
size_t len = snprintf(buffer, sizeof(buffer),
"message repeated %u times\n",
lastlog.count);
do_add_log_entry(buffer, len);
}
}
static void add_log_entry(const char *msg, int prefixlen, size_t size)
{
cb_mutex_enter(&mutex);
if (size < sizeof(lastlog.buffer)) {
if (memcmp(lastlog.buffer + lastlog.offset, msg + prefixlen, size-prefixlen) == 0) {
++lastlog.count;
} else {
flush_last_log();
do_add_log_entry(msg, size);
memcpy(lastlog.buffer, msg, size);
lastlog.offset = prefixlen;
lastlog.count = 0;
}
} else {
flush_last_log();
lastlog.buffer[0] = '\0';
lastlog.count = 0;
lastlog.offset = 0;
do_add_log_entry(msg, size);
}
cb_mutex_exit(&mutex);
}
static const char *severity2string(EXTENSION_LOG_LEVEL sev) {
switch (sev) {
case EXTENSION_LOG_WARNING:
return "WARNING";
case EXTENSION_LOG_INFO:
return "INFO";
case EXTENSION_LOG_DEBUG:
return "DEBUG";
case EXTENSION_LOG_DETAIL:
return "DETAIL";
default:
return "????";
}
}
/* Takes the syslog compliant event and calls the native logging functionality */
static void syslog_event_receiver(SyslogEvent *event) {
char buffer[2048];
size_t avail_char_in_buffer = sizeof(buffer) - 1; /*space excluding terminating char */
int prefixlen = 0;
char str[40];
int error;
struct tm tval;
time_t nsec;
uint8_t syslog_severity = event->prival & 7; /* Mask out all but 3 least-significant bits */
EXTENSION_LOG_LEVEL severity = EXTENSION_LOG_WARNING;
switch (syslog_severity) {
case SYSLOG_WARNING:
severity = EXTENSION_LOG_WARNING;
break;
case SYSLOG_NOTICE:
severity = EXTENSION_LOG_INFO;
break;
case SYSLOG_INFORMATIONAL:
severity = EXTENSION_LOG_DEBUG;
break;
case SYSLOG_DEBUG:
severity = EXTENSION_LOG_DETAIL;
break;
default:
fprintf(stderr, "ERROR: Unknown syslog_severity\n");
}
tval.tm_sec = event->time_second;
tval.tm_min = event->time_minute + event->offset_minute;
tval.tm_hour = event->time_hour + event->offset_hour;
tval.tm_mday = event->date_mday;
tval.tm_mon = event->date_month - 1;
tval.tm_year = event->date_fullyear - 1900;
tval.tm_isdst = -1;
tval.tm_wday = -1;
tval.tm_yday = -1;
nsec = mktime(&tval);
#ifdef WIN32
error = (asctime_s(str, sizeof(str), &tval) != 0);
#else
error = (asctime_r(&tval, str) == NULL);
#endif
if (error) {
prefixlen = snprintf(buffer, avail_char_in_buffer, "%u.%06u",
(unsigned int)nsec,
(unsigned int)event->time_secfrac);
} else {
const char *tz;
#ifdef HAVE_TM_ZONE
tz = tval.tm_zone;
#else
tz = tzname[tval.tm_isdst ? 1 : 0];
#endif
/* trim off ' YYYY\n' */
str[strlen(str) - 6] = '\0';
prefixlen = snprintf(buffer, avail_char_in_buffer, "%s.%06u %s",
str, (unsigned int)event->time_secfrac,
tz);
}
if (prettyprint) {
prefixlen += snprintf(buffer+prefixlen, avail_char_in_buffer-prefixlen,
" %s: ", severity2string(severity));
} else {
prefixlen += snprintf(buffer+prefixlen, avail_char_in_buffer-prefixlen,
" %u: ", (unsigned int)severity);
}
avail_char_in_buffer -= prefixlen;
/* now copy the syslog msg into the buffer */
strncat(buffer, event->msg, avail_char_in_buffer);
if (strlen(event->msg) > avail_char_in_buffer) {
fprintf(stderr, "Event message too big... cropped. Full msg: %s \n", event->msg);
}
if (severity >= current_log_level || severity >= output_level) {
if (severity >= output_level) {
fputs(buffer, stderr);
fflush(stderr);
}
if (severity >= current_log_level) {
add_log_entry(buffer, prefixlen, strlen(buffer));
}
}
}
/* Takes the current logging format and produces syslogd compliant event */
static void logger_log_wrapper(EXTENSION_LOG_LEVEL severity,
const void* client_cookie,
const char *fmt, ...) {
(void)client_cookie;
SyslogEvent event;
size_t avail_char_in_msg = sizeof(event.msg) - 1; /*space excluding terminating char */
struct timeval now;
va_list ap;
int len;
uint8_t facility = 16; /* Facility - defaulting to local0 */
uint8_t syslog_severity;
/* RFC5424 uses version 1 of syslog protocol */
event.version = 1;
event.msgid = GENERIC_EVENT;
strcpy(event.app_name, "memcached");
strcpy(event.hostname, hostname);
event.procid = (uint64_t)pid;
va_start(ap, fmt);
len = vsnprintf(event.msg, avail_char_in_msg, fmt, ap);
va_end(ap);
/* If an encoding error occurs with vsnprintf a -ive number is returned */
if ((len <= avail_char_in_msg) && (len >= 0)) {
/* add a new line to the message if not already there */
if (event.msg[len - 1] != '\n') {
event.msg[len++] = '\n';
event.msg[len] ='\0';
}
} else {
fprintf(stderr, "Syslog message dropped... too big \n");
}
switch (severity) {
case EXTENSION_LOG_WARNING:
syslog_severity = SYSLOG_WARNING;
break;
case EXTENSION_LOG_INFO:
syslog_severity = SYSLOG_NOTICE;
break;
case EXTENSION_LOG_DEBUG:
syslog_severity = SYSLOG_INFORMATIONAL;
break;
case EXTENSION_LOG_DETAIL:
syslog_severity = SYSLOG_DEBUG;
break;
default:
fprintf(stderr, "Unknown severity\n");
syslog_severity = SYSLOG_UNKNOWN;
}
/*
To produce the priority_value multiply facility by 8
i.e. shift to left 3 places. Then add the syslog_severity
*/
event.prival = (facility << 3) + syslog_severity;
/* Fill-in date structure */
if (cb_get_timeofday(&now) == 0) {
struct tm localval, utcval;
time_t nsec = (time_t)now.tv_sec;
cb_gmtime_r(&nsec, &utcval);
cb_localtime_r(&nsec, &localval);
event.date_fullyear = 1900 + utcval.tm_year;
event.date_month = 1 + utcval.tm_mon;
event.date_mday = utcval.tm_mday;
event.time_hour = utcval.tm_hour;
event.time_minute = utcval.tm_min;
event.time_second = utcval.tm_sec;
event.time_secfrac = now.tv_usec;
/* Calculate the offset from UTC to local-time */
event.offset_hour = localval.tm_hour - utcval.tm_hour;
event.offset_minute = localval.tm_min - utcval.tm_min;
} else {
fprintf(stderr, "gettimeofday failed in file_logger.c: %s\n", strerror(errno));
return;
}
/* Send the syslog event */
syslog_event_receiver(&event);
}
static HANDLE open_logfile(const char *fnm) {
static unsigned int next_id = 0;
char fname[1024];
HANDLE ret;
do {
sprintf(fname, "%s.%d.%s", fnm, next_id++, extension);
} while (access(fname, F_OK) == 0);
ret = iops.open(fname, "wb");
if (!ret) {
fprintf(stderr, "Failed to open memcached log file\n");
}
return ret;
}
static void close_logfile(HANDLE fp) {
if (fp) {
iops.close(fp);
}
}
static HANDLE reopen_logfile(HANDLE old, const char *fnm) {
close_logfile(old);
return open_logfile(fnm);
}
static size_t flush_pending_io(HANDLE file, struct logbuffer *lb) {
size_t ret = 0;
if (lb->offset > 0) {
char *ptr = lb->data;
size_t towrite = ret = lb->offset;
while (towrite > 0) {
int nw = iops.write(file, ptr, towrite);
if (nw > 0) {
ptr += nw;
towrite -= nw;
}
}
lb->offset = 0;
iops.flush(file);
}
return ret;
}
static void flush_all_buffers_to_file(HANDLE file) {
while (buffers[currbuffer].offset) {
int this = currbuffer;
currbuffer = (currbuffer == 0) ? 1 : 0;
flush_pending_io(file, buffers + this);
}
}
static volatile int run = 1;
static cb_thread_t tid;
static HANDLE fp;
static void logger_thead_main(void* arg)
{
size_t currsize = 0;
fp = open_logfile(arg);
struct timeval tp;
cb_get_timeofday(&tp);
time_t next = (time_t)tp.tv_sec;
cb_mutex_enter(&mutex);
while (run) {
cb_get_timeofday(&tp);
while ((time_t)tp.tv_sec >= next ||
buffers[currbuffer].offset > (buffersz * 0.75)) {
int this = currbuffer;
next = (time_t)tp.tv_sec + 1;
currbuffer = (currbuffer == 0) ? 1 : 0;
/* Let people who is blocked for space continue */
cb_cond_broadcast(&space_cond);
/* Perform file IO without the lock */
cb_mutex_exit(&mutex);
currsize += flush_pending_io(fp, buffers + this);
if (currsize > cyclesz) {
fp = reopen_logfile(fp, arg);
currsize = 0;
}
cb_mutex_enter(&mutex);
}
cb_get_timeofday(&tp);
next = (time_t)tp.tv_sec + (time_t)sleeptime;
if (unit_test) {
cb_cond_timedwait(&cond, &mutex, 100);
} else {
cb_cond_timedwait(&cond, &mutex, (unsigned int)(1000 * sleeptime));
}
}
if (fp) {
flush_all_buffers_to_file(fp);
close_logfile(fp);
}
cb_mutex_exit(&mutex);
free(arg);
free(buffers[0].data);
free(buffers[1].data);
}
static void exit_handler(void) {
/* Unfortunately it looks like the C runtime from MSVC "kills" the
* threads before the "atexit" handler is run, causing the program
* to halt in one of these steps depending on the state of the
* variables. Just disable the code for now.
*/
#ifndef WIN32
cb_mutex_enter(&mutex);
run = 0;
cb_cond_signal(&cond);
cb_mutex_exit(&mutex);
cb_join_thread(tid);
#endif
}
static const char *get_name(void) {
return "file logger";
}
static EXTENSION_LOGGER_DESCRIPTOR descriptor;
static void on_log_level(const void *cookie, ENGINE_EVENT_TYPE type,
const void *event_data, const void *cb_data) {
if (sapi != NULL) {
current_log_level = sapi->log->get_level();
}
}
static void logger_shutdown(bool force) {
if (force) {
// Don't bother attempting to take any mutexes - other threads may
// never run again. Just flush the buffers asap.
if (fp) {
flush_all_buffers_to_file(fp);
close_logfile(fp);
fp = NULL;
}
return;
}
int running;
cb_mutex_enter(&mutex);
flush_last_log();
running = run;
run = 0;
cb_cond_signal(&cond);
cb_mutex_exit(&mutex);
if (running) {
cb_join_thread(tid);
}
}
MEMCACHED_PUBLIC_API
EXTENSION_ERROR_CODE memcached_extensions_initialize(const char *config,
GET_SERVER_API get_server_api)
{
char *fname = NULL;
cb_mutex_initialize(&mutex);
cb_cond_initialize(&cond);
cb_cond_initialize(&space_cond);
iops.open = stdio_open;
iops.close = stdio_close;
iops.flush = stdio_flush;
iops.write = stdio_write;
descriptor.get_name = get_name;
descriptor.log = logger_log_wrapper;
descriptor.shutdown = logger_shutdown;
#ifdef HAVE_TM_ZONE
tzset();
#endif
sapi = get_server_api();
if (sapi == NULL) {
return EXTENSION_FATAL;
}
pid = (pid_t)getpid();
if (gethostname(hostname, sizeof(hostname))) {
fprintf(stderr,"Could not get the hostname");
strcpy(hostname,"unknown");
}
if (config != NULL) {
char *loglevel = NULL;
struct config_item items[8];
int ii = 0;
memset(&items, 0, sizeof(items));
items[ii].key = "filename";
items[ii].datatype = DT_STRING;
items[ii].value.dt_string = &fname;
++ii;
items[ii].key = "buffersize";
items[ii].datatype = DT_SIZE;
items[ii].value.dt_size = &buffersz;
++ii;
items[ii].key = "cyclesize";
items[ii].datatype = DT_SIZE;
items[ii].value.dt_size = &cyclesz;
++ii;
items[ii].key = "loglevel";
items[ii].datatype = DT_STRING;
items[ii].value.dt_string = &loglevel;
++ii;
items[ii].key = "prettyprint";
items[ii].datatype = DT_BOOL;
items[ii].value.dt_bool = &prettyprint;
++ii;
items[ii].key = "sleeptime";
items[ii].datatype = DT_SIZE;
items[ii].value.dt_size = &sleeptime;
++ii;
items[ii].key = "unit_test";
items[ii].datatype = DT_BOOL;
items[ii].value.dt_bool = &unit_test;
++ii;
items[ii].key = NULL;
++ii;
cb_assert(ii == 8);
if (sapi->core->parse_config(config, items, stderr) != ENGINE_SUCCESS) {
return EXTENSION_FATAL;
}
if (loglevel != NULL) {
if (strcasecmp("warning", loglevel) == 0) {
output_level = EXTENSION_LOG_WARNING;
} else if (strcasecmp("info", loglevel) == 0) {
output_level = EXTENSION_LOG_INFO;
} else if (strcasecmp("debug", loglevel) == 0) {
output_level = EXTENSION_LOG_DEBUG;
} else if (strcasecmp("detail", loglevel) == 0) {
output_level = EXTENSION_LOG_DETAIL;
} else {
fprintf(stderr, "Unknown loglevel: %s. Use warning/info/debug/detail\n",
loglevel);
return EXTENSION_FATAL;
}
}
free(loglevel);
}
if (fname == NULL) {
fname = strdup("memcached");
}
buffers[0].data = malloc(buffersz);
buffers[1].data = malloc(buffersz);
if (buffers[0].data == NULL || buffers[1].data == NULL || fname == NULL) {
fprintf(stderr, "Failed to allocate memory for the logger\n");
free(fname);
free(buffers[0].data);
free(buffers[1].data);
return EXTENSION_FATAL;
}
if (cb_create_thread(&tid, logger_thead_main, fname, 0) < 0) {
fprintf(stderr, "Failed to initialize the logger\n");
free(fname);
free(buffers[0].data);
free(buffers[1].data);
return EXTENSION_FATAL;
}
atexit(exit_handler);
current_log_level = sapi->log->get_level();
if (!sapi->extension->register_extension(EXTENSION_LOGGER, &descriptor)) {
return EXTENSION_FATAL;
}
sapi->callback->register_callback(NULL, ON_LOG_LEVEL, on_log_level, NULL);
return EXTENSION_SUCCESS;
}
|
315747.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strtoupper.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: snicolet <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/06/09 00:33:47 by snicolet #+# #+# */
/* Updated: 2016/06/09 00:57:32 by snicolet ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
char *ft_strtoupper(char *s)
{
unsigned int p;
p = 0;
while (s[p])
{
if ((s[p] >= 'a') && (s[p] <= 'z'))
s[p] = s[p] - 'a' + 'A';
p++;
}
return (s);
}
|
155515.c | /*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014 Damien P. George
*
* 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.
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include "py/compile.h"
#include "py/runtime.h"
#include "py/repl.h"
#include "py/gc.h"
#include "py/gc_long_lived.h"
#include "py/frozenmod.h"
#include "py/mphal.h"
#if MICROPY_HW_ENABLE_USB
#include "irq.h"
#include "usb.h"
#endif
#include "lib/mp-readline/readline.h"
#include "lib/utils/pyexec.h"
#include "genhdr/mpversion.h"
pyexec_mode_kind_t pyexec_mode_kind = PYEXEC_MODE_FRIENDLY_REPL;
int pyexec_system_exit = 0;
STATIC bool repl_display_debugging_info = 0;
#define EXEC_FLAG_PRINT_EOF (1)
#define EXEC_FLAG_ALLOW_DEBUGGING (2)
#define EXEC_FLAG_IS_REPL (4)
#define EXEC_FLAG_SOURCE_IS_RAW_CODE (8)
#define EXEC_FLAG_SOURCE_IS_VSTR (16)
#define EXEC_FLAG_SOURCE_IS_FILENAME (32)
// parses, compiles and executes the code in the lexer
// frees the lexer before returning
// EXEC_FLAG_PRINT_EOF prints 2 EOF chars: 1 after normal output, 1 after exception output
// EXEC_FLAG_ALLOW_DEBUGGING allows debugging info to be printed after executing the code
// EXEC_FLAG_IS_REPL is used for REPL inputs (flag passed on to mp_compile)
STATIC int parse_compile_execute(const void *source, mp_parse_input_kind_t input_kind, int exec_flags, pyexec_result_t *result) {
int ret = 0;
uint32_t start = 0;
// by default a SystemExit exception returns 0
pyexec_system_exit = 0;
nlr_buf_t nlr;
if (nlr_push(&nlr) == 0) {
mp_obj_t module_fun;
#if MICROPY_MODULE_FROZEN_MPY
if (exec_flags & EXEC_FLAG_SOURCE_IS_RAW_CODE) {
// source is a raw_code object, create the function
module_fun = mp_make_function_from_raw_code(source, MP_OBJ_NULL, MP_OBJ_NULL);
} else
#endif
{
#if MICROPY_ENABLE_COMPILER
mp_lexer_t *lex;
if (exec_flags & EXEC_FLAG_SOURCE_IS_VSTR) {
const vstr_t *vstr = source;
lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, vstr->buf, vstr->len, 0);
} else if (exec_flags & EXEC_FLAG_SOURCE_IS_FILENAME) {
lex = mp_lexer_new_from_file(source);
} else {
lex = (mp_lexer_t*)source;
}
// source is a lexer, parse and compile the script
qstr source_name = lex->source_name;
if (input_kind == MP_PARSE_FILE_INPUT) {
mp_store_global(MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name));
}
mp_parse_tree_t parse_tree = mp_parse(lex, input_kind);
module_fun = mp_compile(&parse_tree, source_name, MP_EMIT_OPT_NONE, exec_flags & EXEC_FLAG_IS_REPL);
// Clear the parse tree because it has a heap pointer we don't need anymore.
*((uint32_t volatile*) &parse_tree.chunk) = 0;
#else
mp_raise_msg(&mp_type_RuntimeError, translate("script compilation not supported"));
#endif
}
// If the code was loaded from a file its likely to be running for a while so we'll long
// live it and collect any garbage before running.
if (input_kind == MP_PARSE_FILE_INPUT) {
module_fun = make_obj_long_lived(module_fun, 6);
gc_collect();
}
// execute code
mp_hal_set_interrupt_char(CHAR_CTRL_C); // allow ctrl-C to interrupt us
start = mp_hal_ticks_ms();
mp_call_function_0(module_fun);
mp_hal_set_interrupt_char(-1); // disable interrupt
nlr_pop();
ret = 0;
if (exec_flags & EXEC_FLAG_PRINT_EOF) {
mp_hal_stdout_tx_strn("\x04", 1);
}
} else {
// uncaught exception
// FIXME it could be that an interrupt happens just before we disable it here
mp_hal_set_interrupt_char(-1); // disable interrupt
// print EOF after normal output
if (exec_flags & EXEC_FLAG_PRINT_EOF) {
mp_hal_stdout_tx_strn("\x04", 1);
}
// check for SystemExit
if (mp_obj_is_subclass_fast(mp_obj_get_type((mp_obj_t)nlr.ret_val), &mp_type_SystemExit)) {
// at the moment, the value of SystemExit is unused
ret = pyexec_system_exit;
} else {
if ((mp_obj_t) nlr.ret_val != MP_OBJ_FROM_PTR(&MP_STATE_VM(mp_reload_exception))) {
mp_obj_print_exception(&mp_plat_print, (mp_obj_t)nlr.ret_val);
}
ret = PYEXEC_EXCEPTION;
}
}
if (result != NULL) {
result->return_code = ret;
if (ret != 0) {
mp_obj_t return_value = (mp_obj_t)nlr.ret_val;
result->exception_type = mp_obj_get_type(return_value);
result->exception_line = -1;
if (mp_obj_is_exception_instance(return_value)) {
size_t n, *values;
mp_obj_exception_get_traceback(return_value, &n, &values);
if (values != NULL) {
result->exception_line = values[n - 2];
}
}
}
}
// display debugging info if wanted
if ((exec_flags & EXEC_FLAG_ALLOW_DEBUGGING) && repl_display_debugging_info) {
mp_uint_t ticks = mp_hal_ticks_ms() - start; // TODO implement a function that does this properly
printf("took " UINT_FMT " ms\n", ticks);
// qstr info
{
size_t n_pool, n_qstr, n_str_data_bytes, n_total_bytes;
qstr_pool_info(&n_pool, &n_qstr, &n_str_data_bytes, &n_total_bytes);
printf("qstr:\n n_pool=" UINT_FMT "\n n_qstr=" UINT_FMT "\n "
"n_str_data_bytes=" UINT_FMT "\n n_total_bytes=" UINT_FMT "\n",
(unsigned)n_pool, (unsigned)n_qstr, (unsigned)n_str_data_bytes, (unsigned)n_total_bytes);
}
#if MICROPY_ENABLE_GC
// run collection and print GC info
gc_collect();
gc_dump_info();
#endif
}
if (exec_flags & EXEC_FLAG_PRINT_EOF) {
mp_hal_stdout_tx_strn("\x04", 1);
}
return ret;
}
#if MICROPY_ENABLE_COMPILER
#if MICROPY_REPL_EVENT_DRIVEN
typedef struct _repl_t {
// This structure originally also held current REPL line,
// but it was moved to MP_STATE_VM(repl_line) as containing
// root pointer. Still keep structure in case more state
// will be added later.
//vstr_t line;
bool cont_line;
} repl_t;
repl_t repl;
STATIC int pyexec_raw_repl_process_char(int c);
STATIC int pyexec_friendly_repl_process_char(int c);
void pyexec_event_repl_init(void) {
MP_STATE_VM(repl_line) = vstr_new(32);
repl.cont_line = false;
// no prompt before printing friendly REPL banner or entering raw REPL
readline_init(MP_STATE_VM(repl_line), "");
if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) {
pyexec_raw_repl_process_char(CHAR_CTRL_A);
} else {
pyexec_friendly_repl_process_char(CHAR_CTRL_B);
}
}
STATIC int pyexec_raw_repl_process_char(int c) {
if (c == CHAR_CTRL_A) {
// reset raw REPL
mp_hal_stdout_tx_str("raw REPL; CTRL-B to exit\r\n");
goto reset;
} else if (c == CHAR_CTRL_B) {
// change to friendly REPL
pyexec_mode_kind = PYEXEC_MODE_FRIENDLY_REPL;
vstr_reset(MP_STATE_VM(repl_line));
repl.cont_line = false;
pyexec_friendly_repl_process_char(CHAR_CTRL_B);
return 0;
} else if (c == CHAR_CTRL_C) {
// clear line
vstr_reset(MP_STATE_VM(repl_line));
return 0;
} else if (c == CHAR_CTRL_D) {
// input finished
} else {
// let through any other raw 8-bit value
vstr_add_byte(MP_STATE_VM(repl_line), c);
return 0;
}
// indicate reception of command
mp_hal_stdout_tx_str("OK");
if (MP_STATE_VM(repl_line)->len == 0) {
// exit for a soft reset
mp_hal_stdout_tx_str("\r\n");
vstr_clear(MP_STATE_VM(repl_line));
return PYEXEC_FORCED_EXIT;
}
int ret = parse_compile_execute(MP_STATE_VM(repl_line), MP_PARSE_FILE_INPUT, EXEC_FLAG_PRINT_EOF | EXEC_FLAG_SOURCE_IS_VSTR, NULL);
if (ret & PYEXEC_FORCED_EXIT) {
return ret;
}
reset:
vstr_reset(MP_STATE_VM(repl_line));
mp_hal_stdout_tx_str(">");
return 0;
}
STATIC int pyexec_friendly_repl_process_char(int c) {
int ret = readline_process_char(c);
if (!repl.cont_line) {
if (ret == CHAR_CTRL_A) {
// change to raw REPL
pyexec_mode_kind = PYEXEC_MODE_RAW_REPL;
mp_hal_stdout_tx_str("\r\n");
pyexec_raw_repl_process_char(CHAR_CTRL_A);
return 0;
} else if (ret == CHAR_CTRL_B) {
// reset friendly REPL
mp_hal_stdout_tx_str("\r\n");
mp_hal_stdout_tx_str(MICROPY_FULL_VERSION_INFO);
mp_hal_stdout_tx_str("\r\n");
// mp_hal_stdout_tx_str("Type \"help()\" for more information.\r\n");
goto input_restart;
} else if (ret == CHAR_CTRL_C) {
// break
mp_hal_stdout_tx_str("\r\n");
goto input_restart;
} else if (ret == CHAR_CTRL_D) {
// exit for a soft reset
mp_hal_stdout_tx_str("\r\n");
vstr_clear(MP_STATE_VM(repl_line));
return PYEXEC_FORCED_EXIT;
}
if (ret < 0) {
return 0;
}
if (!mp_repl_continue_with_input(vstr_null_terminated_str(MP_STATE_VM(repl_line)))) {
goto exec;
}
vstr_add_byte(MP_STATE_VM(repl_line), '\n');
repl.cont_line = true;
readline_note_newline("... ");
return 0;
} else {
if (ret == CHAR_CTRL_C) {
// cancel everything
mp_hal_stdout_tx_str("\r\n");
repl.cont_line = false;
goto input_restart;
} else if (ret == CHAR_CTRL_D) {
// stop entering compound statement
goto exec;
}
if (ret < 0) {
return 0;
}
if (mp_repl_continue_with_input(vstr_null_terminated_str(MP_STATE_VM(repl_line)))) {
vstr_add_byte(MP_STATE_VM(repl_line), '\n');
readline_note_newline("... ");
return 0;
}
exec: ;
int ret = parse_compile_execute(MP_STATE_VM(repl_line), MP_PARSE_SINGLE_INPUT, EXEC_FLAG_ALLOW_DEBUGGING | EXEC_FLAG_IS_REPL | EXEC_FLAG_SOURCE_IS_VSTR, NULL);
if (ret & PYEXEC_FORCED_EXIT) {
return ret;
}
input_restart:
vstr_reset(MP_STATE_VM(repl_line));
repl.cont_line = false;
readline_init(MP_STATE_VM(repl_line), ">>> ");
return 0;
}
}
uint8_t pyexec_repl_active;
int pyexec_event_repl_process_char(int c) {
pyexec_repl_active = 1;
int res;
if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) {
res = pyexec_raw_repl_process_char(c);
} else {
res = pyexec_friendly_repl_process_char(c);
}
pyexec_repl_active = 0;
return res;
}
#else // MICROPY_REPL_EVENT_DRIVEN
int pyexec_raw_repl(void) {
vstr_t line;
vstr_init(&line, 32);
raw_repl_reset:
mp_hal_stdout_tx_str("raw REPL; CTRL-B to exit\r\n");
for (;;) {
vstr_reset(&line);
mp_hal_stdout_tx_str(">");
for (;;) {
int c = mp_hal_stdin_rx_chr();
if (c == CHAR_CTRL_A) {
// reset raw REPL
goto raw_repl_reset;
} else if (c == CHAR_CTRL_B) {
// change to friendly REPL
mp_hal_stdout_tx_str("\r\n");
vstr_clear(&line);
pyexec_mode_kind = PYEXEC_MODE_FRIENDLY_REPL;
return 0;
} else if (c == CHAR_CTRL_C) {
// clear line
vstr_reset(&line);
} else if (c == CHAR_CTRL_D) {
// input finished
break;
} else {
// let through any other raw 8-bit value
vstr_add_byte(&line, c);
}
}
// indicate reception of command
mp_hal_stdout_tx_str("OK");
if (line.len == 0) {
// exit for a soft reset
mp_hal_stdout_tx_str("\r\n");
vstr_clear(&line);
return PYEXEC_FORCED_EXIT;
}
int ret = parse_compile_execute(&line, MP_PARSE_FILE_INPUT, EXEC_FLAG_PRINT_EOF | EXEC_FLAG_SOURCE_IS_VSTR, NULL);
if (ret & PYEXEC_FORCED_EXIT) {
return ret;
}
}
}
int pyexec_friendly_repl(void) {
vstr_t line;
vstr_init(&line, 32);
#if defined(USE_HOST_MODE) && MICROPY_HW_HAS_LCD
// in host mode, we enable the LCD for the repl
mp_obj_t lcd_o = mp_call_function_0(mp_load_name(qstr_from_str("LCD")));
mp_call_function_1(mp_load_attr(lcd_o, qstr_from_str("light")), mp_const_true);
#endif
friendly_repl_reset:
mp_hal_stdout_tx_str("\r\n");
mp_hal_stdout_tx_str(MICROPY_FULL_VERSION_INFO);
mp_hal_stdout_tx_str("\r\n");
// mp_hal_stdout_tx_str("Type \"help()\" for more information.\r\n");
// to test ctrl-C
/*
{
uint32_t x[4] = {0x424242, 0xdeaddead, 0x242424, 0xdeadbeef};
for (;;) {
nlr_buf_t nlr;
printf("pyexec_repl: %p\n", x);
mp_hal_set_interrupt_char(CHAR_CTRL_C);
if (nlr_push(&nlr) == 0) {
for (;;) {
}
} else {
printf("break\n");
}
}
}
*/
for (;;) {
input_restart:
#if MICROPY_HW_ENABLE_USB
if (usb_vcp_is_enabled()) {
// If the user gets to here and interrupts are disabled then
// they'll never see the prompt, traceback etc. The USB REPL needs
// interrupts to be enabled or no transfers occur. So we try to
// do the user a favor and reenable interrupts.
if (query_irq() == IRQ_STATE_DISABLED) {
enable_irq(IRQ_STATE_ENABLED);
mp_hal_stdout_tx_str("PYB: enabling IRQs\r\n");
}
}
#endif
vstr_reset(&line);
int ret = readline(&line, ">>> ");
mp_parse_input_kind_t parse_input_kind = MP_PARSE_SINGLE_INPUT;
if (ret == CHAR_CTRL_A) {
// change to raw REPL
mp_hal_stdout_tx_str("\r\n");
vstr_clear(&line);
pyexec_mode_kind = PYEXEC_MODE_RAW_REPL;
return 0;
} else if (ret == CHAR_CTRL_B) {
// reset friendly REPL
mp_hal_stdout_tx_str("\r\n");
goto friendly_repl_reset;
} else if (ret == CHAR_CTRL_C) {
// break
mp_hal_stdout_tx_str("\r\n");
continue;
} else if (ret == CHAR_CTRL_D) {
// exit for a soft reset
mp_hal_stdout_tx_str("\r\n");
vstr_clear(&line);
return PYEXEC_FORCED_EXIT;
} else if (ret == CHAR_CTRL_E) {
// paste mode
mp_hal_stdout_tx_str("\r\npaste mode; Ctrl-C to cancel, Ctrl-D to finish\r\n=== ");
vstr_reset(&line);
for (;;) {
char c = mp_hal_stdin_rx_chr();
if (c == CHAR_CTRL_C) {
// cancel everything
mp_hal_stdout_tx_str("\r\n");
goto input_restart;
} else if (c == CHAR_CTRL_D) {
// end of input
mp_hal_stdout_tx_str("\r\n");
break;
} else {
// add char to buffer and echo
vstr_add_byte(&line, c);
if (c == '\r') {
mp_hal_stdout_tx_str("\r\n=== ");
} else {
mp_hal_stdout_tx_strn(&c, 1);
}
}
}
parse_input_kind = MP_PARSE_FILE_INPUT;
} else if (vstr_len(&line) == 0) {
continue;
} else {
// got a line with non-zero length, see if it needs continuing
while (mp_repl_continue_with_input(vstr_null_terminated_str(&line))) {
vstr_add_byte(&line, '\n');
ret = readline(&line, "... ");
if (ret == CHAR_CTRL_C) {
// cancel everything
mp_hal_stdout_tx_str("\r\n");
goto input_restart;
} else if (ret == CHAR_CTRL_D) {
// stop entering compound statement
break;
}
}
}
ret = parse_compile_execute(&line, parse_input_kind, EXEC_FLAG_ALLOW_DEBUGGING | EXEC_FLAG_IS_REPL | EXEC_FLAG_SOURCE_IS_VSTR, NULL);
if (ret & PYEXEC_FORCED_EXIT) {
return ret;
}
}
}
#endif // MICROPY_REPL_EVENT_DRIVEN
#endif // MICROPY_ENABLE_COMPILER
int pyexec_file(const char *filename, pyexec_result_t *result) {
return parse_compile_execute(filename, MP_PARSE_FILE_INPUT, EXEC_FLAG_SOURCE_IS_FILENAME, result);
}
#if MICROPY_MODULE_FROZEN
int pyexec_frozen_module(const char *name) {
void *frozen_data;
int frozen_type = mp_find_frozen_module(name, strlen(name), &frozen_data);
switch (frozen_type) {
#if MICROPY_MODULE_FROZEN_STR
case MP_FROZEN_STR:
return parse_compile_execute(frozen_data, MP_PARSE_FILE_INPUT, 0, NULL);
#endif
#if MICROPY_MODULE_FROZEN_MPY
case MP_FROZEN_MPY:
return parse_compile_execute(frozen_data, MP_PARSE_FILE_INPUT, EXEC_FLAG_SOURCE_IS_RAW_CODE, NULL);
#endif
default:
printf("could not find module '%s'\n", name);
return false;
}
}
#endif
mp_obj_t pyb_set_repl_info(mp_obj_t o_value) {
repl_display_debugging_info = mp_obj_get_int(o_value);
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_1(pyb_set_repl_info_obj, pyb_set_repl_info);
|
172253.c | /*-
* Copyright (c) 2008, Kohsuke Ohtani
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the author nor the names of any co-contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* 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.
*/
/*
* diag.c - diagnostic message support
*/
#include <stdarg.h>
#include <stdio.h>
#include "pl011.h"
#include "kernel.h"
#include "bootinfo.h"
#include "busio.h"
#include "vm.h"
#define UART_BASE PL011_BASE
#define UART_PHYSICAL_BASE PL011_PHYSICAL_BASE
// Flag register
#define FR_RXFE 0x10 // Receive FIFO empty.
#define FR_TXFF 0x20 // Transmit FIFO full.
static void serial_putc(int c)
{
while (bus_read_32(UART_FR) & FR_TXFF)
continue;
bus_write_32(UART_DR, (uint32_t)c);
}
void diag_puts(char *buf)
{
while (*buf) {
if (*buf == '\n')
serial_putc('\r');
serial_putc(*buf++);
}
}
static char buffer[CONFIG_DIAG_MSGSZ];
int diag_printf(const char *__restrict fmt, ...)
{
va_list ap;
int s = splhigh();
va_start(ap, fmt);
int c = vsnprintf(buffer, CONFIG_DIAG_MSGSZ, fmt, ap);
diag_puts(buffer);
va_end(ap);
splx(s);
return c;
}
void diag_init(void)
{
// Map the UART physical address to its address in the kernel virtual space.
vm_premap(UART_PHYSICAL_BASE, UART_BASE);
}
|
473986.c | #include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/wait.h>
void espera_hijo(){
wait(0);
printf("Hijo esperado...\n");
signal(SIGCHLD, espera_hijo);
}
int main(int argc, char *argv[]){
pid_t pid = fork();
signal(SIGCHLD, espera_hijo);
int v = 10;
if(pid == 0){
// Codigo del hijo
v = 5;
//while(1);
exit(0);
} else if (pid > 0){
// Codigo del padre
//while(1);
wait(NULL);
} else {
perror("fork");
return -1;
}
printf("Terminado\n");
pause();
return 0;
}
|
889457.c | #include "_string.h"
u8 *_strrchr(u8 const *restrict const source, u32 character) {
(void)source;
(void)character;
return NULL;
}
|
213724.c | /*
* QEMU VGA Emulator.
*
* Copyright (c) 2003 Fabrice Bellard
*
* 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.
*/
#include "qemu/osdep.h"
#include "qemu/units.h"
#include "qapi/error.h"
#include "hw/hw.h"
#include "hw/display/vga.h"
#include "hw/pci/pci.h"
#include "vga_int.h"
#include "vga_regs.h"
#include "ui/pixel_ops.h"
#include "qemu/timer.h"
#include "hw/xen/xen.h"
#include "trace.h"
//#define DEBUG_VGA_MEM
//#define DEBUG_VGA_REG
/* 16 state changes per vertical frame @60 Hz */
#define VGA_TEXT_CURSOR_PERIOD_MS (1000 * 2 * 16 / 60)
/*
* Video Graphics Array (VGA)
*
* Chipset docs for original IBM VGA:
* http://www.mcamafia.de/pdf/ibm_vgaxga_trm2.pdf
*
* FreeVGA site:
* http://www.osdever.net/FreeVGA/home.htm
*
* Standard VGA features and Bochs VBE extensions are implemented.
*/
/* force some bits to zero */
const uint8_t sr_mask[8] = {
0x03,
0x3d,
0x0f,
0x3f,
0x0e,
0x00,
0x00,
0xff,
};
const uint8_t gr_mask[16] = {
0x0f, /* 0x00 */
0x0f, /* 0x01 */
0x0f, /* 0x02 */
0x1f, /* 0x03 */
0x03, /* 0x04 */
0x7b, /* 0x05 */
0x0f, /* 0x06 */
0x0f, /* 0x07 */
0xff, /* 0x08 */
0x00, /* 0x09 */
0x00, /* 0x0a */
0x00, /* 0x0b */
0x00, /* 0x0c */
0x00, /* 0x0d */
0x00, /* 0x0e */
0x00, /* 0x0f */
};
#define cbswap_32(__x) \
((uint32_t)( \
(((uint32_t)(__x) & (uint32_t)0x000000ffUL) << 24) | \
(((uint32_t)(__x) & (uint32_t)0x0000ff00UL) << 8) | \
(((uint32_t)(__x) & (uint32_t)0x00ff0000UL) >> 8) | \
(((uint32_t)(__x) & (uint32_t)0xff000000UL) >> 24) ))
#ifdef HOST_WORDS_BIGENDIAN
#define PAT(x) cbswap_32(x)
#else
#define PAT(x) (x)
#endif
#ifdef HOST_WORDS_BIGENDIAN
#define BIG 1
#else
#define BIG 0
#endif
#ifdef HOST_WORDS_BIGENDIAN
#define GET_PLANE(data, p) (((data) >> (24 - (p) * 8)) & 0xff)
#else
#define GET_PLANE(data, p) (((data) >> ((p) * 8)) & 0xff)
#endif
static const uint32_t mask16[16] = {
PAT(0x00000000),
PAT(0x000000ff),
PAT(0x0000ff00),
PAT(0x0000ffff),
PAT(0x00ff0000),
PAT(0x00ff00ff),
PAT(0x00ffff00),
PAT(0x00ffffff),
PAT(0xff000000),
PAT(0xff0000ff),
PAT(0xff00ff00),
PAT(0xff00ffff),
PAT(0xffff0000),
PAT(0xffff00ff),
PAT(0xffffff00),
PAT(0xffffffff),
};
#undef PAT
#ifdef HOST_WORDS_BIGENDIAN
#define PAT(x) (x)
#else
#define PAT(x) cbswap_32(x)
#endif
static uint32_t expand4[256];
static uint16_t expand2[256];
static uint8_t expand4to8[16];
static void vbe_update_vgaregs(VGACommonState *s);
static inline bool vbe_enabled(VGACommonState *s)
{
return s->vbe_regs[VBE_DISPI_INDEX_ENABLE] & VBE_DISPI_ENABLED;
}
static inline uint8_t sr(VGACommonState *s, int idx)
{
return vbe_enabled(s) ? s->sr_vbe[idx] : s->sr[idx];
}
static void vga_update_memory_access(VGACommonState *s)
{
hwaddr base, offset, size;
if (s->legacy_address_space == NULL) {
return;
}
if (s->has_chain4_alias) {
memory_region_del_subregion(s->legacy_address_space, &s->chain4_alias);
object_unparent(OBJECT(&s->chain4_alias));
s->has_chain4_alias = false;
s->plane_updated = 0xf;
}
if ((sr(s, VGA_SEQ_PLANE_WRITE) & VGA_SR02_ALL_PLANES) ==
VGA_SR02_ALL_PLANES && sr(s, VGA_SEQ_MEMORY_MODE) & VGA_SR04_CHN_4M) {
offset = 0;
switch ((s->gr[VGA_GFX_MISC] >> 2) & 3) {
case 0:
base = 0xa0000;
size = 0x20000;
break;
case 1:
base = 0xa0000;
size = 0x10000;
offset = s->bank_offset;
break;
case 2:
base = 0xb0000;
size = 0x8000;
break;
case 3:
default:
base = 0xb8000;
size = 0x8000;
break;
}
assert(offset + size <= s->vram_size);
memory_region_init_alias(&s->chain4_alias, memory_region_owner(&s->vram),
"vga.chain4", &s->vram, offset, size);
memory_region_add_subregion_overlap(s->legacy_address_space, base,
&s->chain4_alias, 2);
s->has_chain4_alias = true;
}
}
static void vga_dumb_update_retrace_info(VGACommonState *s)
{
(void) s;
}
static void vga_precise_update_retrace_info(VGACommonState *s)
{
int htotal_chars;
int hretr_start_char;
int hretr_skew_chars;
int hretr_end_char;
int vtotal_lines;
int vretr_start_line;
int vretr_end_line;
int dots;
#if 0
int div2, sldiv2;
#endif
int clocking_mode;
int clock_sel;
const int clk_hz[] = {25175000, 28322000, 25175000, 25175000};
int64_t chars_per_sec;
struct vga_precise_retrace *r = &s->retrace_info.precise;
htotal_chars = s->cr[VGA_CRTC_H_TOTAL] + 5;
hretr_start_char = s->cr[VGA_CRTC_H_SYNC_START];
hretr_skew_chars = (s->cr[VGA_CRTC_H_SYNC_END] >> 5) & 3;
hretr_end_char = s->cr[VGA_CRTC_H_SYNC_END] & 0x1f;
vtotal_lines = (s->cr[VGA_CRTC_V_TOTAL] |
(((s->cr[VGA_CRTC_OVERFLOW] & 1) |
((s->cr[VGA_CRTC_OVERFLOW] >> 4) & 2)) << 8)) + 2;
vretr_start_line = s->cr[VGA_CRTC_V_SYNC_START] |
((((s->cr[VGA_CRTC_OVERFLOW] >> 2) & 1) |
((s->cr[VGA_CRTC_OVERFLOW] >> 6) & 2)) << 8);
vretr_end_line = s->cr[VGA_CRTC_V_SYNC_END] & 0xf;
clocking_mode = (sr(s, VGA_SEQ_CLOCK_MODE) >> 3) & 1;
clock_sel = (s->msr >> 2) & 3;
dots = (s->msr & 1) ? 8 : 9;
chars_per_sec = clk_hz[clock_sel] / dots;
htotal_chars <<= clocking_mode;
r->total_chars = vtotal_lines * htotal_chars;
if (r->freq) {
r->ticks_per_char = NANOSECONDS_PER_SECOND / (r->total_chars * r->freq);
} else {
r->ticks_per_char = NANOSECONDS_PER_SECOND / chars_per_sec;
}
r->vstart = vretr_start_line;
r->vend = r->vstart + vretr_end_line + 1;
r->hstart = hretr_start_char + hretr_skew_chars;
r->hend = r->hstart + hretr_end_char + 1;
r->htotal = htotal_chars;
#if 0
div2 = (s->cr[VGA_CRTC_MODE] >> 2) & 1;
sldiv2 = (s->cr[VGA_CRTC_MODE] >> 3) & 1;
printf (
"hz=%f\n"
"htotal = %d\n"
"hretr_start = %d\n"
"hretr_skew = %d\n"
"hretr_end = %d\n"
"vtotal = %d\n"
"vretr_start = %d\n"
"vretr_end = %d\n"
"div2 = %d sldiv2 = %d\n"
"clocking_mode = %d\n"
"clock_sel = %d %d\n"
"dots = %d\n"
"ticks/char = %" PRId64 "\n"
"\n",
(double) NANOSECONDS_PER_SECOND / (r->ticks_per_char * r->total_chars),
htotal_chars,
hretr_start_char,
hretr_skew_chars,
hretr_end_char,
vtotal_lines,
vretr_start_line,
vretr_end_line,
div2, sldiv2,
clocking_mode,
clock_sel,
clk_hz[clock_sel],
dots,
r->ticks_per_char
);
#endif
}
static uint8_t vga_precise_retrace(VGACommonState *s)
{
struct vga_precise_retrace *r = &s->retrace_info.precise;
uint8_t val = s->st01 & ~(ST01_V_RETRACE | ST01_DISP_ENABLE);
if (r->total_chars) {
int cur_line, cur_line_char, cur_char;
int64_t cur_tick;
cur_tick = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
cur_char = (cur_tick / r->ticks_per_char) % r->total_chars;
cur_line = cur_char / r->htotal;
if (cur_line >= r->vstart && cur_line <= r->vend) {
val |= ST01_V_RETRACE | ST01_DISP_ENABLE;
} else {
cur_line_char = cur_char % r->htotal;
if (cur_line_char >= r->hstart && cur_line_char <= r->hend) {
val |= ST01_DISP_ENABLE;
}
}
return val;
} else {
return s->st01 ^ (ST01_V_RETRACE | ST01_DISP_ENABLE);
}
}
static uint8_t vga_dumb_retrace(VGACommonState *s)
{
return s->st01 ^ (ST01_V_RETRACE | ST01_DISP_ENABLE);
}
int vga_ioport_invalid(VGACommonState *s, uint32_t addr)
{
if (s->msr & VGA_MIS_COLOR) {
/* Color */
return (addr >= 0x3b0 && addr <= 0x3bf);
} else {
/* Monochrome */
return (addr >= 0x3d0 && addr <= 0x3df);
}
}
uint32_t vga_ioport_read(void *opaque, uint32_t addr)
{
VGACommonState *s = opaque;
int val, index;
if (vga_ioport_invalid(s, addr)) {
val = 0xff;
} else {
switch(addr) {
case VGA_ATT_W:
if (s->ar_flip_flop == 0) {
val = s->ar_index;
} else {
val = 0;
}
break;
case VGA_ATT_R:
index = s->ar_index & 0x1f;
if (index < VGA_ATT_C) {
val = s->ar[index];
} else {
val = 0;
}
break;
case VGA_MIS_W:
val = s->st00;
break;
case VGA_SEQ_I:
val = s->sr_index;
break;
case VGA_SEQ_D:
val = s->sr[s->sr_index];
#ifdef DEBUG_VGA_REG
printf("vga: read SR%x = 0x%02x\n", s->sr_index, val);
#endif
break;
case VGA_PEL_IR:
val = s->dac_state;
break;
case VGA_PEL_IW:
val = s->dac_write_index;
break;
case VGA_PEL_D:
val = s->palette[s->dac_read_index * 3 + s->dac_sub_index];
if (++s->dac_sub_index == 3) {
s->dac_sub_index = 0;
s->dac_read_index++;
}
break;
case VGA_FTC_R:
val = s->fcr;
break;
case VGA_MIS_R:
val = s->msr;
break;
case VGA_GFX_I:
val = s->gr_index;
break;
case VGA_GFX_D:
val = s->gr[s->gr_index];
#ifdef DEBUG_VGA_REG
printf("vga: read GR%x = 0x%02x\n", s->gr_index, val);
#endif
break;
case VGA_CRT_IM:
case VGA_CRT_IC:
val = s->cr_index;
break;
case VGA_CRT_DM:
case VGA_CRT_DC:
val = s->cr[s->cr_index];
#ifdef DEBUG_VGA_REG
printf("vga: read CR%x = 0x%02x\n", s->cr_index, val);
#endif
break;
case VGA_IS1_RM:
case VGA_IS1_RC:
/* just toggle to fool polling */
val = s->st01 = s->retrace(s);
s->ar_flip_flop = 0;
break;
default:
val = 0x00;
break;
}
}
trace_vga_std_read_io(addr, val);
return val;
}
void vga_ioport_write(void *opaque, uint32_t addr, uint32_t val)
{
VGACommonState *s = opaque;
int index;
/* check port range access depending on color/monochrome mode */
if (vga_ioport_invalid(s, addr)) {
return;
}
trace_vga_std_write_io(addr, val);
switch(addr) {
case VGA_ATT_W:
if (s->ar_flip_flop == 0) {
val &= 0x3f;
s->ar_index = val;
} else {
index = s->ar_index & 0x1f;
switch(index) {
case VGA_ATC_PALETTE0 ... VGA_ATC_PALETTEF:
s->ar[index] = val & 0x3f;
break;
case VGA_ATC_MODE:
s->ar[index] = val & ~0x10;
break;
case VGA_ATC_OVERSCAN:
s->ar[index] = val;
break;
case VGA_ATC_PLANE_ENABLE:
s->ar[index] = val & ~0xc0;
break;
case VGA_ATC_PEL:
s->ar[index] = val & ~0xf0;
break;
case VGA_ATC_COLOR_PAGE:
s->ar[index] = val & ~0xf0;
break;
default:
break;
}
}
s->ar_flip_flop ^= 1;
break;
case VGA_MIS_W:
s->msr = val & ~0x10;
s->update_retrace_info(s);
break;
case VGA_SEQ_I:
s->sr_index = val & 7;
break;
case VGA_SEQ_D:
#ifdef DEBUG_VGA_REG
printf("vga: write SR%x = 0x%02x\n", s->sr_index, val);
#endif
s->sr[s->sr_index] = val & sr_mask[s->sr_index];
if (s->sr_index == VGA_SEQ_CLOCK_MODE) {
s->update_retrace_info(s);
}
vga_update_memory_access(s);
break;
case VGA_PEL_IR:
s->dac_read_index = val;
s->dac_sub_index = 0;
s->dac_state = 3;
break;
case VGA_PEL_IW:
s->dac_write_index = val;
s->dac_sub_index = 0;
s->dac_state = 0;
break;
case VGA_PEL_D:
s->dac_cache[s->dac_sub_index] = val;
if (++s->dac_sub_index == 3) {
memcpy(&s->palette[s->dac_write_index * 3], s->dac_cache, 3);
s->dac_sub_index = 0;
s->dac_write_index++;
}
break;
case VGA_GFX_I:
s->gr_index = val & 0x0f;
break;
case VGA_GFX_D:
#ifdef DEBUG_VGA_REG
printf("vga: write GR%x = 0x%02x\n", s->gr_index, val);
#endif
s->gr[s->gr_index] = val & gr_mask[s->gr_index];
vbe_update_vgaregs(s);
vga_update_memory_access(s);
break;
case VGA_CRT_IM:
case VGA_CRT_IC:
s->cr_index = val;
break;
case VGA_CRT_DM:
case VGA_CRT_DC:
#ifdef DEBUG_VGA_REG
printf("vga: write CR%x = 0x%02x\n", s->cr_index, val);
#endif
/* handle CR0-7 protection */
if ((s->cr[VGA_CRTC_V_SYNC_END] & VGA_CR11_LOCK_CR0_CR7) &&
s->cr_index <= VGA_CRTC_OVERFLOW) {
/* can always write bit 4 of CR7 */
if (s->cr_index == VGA_CRTC_OVERFLOW) {
s->cr[VGA_CRTC_OVERFLOW] = (s->cr[VGA_CRTC_OVERFLOW] & ~0x10) |
(val & 0x10);
vbe_update_vgaregs(s);
}
return;
}
s->cr[s->cr_index] = val;
vbe_update_vgaregs(s);
switch(s->cr_index) {
case VGA_CRTC_H_TOTAL:
case VGA_CRTC_H_SYNC_START:
case VGA_CRTC_H_SYNC_END:
case VGA_CRTC_V_TOTAL:
case VGA_CRTC_OVERFLOW:
case VGA_CRTC_V_SYNC_END:
case VGA_CRTC_MODE:
s->update_retrace_info(s);
break;
}
break;
case VGA_IS1_RM:
case VGA_IS1_RC:
s->fcr = val & 0x10;
break;
}
}
/*
* Sanity check vbe register writes.
*
* As we don't have a way to signal errors to the guest in the bochs
* dispi interface we'll go adjust the registers to the closest valid
* value.
*/
static void vbe_fixup_regs(VGACommonState *s)
{
uint16_t *r = s->vbe_regs;
uint32_t bits, linelength, maxy, offset;
if (!vbe_enabled(s)) {
/* vbe is turned off -- nothing to do */
return;
}
/* check depth */
switch (r[VBE_DISPI_INDEX_BPP]) {
case 4:
case 8:
case 16:
case 24:
case 32:
bits = r[VBE_DISPI_INDEX_BPP];
break;
case 15:
bits = 16;
break;
default:
bits = r[VBE_DISPI_INDEX_BPP] = 8;
break;
}
/* check width */
r[VBE_DISPI_INDEX_XRES] &= ~7u;
if (r[VBE_DISPI_INDEX_XRES] == 0) {
r[VBE_DISPI_INDEX_XRES] = 8;
}
if (r[VBE_DISPI_INDEX_XRES] > VBE_DISPI_MAX_XRES) {
r[VBE_DISPI_INDEX_XRES] = VBE_DISPI_MAX_XRES;
}
r[VBE_DISPI_INDEX_VIRT_WIDTH] &= ~7u;
if (r[VBE_DISPI_INDEX_VIRT_WIDTH] > VBE_DISPI_MAX_XRES) {
r[VBE_DISPI_INDEX_VIRT_WIDTH] = VBE_DISPI_MAX_XRES;
}
if (r[VBE_DISPI_INDEX_VIRT_WIDTH] < r[VBE_DISPI_INDEX_XRES]) {
r[VBE_DISPI_INDEX_VIRT_WIDTH] = r[VBE_DISPI_INDEX_XRES];
}
/* check height */
linelength = r[VBE_DISPI_INDEX_VIRT_WIDTH] * bits / 8;
maxy = s->vbe_size / linelength;
if (r[VBE_DISPI_INDEX_YRES] == 0) {
r[VBE_DISPI_INDEX_YRES] = 1;
}
if (r[VBE_DISPI_INDEX_YRES] > VBE_DISPI_MAX_YRES) {
r[VBE_DISPI_INDEX_YRES] = VBE_DISPI_MAX_YRES;
}
if (r[VBE_DISPI_INDEX_YRES] > maxy) {
r[VBE_DISPI_INDEX_YRES] = maxy;
}
/* check offset */
if (r[VBE_DISPI_INDEX_X_OFFSET] > VBE_DISPI_MAX_XRES) {
r[VBE_DISPI_INDEX_X_OFFSET] = VBE_DISPI_MAX_XRES;
}
if (r[VBE_DISPI_INDEX_Y_OFFSET] > VBE_DISPI_MAX_YRES) {
r[VBE_DISPI_INDEX_Y_OFFSET] = VBE_DISPI_MAX_YRES;
}
offset = r[VBE_DISPI_INDEX_X_OFFSET] * bits / 8;
offset += r[VBE_DISPI_INDEX_Y_OFFSET] * linelength;
if (offset + r[VBE_DISPI_INDEX_YRES] * linelength > s->vbe_size) {
r[VBE_DISPI_INDEX_Y_OFFSET] = 0;
offset = r[VBE_DISPI_INDEX_X_OFFSET] * bits / 8;
if (offset + r[VBE_DISPI_INDEX_YRES] * linelength > s->vbe_size) {
r[VBE_DISPI_INDEX_X_OFFSET] = 0;
offset = 0;
}
}
/* update vga state */
r[VBE_DISPI_INDEX_VIRT_HEIGHT] = maxy;
s->vbe_line_offset = linelength;
s->vbe_start_addr = offset / 4;
}
/* we initialize the VGA graphic mode */
static void vbe_update_vgaregs(VGACommonState *s)
{
int h, shift_control;
if (!vbe_enabled(s)) {
/* vbe is turned off -- nothing to do */
return;
}
/* graphic mode + memory map 1 */
s->gr[VGA_GFX_MISC] = (s->gr[VGA_GFX_MISC] & ~0x0c) | 0x04 |
VGA_GR06_GRAPHICS_MODE;
s->cr[VGA_CRTC_MODE] |= 3; /* no CGA modes */
s->cr[VGA_CRTC_OFFSET] = s->vbe_line_offset >> 3;
/* width */
s->cr[VGA_CRTC_H_DISP] =
(s->vbe_regs[VBE_DISPI_INDEX_XRES] >> 3) - 1;
/* height (only meaningful if < 1024) */
h = s->vbe_regs[VBE_DISPI_INDEX_YRES] - 1;
s->cr[VGA_CRTC_V_DISP_END] = h;
s->cr[VGA_CRTC_OVERFLOW] = (s->cr[VGA_CRTC_OVERFLOW] & ~0x42) |
((h >> 7) & 0x02) | ((h >> 3) & 0x40);
/* line compare to 1023 */
s->cr[VGA_CRTC_LINE_COMPARE] = 0xff;
s->cr[VGA_CRTC_OVERFLOW] |= 0x10;
s->cr[VGA_CRTC_MAX_SCAN] |= 0x40;
if (s->vbe_regs[VBE_DISPI_INDEX_BPP] == 4) {
shift_control = 0;
s->sr_vbe[VGA_SEQ_CLOCK_MODE] &= ~8; /* no double line */
} else {
shift_control = 2;
/* set chain 4 mode */
s->sr_vbe[VGA_SEQ_MEMORY_MODE] |= VGA_SR04_CHN_4M;
/* activate all planes */
s->sr_vbe[VGA_SEQ_PLANE_WRITE] |= VGA_SR02_ALL_PLANES;
}
s->gr[VGA_GFX_MODE] = (s->gr[VGA_GFX_MODE] & ~0x60) |
(shift_control << 5);
s->cr[VGA_CRTC_MAX_SCAN] &= ~0x9f; /* no double scan */
}
static uint32_t vbe_ioport_read_index(void *opaque, uint32_t addr)
{
VGACommonState *s = opaque;
return s->vbe_index;
}
uint32_t vbe_ioport_read_data(void *opaque, uint32_t addr)
{
VGACommonState *s = opaque;
uint32_t val;
if (s->vbe_index < VBE_DISPI_INDEX_NB) {
if (s->vbe_regs[VBE_DISPI_INDEX_ENABLE] & VBE_DISPI_GETCAPS) {
switch(s->vbe_index) {
/* XXX: do not hardcode ? */
case VBE_DISPI_INDEX_XRES:
val = VBE_DISPI_MAX_XRES;
break;
case VBE_DISPI_INDEX_YRES:
val = VBE_DISPI_MAX_YRES;
break;
case VBE_DISPI_INDEX_BPP:
val = VBE_DISPI_MAX_BPP;
break;
default:
val = s->vbe_regs[s->vbe_index];
break;
}
} else {
val = s->vbe_regs[s->vbe_index];
}
} else if (s->vbe_index == VBE_DISPI_INDEX_VIDEO_MEMORY_64K) {
val = s->vbe_size / (64 * KiB);
} else {
val = 0;
}
trace_vga_vbe_read(s->vbe_index, val);
return val;
}
void vbe_ioport_write_index(void *opaque, uint32_t addr, uint32_t val)
{
VGACommonState *s = opaque;
s->vbe_index = val;
}
void vbe_ioport_write_data(void *opaque, uint32_t addr, uint32_t val)
{
VGACommonState *s = opaque;
if (s->vbe_index <= VBE_DISPI_INDEX_NB) {
trace_vga_vbe_write(s->vbe_index, val);
switch(s->vbe_index) {
case VBE_DISPI_INDEX_ID:
if (val == VBE_DISPI_ID0 ||
val == VBE_DISPI_ID1 ||
val == VBE_DISPI_ID2 ||
val == VBE_DISPI_ID3 ||
val == VBE_DISPI_ID4) {
s->vbe_regs[s->vbe_index] = val;
}
break;
case VBE_DISPI_INDEX_XRES:
case VBE_DISPI_INDEX_YRES:
case VBE_DISPI_INDEX_BPP:
case VBE_DISPI_INDEX_VIRT_WIDTH:
case VBE_DISPI_INDEX_X_OFFSET:
case VBE_DISPI_INDEX_Y_OFFSET:
s->vbe_regs[s->vbe_index] = val;
vbe_fixup_regs(s);
vbe_update_vgaregs(s);
break;
case VBE_DISPI_INDEX_BANK:
val &= s->vbe_bank_mask;
s->vbe_regs[s->vbe_index] = val;
s->bank_offset = (val << 16);
vga_update_memory_access(s);
break;
case VBE_DISPI_INDEX_ENABLE:
if ((val & VBE_DISPI_ENABLED) &&
!(s->vbe_regs[VBE_DISPI_INDEX_ENABLE] & VBE_DISPI_ENABLED)) {
s->vbe_regs[VBE_DISPI_INDEX_VIRT_WIDTH] = 0;
s->vbe_regs[VBE_DISPI_INDEX_X_OFFSET] = 0;
s->vbe_regs[VBE_DISPI_INDEX_Y_OFFSET] = 0;
s->vbe_regs[VBE_DISPI_INDEX_ENABLE] |= VBE_DISPI_ENABLED;
vbe_fixup_regs(s);
vbe_update_vgaregs(s);
/* clear the screen */
if (!(val & VBE_DISPI_NOCLEARMEM)) {
memset(s->vram_ptr, 0,
s->vbe_regs[VBE_DISPI_INDEX_YRES] * s->vbe_line_offset);
}
} else {
s->bank_offset = 0;
}
s->dac_8bit = (val & VBE_DISPI_8BIT_DAC) > 0;
s->vbe_regs[s->vbe_index] = val;
vga_update_memory_access(s);
break;
default:
break;
}
}
}
/* called for accesses between 0xa0000 and 0xc0000 */
uint32_t vga_mem_readb(VGACommonState *s, hwaddr addr)
{
int memory_map_mode, plane;
uint32_t ret;
/* convert to VGA memory offset */
memory_map_mode = (s->gr[VGA_GFX_MISC] >> 2) & 3;
addr &= 0x1ffff;
switch(memory_map_mode) {
case 0:
break;
case 1:
if (addr >= 0x10000)
return 0xff;
addr += s->bank_offset;
break;
case 2:
addr -= 0x10000;
if (addr >= 0x8000)
return 0xff;
break;
default:
case 3:
addr -= 0x18000;
if (addr >= 0x8000)
return 0xff;
break;
}
if (sr(s, VGA_SEQ_MEMORY_MODE) & VGA_SR04_CHN_4M) {
/* chain 4 mode : simplest access */
assert(addr < s->vram_size);
ret = s->vram_ptr[addr];
} else if (s->gr[VGA_GFX_MODE] & 0x10) {
/* odd/even mode (aka text mode mapping) */
plane = (s->gr[VGA_GFX_PLANE_READ] & 2) | (addr & 1);
addr = ((addr & ~1) << 1) | plane;
if (addr >= s->vram_size) {
return 0xff;
}
ret = s->vram_ptr[addr];
} else {
/* standard VGA latched access */
if (addr * sizeof(uint32_t) >= s->vram_size) {
return 0xff;
}
s->latch = ((uint32_t *)s->vram_ptr)[addr];
if (!(s->gr[VGA_GFX_MODE] & 0x08)) {
/* read mode 0 */
plane = s->gr[VGA_GFX_PLANE_READ];
ret = GET_PLANE(s->latch, plane);
} else {
/* read mode 1 */
ret = (s->latch ^ mask16[s->gr[VGA_GFX_COMPARE_VALUE]]) &
mask16[s->gr[VGA_GFX_COMPARE_MASK]];
ret |= ret >> 16;
ret |= ret >> 8;
ret = (~ret) & 0xff;
}
}
return ret;
}
/* called for accesses between 0xa0000 and 0xc0000 */
void vga_mem_writeb(VGACommonState *s, hwaddr addr, uint32_t val)
{
int memory_map_mode, plane, write_mode, b, func_select, mask;
uint32_t write_mask, bit_mask, set_mask;
#ifdef DEBUG_VGA_MEM
printf("vga: [0x" TARGET_FMT_plx "] = 0x%02x\n", addr, val);
#endif
/* convert to VGA memory offset */
memory_map_mode = (s->gr[VGA_GFX_MISC] >> 2) & 3;
addr &= 0x1ffff;
switch(memory_map_mode) {
case 0:
break;
case 1:
if (addr >= 0x10000)
return;
addr += s->bank_offset;
break;
case 2:
addr -= 0x10000;
if (addr >= 0x8000)
return;
break;
default:
case 3:
addr -= 0x18000;
if (addr >= 0x8000)
return;
break;
}
if (sr(s, VGA_SEQ_MEMORY_MODE) & VGA_SR04_CHN_4M) {
/* chain 4 mode : simplest access */
plane = addr & 3;
mask = (1 << plane);
if (sr(s, VGA_SEQ_PLANE_WRITE) & mask) {
assert(addr < s->vram_size);
s->vram_ptr[addr] = val;
#ifdef DEBUG_VGA_MEM
printf("vga: chain4: [0x" TARGET_FMT_plx "]\n", addr);
#endif
s->plane_updated |= mask; /* only used to detect font change */
memory_region_set_dirty(&s->vram, addr, 1);
}
} else if (s->gr[VGA_GFX_MODE] & 0x10) {
/* odd/even mode (aka text mode mapping) */
plane = (s->gr[VGA_GFX_PLANE_READ] & 2) | (addr & 1);
mask = (1 << plane);
if (sr(s, VGA_SEQ_PLANE_WRITE) & mask) {
addr = ((addr & ~1) << 1) | plane;
if (addr >= s->vram_size) {
return;
}
s->vram_ptr[addr] = val;
#ifdef DEBUG_VGA_MEM
printf("vga: odd/even: [0x" TARGET_FMT_plx "]\n", addr);
#endif
s->plane_updated |= mask; /* only used to detect font change */
memory_region_set_dirty(&s->vram, addr, 1);
}
} else {
/* standard VGA latched access */
write_mode = s->gr[VGA_GFX_MODE] & 3;
switch(write_mode) {
default:
case 0:
/* rotate */
b = s->gr[VGA_GFX_DATA_ROTATE] & 7;
val = ((val >> b) | (val << (8 - b))) & 0xff;
val |= val << 8;
val |= val << 16;
/* apply set/reset mask */
set_mask = mask16[s->gr[VGA_GFX_SR_ENABLE]];
val = (val & ~set_mask) |
(mask16[s->gr[VGA_GFX_SR_VALUE]] & set_mask);
bit_mask = s->gr[VGA_GFX_BIT_MASK];
break;
case 1:
val = s->latch;
goto do_write;
case 2:
val = mask16[val & 0x0f];
bit_mask = s->gr[VGA_GFX_BIT_MASK];
break;
case 3:
/* rotate */
b = s->gr[VGA_GFX_DATA_ROTATE] & 7;
val = (val >> b) | (val << (8 - b));
bit_mask = s->gr[VGA_GFX_BIT_MASK] & val;
val = mask16[s->gr[VGA_GFX_SR_VALUE]];
break;
}
/* apply logical operation */
func_select = s->gr[VGA_GFX_DATA_ROTATE] >> 3;
switch(func_select) {
case 0:
default:
/* nothing to do */
break;
case 1:
/* and */
val &= s->latch;
break;
case 2:
/* or */
val |= s->latch;
break;
case 3:
/* xor */
val ^= s->latch;
break;
}
/* apply bit mask */
bit_mask |= bit_mask << 8;
bit_mask |= bit_mask << 16;
val = (val & bit_mask) | (s->latch & ~bit_mask);
do_write:
/* mask data according to sr[2] */
mask = sr(s, VGA_SEQ_PLANE_WRITE);
s->plane_updated |= mask; /* only used to detect font change */
write_mask = mask16[mask];
if (addr * sizeof(uint32_t) >= s->vram_size) {
return;
}
((uint32_t *)s->vram_ptr)[addr] =
(((uint32_t *)s->vram_ptr)[addr] & ~write_mask) |
(val & write_mask);
#ifdef DEBUG_VGA_MEM
printf("vga: latch: [0x" TARGET_FMT_plx "] mask=0x%08x val=0x%08x\n",
addr * 4, write_mask, val);
#endif
memory_region_set_dirty(&s->vram, addr << 2, sizeof(uint32_t));
}
}
typedef void vga_draw_line_func(VGACommonState *s1, uint8_t *d,
uint32_t srcaddr, int width);
#include "vga-helpers.h"
/* return true if the palette was modified */
static int update_palette16(VGACommonState *s)
{
int full_update, i;
uint32_t v, col, *palette;
full_update = 0;
palette = s->last_palette;
for(i = 0; i < 16; i++) {
v = s->ar[i];
if (s->ar[VGA_ATC_MODE] & 0x80) {
v = ((s->ar[VGA_ATC_COLOR_PAGE] & 0xf) << 4) | (v & 0xf);
} else {
v = ((s->ar[VGA_ATC_COLOR_PAGE] & 0xc) << 4) | (v & 0x3f);
}
v = v * 3;
col = rgb_to_pixel32(c6_to_8(s->palette[v]),
c6_to_8(s->palette[v + 1]),
c6_to_8(s->palette[v + 2]));
if (col != palette[i]) {
full_update = 1;
palette[i] = col;
}
}
return full_update;
}
/* return true if the palette was modified */
static int update_palette256(VGACommonState *s)
{
int full_update, i;
uint32_t v, col, *palette;
full_update = 0;
palette = s->last_palette;
v = 0;
for(i = 0; i < 256; i++) {
if (s->dac_8bit) {
col = rgb_to_pixel32(s->palette[v],
s->palette[v + 1],
s->palette[v + 2]);
} else {
col = rgb_to_pixel32(c6_to_8(s->palette[v]),
c6_to_8(s->palette[v + 1]),
c6_to_8(s->palette[v + 2]));
}
if (col != palette[i]) {
full_update = 1;
palette[i] = col;
}
v += 3;
}
return full_update;
}
static void vga_get_offsets(VGACommonState *s,
uint32_t *pline_offset,
uint32_t *pstart_addr,
uint32_t *pline_compare)
{
uint32_t start_addr, line_offset, line_compare;
if (vbe_enabled(s)) {
line_offset = s->vbe_line_offset;
start_addr = s->vbe_start_addr;
line_compare = 65535;
} else {
/* compute line_offset in bytes */
line_offset = s->cr[VGA_CRTC_OFFSET];
line_offset <<= 3;
/* starting address */
start_addr = s->cr[VGA_CRTC_START_LO] |
(s->cr[VGA_CRTC_START_HI] << 8);
/* line compare */
line_compare = s->cr[VGA_CRTC_LINE_COMPARE] |
((s->cr[VGA_CRTC_OVERFLOW] & 0x10) << 4) |
((s->cr[VGA_CRTC_MAX_SCAN] & 0x40) << 3);
}
*pline_offset = line_offset;
*pstart_addr = start_addr;
*pline_compare = line_compare;
}
/* update start_addr and line_offset. Return TRUE if modified */
static int update_basic_params(VGACommonState *s)
{
int full_update;
uint32_t start_addr, line_offset, line_compare;
full_update = 0;
s->get_offsets(s, &line_offset, &start_addr, &line_compare);
if (line_offset != s->line_offset ||
start_addr != s->start_addr ||
line_compare != s->line_compare) {
s->line_offset = line_offset;
s->start_addr = start_addr;
s->line_compare = line_compare;
full_update = 1;
}
return full_update;
}
static const uint8_t cursor_glyph[32 * 4] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
};
static void vga_get_text_resolution(VGACommonState *s, int *pwidth, int *pheight,
int *pcwidth, int *pcheight)
{
int width, cwidth, height, cheight;
/* total width & height */
cheight = (s->cr[VGA_CRTC_MAX_SCAN] & 0x1f) + 1;
cwidth = 8;
if (!(sr(s, VGA_SEQ_CLOCK_MODE) & VGA_SR01_CHAR_CLK_8DOTS)) {
cwidth = 9;
}
if (sr(s, VGA_SEQ_CLOCK_MODE) & 0x08) {
cwidth = 16; /* NOTE: no 18 pixel wide */
}
width = (s->cr[VGA_CRTC_H_DISP] + 1);
if (s->cr[VGA_CRTC_V_TOTAL] == 100) {
/* ugly hack for CGA 160x100x16 - explain me the logic */
height = 100;
} else {
height = s->cr[VGA_CRTC_V_DISP_END] |
((s->cr[VGA_CRTC_OVERFLOW] & 0x02) << 7) |
((s->cr[VGA_CRTC_OVERFLOW] & 0x40) << 3);
height = (height + 1) / cheight;
}
*pwidth = width;
*pheight = height;
*pcwidth = cwidth;
*pcheight = cheight;
}
/*
* Text mode update
* Missing:
* - double scan
* - double width
* - underline
* - flashing
*/
static void vga_draw_text(VGACommonState *s, int full_update)
{
DisplaySurface *surface = qemu_console_surface(s->con);
int cx, cy, cheight, cw, ch, cattr, height, width, ch_attr;
int cx_min, cx_max, linesize, x_incr, line, line1;
uint32_t offset, fgcol, bgcol, v, cursor_offset;
uint8_t *d1, *d, *src, *dest, *cursor_ptr;
const uint8_t *font_ptr, *font_base[2];
int dup9, line_offset;
uint32_t *palette;
uint32_t *ch_attr_ptr;
int64_t now = qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL);
/* compute font data address (in plane 2) */
v = sr(s, VGA_SEQ_CHARACTER_MAP);
offset = (((v >> 4) & 1) | ((v << 1) & 6)) * 8192 * 4 + 2;
if (offset != s->font_offsets[0]) {
s->font_offsets[0] = offset;
full_update = 1;
}
font_base[0] = s->vram_ptr + offset;
offset = (((v >> 5) & 1) | ((v >> 1) & 6)) * 8192 * 4 + 2;
font_base[1] = s->vram_ptr + offset;
if (offset != s->font_offsets[1]) {
s->font_offsets[1] = offset;
full_update = 1;
}
if (s->plane_updated & (1 << 2) || s->has_chain4_alias) {
/* if the plane 2 was modified since the last display, it
indicates the font may have been modified */
s->plane_updated = 0;
full_update = 1;
}
full_update |= update_basic_params(s);
line_offset = s->line_offset;
vga_get_text_resolution(s, &width, &height, &cw, &cheight);
if ((height * width) <= 1) {
/* better than nothing: exit if transient size is too small */
return;
}
if ((height * width) > CH_ATTR_SIZE) {
/* better than nothing: exit if transient size is too big */
return;
}
if (width != s->last_width || height != s->last_height ||
cw != s->last_cw || cheight != s->last_ch || s->last_depth) {
s->last_scr_width = width * cw;
s->last_scr_height = height * cheight;
qemu_console_resize(s->con, s->last_scr_width, s->last_scr_height);
surface = qemu_console_surface(s->con);
dpy_text_resize(s->con, width, height);
s->last_depth = 0;
s->last_width = width;
s->last_height = height;
s->last_ch = cheight;
s->last_cw = cw;
full_update = 1;
}
full_update |= update_palette16(s);
palette = s->last_palette;
x_incr = cw * surface_bytes_per_pixel(surface);
if (full_update) {
s->full_update_text = 1;
}
if (s->full_update_gfx) {
s->full_update_gfx = 0;
full_update |= 1;
}
cursor_offset = ((s->cr[VGA_CRTC_CURSOR_HI] << 8) |
s->cr[VGA_CRTC_CURSOR_LO]) - s->start_addr;
if (cursor_offset != s->cursor_offset ||
s->cr[VGA_CRTC_CURSOR_START] != s->cursor_start ||
s->cr[VGA_CRTC_CURSOR_END] != s->cursor_end) {
/* if the cursor position changed, we update the old and new
chars */
if (s->cursor_offset < CH_ATTR_SIZE)
s->last_ch_attr[s->cursor_offset] = -1;
if (cursor_offset < CH_ATTR_SIZE)
s->last_ch_attr[cursor_offset] = -1;
s->cursor_offset = cursor_offset;
s->cursor_start = s->cr[VGA_CRTC_CURSOR_START];
s->cursor_end = s->cr[VGA_CRTC_CURSOR_END];
}
cursor_ptr = s->vram_ptr + (s->start_addr + cursor_offset) * 4;
if (now >= s->cursor_blink_time) {
s->cursor_blink_time = now + VGA_TEXT_CURSOR_PERIOD_MS / 2;
s->cursor_visible_phase = !s->cursor_visible_phase;
}
dest = surface_data(surface);
linesize = surface_stride(surface);
ch_attr_ptr = s->last_ch_attr;
line = 0;
offset = s->start_addr * 4;
for(cy = 0; cy < height; cy++) {
d1 = dest;
src = s->vram_ptr + offset;
cx_min = width;
cx_max = -1;
for(cx = 0; cx < width; cx++) {
if (src + sizeof(uint16_t) > s->vram_ptr + s->vram_size) {
break;
}
ch_attr = *(uint16_t *)src;
if (full_update || ch_attr != *ch_attr_ptr || src == cursor_ptr) {
if (cx < cx_min)
cx_min = cx;
if (cx > cx_max)
cx_max = cx;
*ch_attr_ptr = ch_attr;
#ifdef HOST_WORDS_BIGENDIAN
ch = ch_attr >> 8;
cattr = ch_attr & 0xff;
#else
ch = ch_attr & 0xff;
cattr = ch_attr >> 8;
#endif
font_ptr = font_base[(cattr >> 3) & 1];
font_ptr += 32 * 4 * ch;
bgcol = palette[cattr >> 4];
fgcol = palette[cattr & 0x0f];
if (cw == 16) {
vga_draw_glyph16(d1, linesize,
font_ptr, cheight, fgcol, bgcol);
} else if (cw != 9) {
vga_draw_glyph8(d1, linesize,
font_ptr, cheight, fgcol, bgcol);
} else {
dup9 = 0;
if (ch >= 0xb0 && ch <= 0xdf &&
(s->ar[VGA_ATC_MODE] & 0x04)) {
dup9 = 1;
}
vga_draw_glyph9(d1, linesize,
font_ptr, cheight, fgcol, bgcol, dup9);
}
if (src == cursor_ptr &&
!(s->cr[VGA_CRTC_CURSOR_START] & 0x20) &&
s->cursor_visible_phase) {
int line_start, line_last, h;
/* draw the cursor */
line_start = s->cr[VGA_CRTC_CURSOR_START] & 0x1f;
line_last = s->cr[VGA_CRTC_CURSOR_END] & 0x1f;
/* XXX: check that */
if (line_last > cheight - 1)
line_last = cheight - 1;
if (line_last >= line_start && line_start < cheight) {
h = line_last - line_start + 1;
d = d1 + linesize * line_start;
if (cw == 16) {
vga_draw_glyph16(d, linesize,
cursor_glyph, h, fgcol, bgcol);
} else if (cw != 9) {
vga_draw_glyph8(d, linesize,
cursor_glyph, h, fgcol, bgcol);
} else {
vga_draw_glyph9(d, linesize,
cursor_glyph, h, fgcol, bgcol, 1);
}
}
}
}
d1 += x_incr;
src += 4;
ch_attr_ptr++;
}
if (cx_max != -1) {
dpy_gfx_update(s->con, cx_min * cw, cy * cheight,
(cx_max - cx_min + 1) * cw, cheight);
}
dest += linesize * cheight;
line1 = line + cheight;
offset += line_offset;
if (line < s->line_compare && line1 >= s->line_compare) {
offset = 0;
}
line = line1;
}
}
enum {
VGA_DRAW_LINE2,
VGA_DRAW_LINE2D2,
VGA_DRAW_LINE4,
VGA_DRAW_LINE4D2,
VGA_DRAW_LINE8D2,
VGA_DRAW_LINE8,
VGA_DRAW_LINE15_LE,
VGA_DRAW_LINE16_LE,
VGA_DRAW_LINE24_LE,
VGA_DRAW_LINE32_LE,
VGA_DRAW_LINE15_BE,
VGA_DRAW_LINE16_BE,
VGA_DRAW_LINE24_BE,
VGA_DRAW_LINE32_BE,
VGA_DRAW_LINE_NB,
};
static vga_draw_line_func * const vga_draw_line_table[VGA_DRAW_LINE_NB] = {
vga_draw_line2,
vga_draw_line2d2,
vga_draw_line4,
vga_draw_line4d2,
vga_draw_line8d2,
vga_draw_line8,
vga_draw_line15_le,
vga_draw_line16_le,
vga_draw_line24_le,
vga_draw_line32_le,
vga_draw_line15_be,
vga_draw_line16_be,
vga_draw_line24_be,
vga_draw_line32_be,
};
static int vga_get_bpp(VGACommonState *s)
{
int ret;
if (vbe_enabled(s)) {
ret = s->vbe_regs[VBE_DISPI_INDEX_BPP];
} else {
ret = 0;
}
return ret;
}
static void vga_get_resolution(VGACommonState *s, int *pwidth, int *pheight)
{
int width, height;
if (vbe_enabled(s)) {
width = s->vbe_regs[VBE_DISPI_INDEX_XRES];
height = s->vbe_regs[VBE_DISPI_INDEX_YRES];
} else {
width = (s->cr[VGA_CRTC_H_DISP] + 1) * 8;
height = s->cr[VGA_CRTC_V_DISP_END] |
((s->cr[VGA_CRTC_OVERFLOW] & 0x02) << 7) |
((s->cr[VGA_CRTC_OVERFLOW] & 0x40) << 3);
height = (height + 1);
}
*pwidth = width;
*pheight = height;
}
void vga_invalidate_scanlines(VGACommonState *s, int y1, int y2)
{
int y;
if (y1 >= VGA_MAX_HEIGHT)
return;
if (y2 >= VGA_MAX_HEIGHT)
y2 = VGA_MAX_HEIGHT;
for(y = y1; y < y2; y++) {
s->invalidated_y_table[y >> 5] |= 1 << (y & 0x1f);
}
}
static bool vga_scanline_invalidated(VGACommonState *s, int y)
{
if (y >= VGA_MAX_HEIGHT) {
return false;
}
return s->invalidated_y_table[y >> 5] & (1 << (y & 0x1f));
}
void vga_dirty_log_start(VGACommonState *s)
{
memory_region_set_log(&s->vram, true, DIRTY_MEMORY_VGA);
}
void vga_dirty_log_stop(VGACommonState *s)
{
memory_region_set_log(&s->vram, false, DIRTY_MEMORY_VGA);
}
/*
* graphic modes
*/
static void vga_draw_graphic(VGACommonState *s, int full_update)
{
DisplaySurface *surface = qemu_console_surface(s->con);
int y1, y, update, linesize, y_start, double_scan, mask, depth;
int width, height, shift_control, bwidth, bits;
ram_addr_t page0, page1, region_start, region_end;
DirtyBitmapSnapshot *snap = NULL;
int disp_width, multi_scan, multi_run;
uint8_t *d;
uint32_t v, addr1, addr;
vga_draw_line_func *vga_draw_line = NULL;
bool share_surface, force_shadow = false;
pixman_format_code_t format;
#ifdef HOST_WORDS_BIGENDIAN
bool byteswap = !s->big_endian_fb;
#else
bool byteswap = s->big_endian_fb;
#endif
full_update |= update_basic_params(s);
s->get_resolution(s, &width, &height);
disp_width = width;
depth = s->get_bpp(s);
region_start = (s->start_addr * 4);
region_end = region_start + (ram_addr_t)s->line_offset * height;
region_end += width * depth / 8; /* scanline length */
region_end -= s->line_offset;
if (region_end > s->vbe_size || depth == 0 || depth == 15) {
/*
* We land here on:
* - wraps around (can happen with cirrus vbe modes)
* - depth == 0 (256 color palette video mode)
* - depth == 15
*
* Take the safe and slow route:
* - create a dirty bitmap snapshot for all vga memory.
* - force shadowing (so all vga memory access goes
* through vga_read_*() helpers).
*
* Given this affects only vga features which are pretty much
* unused by modern guests there should be no performance
* impact.
*/
region_start = 0;
region_end = s->vbe_size;
force_shadow = true;
}
shift_control = (s->gr[VGA_GFX_MODE] >> 5) & 3;
double_scan = (s->cr[VGA_CRTC_MAX_SCAN] >> 7);
if (shift_control != 1) {
multi_scan = (((s->cr[VGA_CRTC_MAX_SCAN] & 0x1f) + 1) << double_scan)
- 1;
} else {
/* in CGA modes, multi_scan is ignored */
/* XXX: is it correct ? */
multi_scan = double_scan;
}
multi_run = multi_scan;
if (shift_control != s->shift_control ||
double_scan != s->double_scan) {
full_update = 1;
s->shift_control = shift_control;
s->double_scan = double_scan;
}
if (shift_control == 0) {
if (sr(s, VGA_SEQ_CLOCK_MODE) & 8) {
disp_width <<= 1;
}
} else if (shift_control == 1) {
if (sr(s, VGA_SEQ_CLOCK_MODE) & 8) {
disp_width <<= 1;
}
}
/*
* Check whether we can share the surface with the backend
* or whether we need a shadow surface. We share native
* endian surfaces for 15bpp and above and byteswapped
* surfaces for 24bpp and above.
*/
format = qemu_default_pixman_format(depth, !byteswap);
if (format) {
share_surface = dpy_gfx_check_format(s->con, format)
&& !s->force_shadow && !force_shadow;
} else {
share_surface = false;
}
if (s->line_offset != s->last_line_offset ||
disp_width != s->last_width ||
height != s->last_height ||
s->last_depth != depth ||
s->last_byteswap != byteswap ||
share_surface != is_buffer_shared(surface)) {
/* display parameters changed -> need new display surface */
s->last_scr_width = disp_width;
s->last_scr_height = height;
s->last_width = disp_width;
s->last_height = height;
s->last_line_offset = s->line_offset;
s->last_depth = depth;
s->last_byteswap = byteswap;
full_update = 1;
}
if (surface_data(surface) != s->vram_ptr + (s->start_addr * 4)
&& is_buffer_shared(surface)) {
/* base address changed (page flip) -> shared display surfaces
* must be updated with the new base address */
full_update = 1;
}
if (full_update) {
if (share_surface) {
surface = qemu_create_displaysurface_from(disp_width,
height, format, s->line_offset,
s->vram_ptr + (s->start_addr * 4));
dpy_gfx_replace_surface(s->con, surface);
} else {
qemu_console_resize(s->con, disp_width, height);
surface = qemu_console_surface(s->con);
}
}
if (shift_control == 0) {
full_update |= update_palette16(s);
if (sr(s, VGA_SEQ_CLOCK_MODE) & 8) {
v = VGA_DRAW_LINE4D2;
} else {
v = VGA_DRAW_LINE4;
}
bits = 4;
} else if (shift_control == 1) {
full_update |= update_palette16(s);
if (sr(s, VGA_SEQ_CLOCK_MODE) & 8) {
v = VGA_DRAW_LINE2D2;
} else {
v = VGA_DRAW_LINE2;
}
bits = 4;
} else {
switch(s->get_bpp(s)) {
default:
case 0:
full_update |= update_palette256(s);
v = VGA_DRAW_LINE8D2;
bits = 4;
break;
case 8:
full_update |= update_palette256(s);
v = VGA_DRAW_LINE8;
bits = 8;
break;
case 15:
v = s->big_endian_fb ? VGA_DRAW_LINE15_BE : VGA_DRAW_LINE15_LE;
bits = 16;
break;
case 16:
v = s->big_endian_fb ? VGA_DRAW_LINE16_BE : VGA_DRAW_LINE16_LE;
bits = 16;
break;
case 24:
v = s->big_endian_fb ? VGA_DRAW_LINE24_BE : VGA_DRAW_LINE24_LE;
bits = 24;
break;
case 32:
v = s->big_endian_fb ? VGA_DRAW_LINE32_BE : VGA_DRAW_LINE32_LE;
bits = 32;
break;
}
}
vga_draw_line = vga_draw_line_table[v];
if (!is_buffer_shared(surface) && s->cursor_invalidate) {
s->cursor_invalidate(s);
}
#if 0
printf("w=%d h=%d v=%d line_offset=%d cr[0x09]=0x%02x cr[0x17]=0x%02x linecmp=%d sr[0x01]=0x%02x\n",
width, height, v, line_offset, s->cr[9], s->cr[VGA_CRTC_MODE],
s->line_compare, sr(s, VGA_SEQ_CLOCK_MODE));
#endif
addr1 = (s->start_addr * 4);
bwidth = DIV_ROUND_UP(width * bits, 8);
y_start = -1;
d = surface_data(surface);
linesize = surface_stride(surface);
y1 = 0;
if (!full_update) {
if (s->line_compare < height) {
/* split screen mode */
region_start = 0;
}
snap = memory_region_snapshot_and_clear_dirty(&s->vram, region_start,
region_end - region_start,
DIRTY_MEMORY_VGA);
}
for(y = 0; y < height; y++) {
addr = addr1;
if (!(s->cr[VGA_CRTC_MODE] & 1)) {
int shift;
/* CGA compatibility handling */
shift = 14 + ((s->cr[VGA_CRTC_MODE] >> 6) & 1);
addr = (addr & ~(1 << shift)) | ((y1 & 1) << shift);
}
if (!(s->cr[VGA_CRTC_MODE] & 2)) {
addr = (addr & ~0x8000) | ((y1 & 2) << 14);
}
update = full_update;
page0 = addr & s->vbe_size_mask;
page1 = (addr + bwidth - 1) & s->vbe_size_mask;
if (full_update) {
update = 1;
} else if (page1 < page0) {
/* scanline wraps from end of video memory to the start */
assert(force_shadow);
update = memory_region_snapshot_get_dirty(&s->vram, snap,
page0, s->vbe_size - page0);
update |= memory_region_snapshot_get_dirty(&s->vram, snap,
0, page1);
} else {
update = memory_region_snapshot_get_dirty(&s->vram, snap,
page0, page1 - page0);
}
/* explicit invalidation for the hardware cursor (cirrus only) */
update |= vga_scanline_invalidated(s, y);
if (update) {
if (y_start < 0)
y_start = y;
if (!(is_buffer_shared(surface))) {
vga_draw_line(s, d, addr, width);
if (s->cursor_draw_line)
s->cursor_draw_line(s, d, y);
}
} else {
if (y_start >= 0) {
/* flush to display */
dpy_gfx_update(s->con, 0, y_start,
disp_width, y - y_start);
y_start = -1;
}
}
if (!multi_run) {
mask = (s->cr[VGA_CRTC_MODE] & 3) ^ 3;
if ((y1 & mask) == mask)
addr1 += s->line_offset;
y1++;
multi_run = multi_scan;
} else {
multi_run--;
}
/* line compare acts on the displayed lines */
if (y == s->line_compare)
addr1 = 0;
d += linesize;
}
if (y_start >= 0) {
/* flush to display */
dpy_gfx_update(s->con, 0, y_start,
disp_width, y - y_start);
}
g_free(snap);
memset(s->invalidated_y_table, 0, sizeof(s->invalidated_y_table));
}
static void vga_draw_blank(VGACommonState *s, int full_update)
{
DisplaySurface *surface = qemu_console_surface(s->con);
int i, w;
uint8_t *d;
if (!full_update)
return;
if (s->last_scr_width <= 0 || s->last_scr_height <= 0)
return;
w = s->last_scr_width * surface_bytes_per_pixel(surface);
d = surface_data(surface);
for(i = 0; i < s->last_scr_height; i++) {
memset(d, 0, w);
d += surface_stride(surface);
}
dpy_gfx_update_full(s->con);
}
#define GMODE_TEXT 0
#define GMODE_GRAPH 1
#define GMODE_BLANK 2
static void vga_update_display(void *opaque)
{
VGACommonState *s = opaque;
DisplaySurface *surface = qemu_console_surface(s->con);
int full_update, graphic_mode;
qemu_flush_coalesced_mmio_buffer();
if (surface_bits_per_pixel(surface) == 0) {
/* nothing to do */
} else {
full_update = 0;
if (!(s->ar_index & 0x20)) {
graphic_mode = GMODE_BLANK;
} else {
graphic_mode = s->gr[VGA_GFX_MISC] & VGA_GR06_GRAPHICS_MODE;
}
if (graphic_mode != s->graphic_mode) {
s->graphic_mode = graphic_mode;
s->cursor_blink_time = qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL);
full_update = 1;
}
switch(graphic_mode) {
case GMODE_TEXT:
vga_draw_text(s, full_update);
break;
case GMODE_GRAPH:
vga_draw_graphic(s, full_update);
break;
case GMODE_BLANK:
default:
vga_draw_blank(s, full_update);
break;
}
}
}
/* force a full display refresh */
static void vga_invalidate_display(void *opaque)
{
VGACommonState *s = opaque;
s->last_width = -1;
s->last_height = -1;
}
void vga_common_reset(VGACommonState *s)
{
s->sr_index = 0;
memset(s->sr, '\0', sizeof(s->sr));
memset(s->sr_vbe, '\0', sizeof(s->sr_vbe));
s->gr_index = 0;
memset(s->gr, '\0', sizeof(s->gr));
s->ar_index = 0;
memset(s->ar, '\0', sizeof(s->ar));
s->ar_flip_flop = 0;
s->cr_index = 0;
memset(s->cr, '\0', sizeof(s->cr));
s->msr = 0;
s->fcr = 0;
s->st00 = 0;
s->st01 = 0;
s->dac_state = 0;
s->dac_sub_index = 0;
s->dac_read_index = 0;
s->dac_write_index = 0;
memset(s->dac_cache, '\0', sizeof(s->dac_cache));
s->dac_8bit = 0;
memset(s->palette, '\0', sizeof(s->palette));
s->bank_offset = 0;
s->vbe_index = 0;
memset(s->vbe_regs, '\0', sizeof(s->vbe_regs));
s->vbe_regs[VBE_DISPI_INDEX_ID] = VBE_DISPI_ID5;
s->vbe_start_addr = 0;
s->vbe_line_offset = 0;
s->vbe_bank_mask = (s->vram_size >> 16) - 1;
memset(s->font_offsets, '\0', sizeof(s->font_offsets));
s->graphic_mode = -1; /* force full update */
s->shift_control = 0;
s->double_scan = 0;
s->line_offset = 0;
s->line_compare = 0;
s->start_addr = 0;
s->plane_updated = 0;
s->last_cw = 0;
s->last_ch = 0;
s->last_width = 0;
s->last_height = 0;
s->last_scr_width = 0;
s->last_scr_height = 0;
s->cursor_start = 0;
s->cursor_end = 0;
s->cursor_offset = 0;
s->big_endian_fb = s->default_endian_fb;
memset(s->invalidated_y_table, '\0', sizeof(s->invalidated_y_table));
memset(s->last_palette, '\0', sizeof(s->last_palette));
memset(s->last_ch_attr, '\0', sizeof(s->last_ch_attr));
switch (vga_retrace_method) {
case VGA_RETRACE_DUMB:
break;
case VGA_RETRACE_PRECISE:
memset(&s->retrace_info, 0, sizeof (s->retrace_info));
break;
}
vga_update_memory_access(s);
}
static void vga_reset(void *opaque)
{
VGACommonState *s = opaque;
vga_common_reset(s);
}
#define TEXTMODE_X(x) ((x) % width)
#define TEXTMODE_Y(x) ((x) / width)
#define VMEM2CHTYPE(v) ((v & 0xff0007ff) | \
((v & 0x00000800) << 10) | ((v & 0x00007000) >> 1))
/* relay text rendering to the display driver
* instead of doing a full vga_update_display() */
static void vga_update_text(void *opaque, console_ch_t *chardata)
{
VGACommonState *s = opaque;
int graphic_mode, i, cursor_offset, cursor_visible;
int cw, cheight, width, height, size, c_min, c_max;
uint32_t *src;
console_ch_t *dst, val;
char msg_buffer[80];
int full_update = 0;
qemu_flush_coalesced_mmio_buffer();
if (!(s->ar_index & 0x20)) {
graphic_mode = GMODE_BLANK;
} else {
graphic_mode = s->gr[VGA_GFX_MISC] & VGA_GR06_GRAPHICS_MODE;
}
if (graphic_mode != s->graphic_mode) {
s->graphic_mode = graphic_mode;
full_update = 1;
}
if (s->last_width == -1) {
s->last_width = 0;
full_update = 1;
}
switch (graphic_mode) {
case GMODE_TEXT:
/* TODO: update palette */
full_update |= update_basic_params(s);
/* total width & height */
cheight = (s->cr[VGA_CRTC_MAX_SCAN] & 0x1f) + 1;
cw = 8;
if (!(sr(s, VGA_SEQ_CLOCK_MODE) & VGA_SR01_CHAR_CLK_8DOTS)) {
cw = 9;
}
if (sr(s, VGA_SEQ_CLOCK_MODE) & 0x08) {
cw = 16; /* NOTE: no 18 pixel wide */
}
width = (s->cr[VGA_CRTC_H_DISP] + 1);
if (s->cr[VGA_CRTC_V_TOTAL] == 100) {
/* ugly hack for CGA 160x100x16 - explain me the logic */
height = 100;
} else {
height = s->cr[VGA_CRTC_V_DISP_END] |
((s->cr[VGA_CRTC_OVERFLOW] & 0x02) << 7) |
((s->cr[VGA_CRTC_OVERFLOW] & 0x40) << 3);
height = (height + 1) / cheight;
}
size = (height * width);
if (size > CH_ATTR_SIZE) {
if (!full_update)
return;
snprintf(msg_buffer, sizeof(msg_buffer), "%i x %i Text mode",
width, height);
break;
}
if (width != s->last_width || height != s->last_height ||
cw != s->last_cw || cheight != s->last_ch) {
s->last_scr_width = width * cw;
s->last_scr_height = height * cheight;
qemu_console_resize(s->con, s->last_scr_width, s->last_scr_height);
dpy_text_resize(s->con, width, height);
s->last_depth = 0;
s->last_width = width;
s->last_height = height;
s->last_ch = cheight;
s->last_cw = cw;
full_update = 1;
}
if (full_update) {
s->full_update_gfx = 1;
}
if (s->full_update_text) {
s->full_update_text = 0;
full_update |= 1;
}
/* Update "hardware" cursor */
cursor_offset = ((s->cr[VGA_CRTC_CURSOR_HI] << 8) |
s->cr[VGA_CRTC_CURSOR_LO]) - s->start_addr;
if (cursor_offset != s->cursor_offset ||
s->cr[VGA_CRTC_CURSOR_START] != s->cursor_start ||
s->cr[VGA_CRTC_CURSOR_END] != s->cursor_end || full_update) {
cursor_visible = !(s->cr[VGA_CRTC_CURSOR_START] & 0x20);
if (cursor_visible && cursor_offset < size && cursor_offset >= 0)
dpy_text_cursor(s->con,
TEXTMODE_X(cursor_offset),
TEXTMODE_Y(cursor_offset));
else
dpy_text_cursor(s->con, -1, -1);
s->cursor_offset = cursor_offset;
s->cursor_start = s->cr[VGA_CRTC_CURSOR_START];
s->cursor_end = s->cr[VGA_CRTC_CURSOR_END];
}
src = (uint32_t *) s->vram_ptr + s->start_addr;
dst = chardata;
if (full_update) {
for (i = 0; i < size; src ++, dst ++, i ++)
console_write_ch(dst, VMEM2CHTYPE(le32_to_cpu(*src)));
dpy_text_update(s->con, 0, 0, width, height);
} else {
c_max = 0;
for (i = 0; i < size; src ++, dst ++, i ++) {
console_write_ch(&val, VMEM2CHTYPE(le32_to_cpu(*src)));
if (*dst != val) {
*dst = val;
c_max = i;
break;
}
}
c_min = i;
for (; i < size; src ++, dst ++, i ++) {
console_write_ch(&val, VMEM2CHTYPE(le32_to_cpu(*src)));
if (*dst != val) {
*dst = val;
c_max = i;
}
}
if (c_min <= c_max) {
i = TEXTMODE_Y(c_min);
dpy_text_update(s->con, 0, i, width, TEXTMODE_Y(c_max) - i + 1);
}
}
return;
case GMODE_GRAPH:
if (!full_update)
return;
s->get_resolution(s, &width, &height);
snprintf(msg_buffer, sizeof(msg_buffer), "%i x %i Graphic mode",
width, height);
break;
case GMODE_BLANK:
default:
if (!full_update)
return;
snprintf(msg_buffer, sizeof(msg_buffer), "VGA Blank mode");
break;
}
/* Display a message */
s->last_width = 60;
s->last_height = height = 3;
dpy_text_cursor(s->con, -1, -1);
dpy_text_resize(s->con, s->last_width, height);
for (dst = chardata, i = 0; i < s->last_width * height; i ++)
console_write_ch(dst ++, ' ');
size = strlen(msg_buffer);
width = (s->last_width - size) / 2;
dst = chardata + s->last_width + width;
for (i = 0; i < size; i ++)
console_write_ch(dst ++, ATTR2CHTYPE(msg_buffer[i], QEMU_COLOR_BLUE,
QEMU_COLOR_BLACK, 1));
dpy_text_update(s->con, 0, 0, s->last_width, height);
}
static uint64_t vga_mem_read(void *opaque, hwaddr addr,
unsigned size)
{
VGACommonState *s = opaque;
return vga_mem_readb(s, addr);
}
static void vga_mem_write(void *opaque, hwaddr addr,
uint64_t data, unsigned size)
{
VGACommonState *s = opaque;
vga_mem_writeb(s, addr, data);
}
const MemoryRegionOps vga_mem_ops = {
.read = vga_mem_read,
.write = vga_mem_write,
.endianness = DEVICE_LITTLE_ENDIAN,
.impl = {
.min_access_size = 1,
.max_access_size = 1,
},
};
static int vga_common_post_load(void *opaque, int version_id)
{
VGACommonState *s = opaque;
/* force refresh */
s->graphic_mode = -1;
vbe_update_vgaregs(s);
vga_update_memory_access(s);
return 0;
}
static bool vga_endian_state_needed(void *opaque)
{
VGACommonState *s = opaque;
/*
* Only send the endian state if it's different from the
* default one, thus ensuring backward compatibility for
* migration of the common case
*/
return s->default_endian_fb != s->big_endian_fb;
}
static const VMStateDescription vmstate_vga_endian = {
.name = "vga.endian",
.version_id = 1,
.minimum_version_id = 1,
.needed = vga_endian_state_needed,
.fields = (VMStateField[]) {
VMSTATE_BOOL(big_endian_fb, VGACommonState),
VMSTATE_END_OF_LIST()
}
};
const VMStateDescription vmstate_vga_common = {
.name = "vga",
.version_id = 2,
.minimum_version_id = 2,
.post_load = vga_common_post_load,
.fields = (VMStateField[]) {
VMSTATE_UINT32(latch, VGACommonState),
VMSTATE_UINT8(sr_index, VGACommonState),
VMSTATE_PARTIAL_BUFFER(sr, VGACommonState, 8),
VMSTATE_UINT8(gr_index, VGACommonState),
VMSTATE_PARTIAL_BUFFER(gr, VGACommonState, 16),
VMSTATE_UINT8(ar_index, VGACommonState),
VMSTATE_BUFFER(ar, VGACommonState),
VMSTATE_INT32(ar_flip_flop, VGACommonState),
VMSTATE_UINT8(cr_index, VGACommonState),
VMSTATE_BUFFER(cr, VGACommonState),
VMSTATE_UINT8(msr, VGACommonState),
VMSTATE_UINT8(fcr, VGACommonState),
VMSTATE_UINT8(st00, VGACommonState),
VMSTATE_UINT8(st01, VGACommonState),
VMSTATE_UINT8(dac_state, VGACommonState),
VMSTATE_UINT8(dac_sub_index, VGACommonState),
VMSTATE_UINT8(dac_read_index, VGACommonState),
VMSTATE_UINT8(dac_write_index, VGACommonState),
VMSTATE_BUFFER(dac_cache, VGACommonState),
VMSTATE_BUFFER(palette, VGACommonState),
VMSTATE_INT32(bank_offset, VGACommonState),
VMSTATE_UINT8_EQUAL(is_vbe_vmstate, VGACommonState, NULL),
VMSTATE_UINT16(vbe_index, VGACommonState),
VMSTATE_UINT16_ARRAY(vbe_regs, VGACommonState, VBE_DISPI_INDEX_NB),
VMSTATE_UINT32(vbe_start_addr, VGACommonState),
VMSTATE_UINT32(vbe_line_offset, VGACommonState),
VMSTATE_UINT32(vbe_bank_mask, VGACommonState),
VMSTATE_END_OF_LIST()
},
.subsections = (const VMStateDescription*[]) {
&vmstate_vga_endian,
NULL
}
};
static const GraphicHwOps vga_ops = {
.invalidate = vga_invalidate_display,
.gfx_update = vga_update_display,
.text_update = vga_update_text,
};
static inline uint32_t uint_clamp(uint32_t val, uint32_t vmin, uint32_t vmax)
{
if (val < vmin) {
return vmin;
}
if (val > vmax) {
return vmax;
}
return val;
}
void vga_common_init(VGACommonState *s, Object *obj)
{
int i, j, v, b;
for(i = 0;i < 256; i++) {
v = 0;
for(j = 0; j < 8; j++) {
v |= ((i >> j) & 1) << (j * 4);
}
expand4[i] = v;
v = 0;
for(j = 0; j < 4; j++) {
v |= ((i >> (2 * j)) & 3) << (j * 4);
}
expand2[i] = v;
}
for(i = 0; i < 16; i++) {
v = 0;
for(j = 0; j < 4; j++) {
b = ((i >> j) & 1);
v |= b << (2 * j);
v |= b << (2 * j + 1);
}
expand4to8[i] = v;
}
s->vram_size_mb = uint_clamp(s->vram_size_mb, 1, 512);
s->vram_size_mb = pow2ceil(s->vram_size_mb);
s->vram_size = s->vram_size_mb * MiB;
if (!s->vbe_size) {
s->vbe_size = s->vram_size;
}
s->vbe_size_mask = s->vbe_size - 1;
s->is_vbe_vmstate = 1;
memory_region_init_ram_nomigrate(&s->vram, obj, "vga.vram", s->vram_size,
&error_fatal);
vmstate_register_ram(&s->vram, s->global_vmstate ? NULL : DEVICE(obj));
xen_register_framebuffer(&s->vram);
s->vram_ptr = memory_region_get_ram_ptr(&s->vram);
s->get_bpp = vga_get_bpp;
s->get_offsets = vga_get_offsets;
s->get_resolution = vga_get_resolution;
s->hw_ops = &vga_ops;
switch (vga_retrace_method) {
case VGA_RETRACE_DUMB:
s->retrace = vga_dumb_retrace;
s->update_retrace_info = vga_dumb_update_retrace_info;
break;
case VGA_RETRACE_PRECISE:
s->retrace = vga_precise_retrace;
s->update_retrace_info = vga_precise_update_retrace_info;
break;
}
/*
* Set default fb endian based on target, could probably be turned
* into a device attribute set by the machine/platform to remove
* all target endian dependencies from this file.
*/
#ifdef TARGET_WORDS_BIGENDIAN
s->default_endian_fb = true;
#else
s->default_endian_fb = false;
#endif
vga_dirty_log_start(s);
}
static const MemoryRegionPortio vga_portio_list[] = {
{ 0x04, 2, 1, .read = vga_ioport_read, .write = vga_ioport_write }, /* 3b4 */
{ 0x0a, 1, 1, .read = vga_ioport_read, .write = vga_ioport_write }, /* 3ba */
{ 0x10, 16, 1, .read = vga_ioport_read, .write = vga_ioport_write }, /* 3c0 */
{ 0x24, 2, 1, .read = vga_ioport_read, .write = vga_ioport_write }, /* 3d4 */
{ 0x2a, 1, 1, .read = vga_ioport_read, .write = vga_ioport_write }, /* 3da */
PORTIO_END_OF_LIST(),
};
static const MemoryRegionPortio vbe_portio_list[] = {
{ 0, 1, 2, .read = vbe_ioport_read_index, .write = vbe_ioport_write_index },
# ifdef TARGET_I386
{ 1, 1, 2, .read = vbe_ioport_read_data, .write = vbe_ioport_write_data },
# endif
{ 2, 1, 2, .read = vbe_ioport_read_data, .write = vbe_ioport_write_data },
PORTIO_END_OF_LIST(),
};
/* Used by both ISA and PCI */
MemoryRegion *vga_init_io(VGACommonState *s, Object *obj,
const MemoryRegionPortio **vga_ports,
const MemoryRegionPortio **vbe_ports)
{
MemoryRegion *vga_mem;
*vga_ports = vga_portio_list;
*vbe_ports = vbe_portio_list;
vga_mem = g_malloc(sizeof(*vga_mem));
memory_region_init_io(vga_mem, obj, &vga_mem_ops, s,
"vga-lowmem", 0x20000);
memory_region_set_flush_coalesced(vga_mem);
return vga_mem;
}
void vga_init(VGACommonState *s, Object *obj, MemoryRegion *address_space,
MemoryRegion *address_space_io, bool init_vga_ports)
{
MemoryRegion *vga_io_memory;
const MemoryRegionPortio *vga_ports, *vbe_ports;
qemu_register_reset(vga_reset, s);
s->bank_offset = 0;
s->legacy_address_space = address_space;
vga_io_memory = vga_init_io(s, obj, &vga_ports, &vbe_ports);
memory_region_add_subregion_overlap(address_space,
0x000a0000,
vga_io_memory,
1);
memory_region_set_coalescing(vga_io_memory);
if (init_vga_ports) {
portio_list_init(&s->vga_port_list, obj, vga_ports, s, "vga");
portio_list_set_flush_coalesced(&s->vga_port_list);
portio_list_add(&s->vga_port_list, address_space_io, 0x3b0);
}
if (vbe_ports) {
portio_list_init(&s->vbe_port_list, obj, vbe_ports, s, "vbe");
portio_list_add(&s->vbe_port_list, address_space_io, 0x1ce);
}
}
void vga_init_vbe(VGACommonState *s, Object *obj, MemoryRegion *system_memory)
{
/* With pc-0.12 and below we map both the PCI BAR and the fixed VBE region,
* so use an alias to avoid double-mapping the same region.
*/
memory_region_init_alias(&s->vram_vbe, obj, "vram.vbe",
&s->vram, 0, memory_region_size(&s->vram));
/* XXX: use optimized standard vga accesses */
memory_region_add_subregion(system_memory,
VBE_DISPI_LFB_PHYSICAL_ADDRESS,
&s->vram_vbe);
s->vbe_mapped = 1;
}
|
234062.c | /* Bosch BMI160 inertial measurement unit driver
*
* Copyright (c) 2016 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*
* Datasheet:
* http://ae-bst.resource.bosch.com/media/_tech/media/datasheets/BST-BMI160-DS000-07.pdf
*/
#include <init.h>
#include <sensor.h>
#include <misc/byteorder.h>
#include <kernel.h>
#include <misc/__assert.h>
#include <logging/log.h>
#include "bmi160.h"
#define LOG_LEVEL CONFIG_SENSOR_LOG_LEVEL
LOG_MODULE_REGISTER(BMI160);
struct bmi160_device_data bmi160_data;
static int bmi160_transceive(struct device *dev, u8_t reg,
bool write, void *data, size_t length)
{
struct bmi160_device_data *bmi160 = dev->driver_data;
const struct spi_buf buf[2] = {
{
.buf = ®,
.len = 1
},
{
.buf = data,
.len = length
}
};
const struct spi_buf_set tx = {
.buffers = buf,
.count = data ? 2 : 1
};
if (!write) {
const struct spi_buf_set rx = {
.buffers = buf,
.count = 2
};
return spi_transceive(bmi160->spi, &bmi160->spi_cfg, &tx, &rx);
}
return spi_write(bmi160->spi, &bmi160->spi_cfg, &tx);
}
int bmi160_read(struct device *dev, u8_t reg_addr, u8_t *data, u8_t len)
{
return bmi160_transceive(dev, reg_addr | BIT(7), false, data, len);
}
int bmi160_byte_read(struct device *dev, u8_t reg_addr, u8_t *byte)
{
return bmi160_transceive(dev, reg_addr | BIT(7), false, byte, 1);
}
static int bmi160_word_read(struct device *dev, u8_t reg_addr, u16_t *word)
{
if (bmi160_transceive(dev, reg_addr | BIT(7), false, word, 2) != 0) {
return -EIO;
}
*word = sys_le16_to_cpu(*word);
return 0;
}
int bmi160_byte_write(struct device *dev, u8_t reg_addr, u8_t byte)
{
return bmi160_transceive(dev, reg_addr & 0x7F, true, &byte, 1);
}
int bmi160_word_write(struct device *dev, u8_t reg_addr, u16_t word)
{
u8_t tx_word[2] = {
(u8_t)(word & 0xff),
(u8_t)(word >> 8)
};
return bmi160_transceive(dev, reg_addr & 0x7F, true, tx_word, 2);
}
int bmi160_reg_field_update(struct device *dev, u8_t reg_addr,
u8_t pos, u8_t mask, u8_t val)
{
u8_t old_val;
if (bmi160_byte_read(dev, reg_addr, &old_val) < 0) {
return -EIO;
}
return bmi160_byte_write(dev, reg_addr,
(old_val & ~mask) | ((val << pos) & mask));
}
static int bmi160_pmu_set(struct device *dev, union bmi160_pmu_status *pmu_sts)
{
struct {
u8_t cmd;
u16_t delay_us; /* values taken from page 82 */
} cmds[] = {
{BMI160_CMD_PMU_MAG | pmu_sts->mag, 350},
{BMI160_CMD_PMU_ACC | pmu_sts->acc, 3200},
{BMI160_CMD_PMU_GYR | pmu_sts->gyr, 55000}
};
size_t i;
for (i = 0; i < ARRAY_SIZE(cmds); i++) {
union bmi160_pmu_status sts;
bool pmu_set = false;
if (bmi160_byte_write(dev, BMI160_REG_CMD, cmds[i].cmd) < 0) {
return -EIO;
}
/*
* Cannot use a timer here since this is called from the
* init function and the timeouts were not initialized yet.
*/
k_busy_wait(cmds[i].delay_us);
/* make sure the PMU_STATUS was set, though */
do {
if (bmi160_byte_read(dev, BMI160_REG_PMU_STATUS,
&sts.raw) < 0) {
return -EIO;
}
if (i == 0) {
pmu_set = (pmu_sts->mag == sts.mag);
} else if (i == 1) {
pmu_set = (pmu_sts->acc == sts.acc);
} else {
pmu_set = (pmu_sts->gyr == sts.gyr);
}
} while (!pmu_set);
}
/* set the undersampling flag for accelerometer */
return bmi160_reg_field_update(dev, BMI160_REG_ACC_CONF,
BMI160_ACC_CONF_US, BMI160_ACC_CONF_US,
pmu_sts->acc != BMI160_PMU_NORMAL);
}
#if defined(CONFIG_BMI160_GYRO_ODR_RUNTIME) ||\
defined(CONFIG_BMI160_ACCEL_ODR_RUNTIME)
/*
* Output data rate map with allowed frequencies:
* freq = freq_int + freq_milli / 1000
*
* Since we don't need a finer frequency resolution than milliHz, use u16_t
* to save some flash.
*/
struct {
u16_t freq_int;
u16_t freq_milli; /* User should convert to uHz before setting the
* SENSOR_ATTR_SAMPLING_FREQUENCY attribute.
*/
} bmi160_odr_map[] = {
{0, 0 }, {0, 780}, {1, 562}, {3, 120}, {6, 250},
{12, 500}, {25, 0 }, {50, 0 }, {100, 0 }, {200, 0 },
{400, 0 }, {800, 0 }, {1600, 0 }, {3200, 0 },
};
static int bmi160_freq_to_odr_val(u16_t freq_int, u16_t freq_milli)
{
size_t i;
/* An ODR of 0 Hz is not allowed */
if (freq_int == 0 && freq_milli == 0) {
return -EINVAL;
}
for (i = 0; i < ARRAY_SIZE(bmi160_odr_map); i++) {
if (freq_int < bmi160_odr_map[i].freq_int ||
(freq_int == bmi160_odr_map[i].freq_int &&
freq_milli <= bmi160_odr_map[i].freq_milli)) {
return i;
}
}
return -EINVAL;
}
#endif
#if defined(CONFIG_BMI160_ACCEL_ODR_RUNTIME)
static int bmi160_acc_odr_set(struct device *dev, u16_t freq_int,
u16_t freq_milli)
{
struct bmi160_device_data *bmi160 = dev->driver_data;
int odr = bmi160_freq_to_odr_val(freq_int, freq_milli);
if (odr < 0) {
return odr;
}
/* some odr values cannot be set in certain power modes */
if ((bmi160->pmu_sts.acc == BMI160_PMU_NORMAL &&
odr < BMI160_ODR_25_2) ||
(bmi160->pmu_sts.acc == BMI160_PMU_LOW_POWER &&
odr < BMI160_ODR_25_32) || odr > BMI160_ODR_1600) {
return -ENOTSUP;
}
return bmi160_reg_field_update(dev, BMI160_REG_ACC_CONF,
BMI160_ACC_CONF_ODR_POS,
BMI160_ACC_CONF_ODR_MASK,
(u8_t) odr);
}
#endif
static const struct bmi160_range bmi160_acc_range_map[] = {
{2, BMI160_ACC_RANGE_2G},
{4, BMI160_ACC_RANGE_4G},
{8, BMI160_ACC_RANGE_8G},
{16, BMI160_ACC_RANGE_16G},
};
#define BMI160_ACC_RANGE_MAP_SIZE ARRAY_SIZE(bmi160_acc_range_map)
static const struct bmi160_range bmi160_gyr_range_map[] = {
{2000, BMI160_GYR_RANGE_2000DPS},
{1000, BMI160_GYR_RANGE_1000DPS},
{500, BMI160_GYR_RANGE_500DPS},
{250, BMI160_GYR_RANGE_250DPS},
{125, BMI160_GYR_RANGE_125DPS},
};
#define BMI160_GYR_RANGE_MAP_SIZE ARRAY_SIZE(bmi160_gyr_range_map)
#if defined(CONFIG_BMI160_ACCEL_RANGE_RUNTIME) ||\
defined(CONFIG_BMI160_GYRO_RANGE_RUNTIME)
static s32_t bmi160_range_to_reg_val(u16_t range,
const struct bmi160_range *range_map,
u16_t range_map_size)
{
int i;
for (i = 0; i < range_map_size; i++) {
if (range <= range_map[i].range) {
return range_map[i].reg_val;
}
}
return -EINVAL;
}
#endif
static s32_t bmi160_reg_val_to_range(u8_t reg_val,
const struct bmi160_range *range_map,
u16_t range_map_size)
{
int i;
for (i = 0; i < range_map_size; i++) {
if (reg_val == range_map[i].reg_val) {
return range_map[i].range;
}
}
return -EINVAL;
}
s32_t bmi160_acc_reg_val_to_range(u8_t reg_val)
{
return bmi160_reg_val_to_range(reg_val, bmi160_acc_range_map,
BMI160_ACC_RANGE_MAP_SIZE);
}
s32_t bmi160_gyr_reg_val_to_range(u8_t reg_val)
{
return bmi160_reg_val_to_range(reg_val, bmi160_gyr_range_map,
BMI160_GYR_RANGE_MAP_SIZE);
}
static int bmi160_do_calibration(struct device *dev, u8_t foc_conf)
{
if (bmi160_byte_write(dev, BMI160_REG_FOC_CONF, foc_conf) < 0) {
return -EIO;
}
if (bmi160_byte_write(dev, BMI160_REG_CMD, BMI160_CMD_START_FOC) < 0) {
return -EIO;
}
k_busy_wait(250000); /* calibration takes a maximum of 250ms */
return 0;
}
#if defined(CONFIG_BMI160_ACCEL_RANGE_RUNTIME)
static int bmi160_acc_range_set(struct device *dev, s32_t range)
{
struct bmi160_device_data *bmi160 = dev->driver_data;
s32_t reg_val = bmi160_range_to_reg_val(range,
bmi160_acc_range_map,
BMI160_ACC_RANGE_MAP_SIZE);
if (reg_val < 0) {
return reg_val;
}
if (bmi160_byte_write(dev, BMI160_REG_ACC_RANGE, reg_val & 0xff) < 0) {
return -EIO;
}
bmi160->scale.acc = BMI160_ACC_SCALE(range);
return 0;
}
#endif
#if !defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND)
/*
* Accelerometer offset scale, taken from pg. 79, converted to micro m/s^2:
* 3.9 * 9.80665 * 1000
*/
#define BMI160_ACC_OFS_LSB 38246
static int bmi160_acc_ofs_set(struct device *dev, enum sensor_channel chan,
const struct sensor_value *ofs)
{
u8_t reg_addr[] = {
BMI160_REG_OFFSET_ACC_X,
BMI160_REG_OFFSET_ACC_Y,
BMI160_REG_OFFSET_ACC_Z
};
int i;
s32_t ofs_u;
s8_t reg_val;
/* we need the offsets for all axis */
if (chan != SENSOR_CHAN_ACCEL_XYZ) {
return -ENOTSUP;
}
for (i = 0; i < 3; i++, ofs++) {
/* convert ofset to micro m/s^2 */
ofs_u = ofs->val1 * 1000000ULL + ofs->val2;
reg_val = ofs_u / BMI160_ACC_OFS_LSB;
if (bmi160_byte_write(dev, reg_addr[i], reg_val) < 0) {
return -EIO;
}
}
/* activate accel HW compensation */
return bmi160_reg_field_update(dev, BMI160_REG_OFFSET_EN,
BMI160_ACC_OFS_EN_POS,
BIT(BMI160_ACC_OFS_EN_POS), 1);
}
static int bmi160_acc_calibrate(struct device *dev, enum sensor_channel chan,
const struct sensor_value *xyz_calib_value)
{
struct bmi160_device_data *bmi160 = dev->driver_data;
u8_t foc_pos[] = {
BMI160_FOC_ACC_X_POS,
BMI160_FOC_ACC_Y_POS,
BMI160_FOC_ACC_Z_POS,
};
int i;
u8_t reg_val = 0U;
/* Calibration has to be done in normal mode. */
if (bmi160->pmu_sts.acc != BMI160_PMU_NORMAL) {
return -ENOTSUP;
}
/*
* Hardware calibration is done knowing the expected values on all axis.
*/
if (chan != SENSOR_CHAN_ACCEL_XYZ) {
return -ENOTSUP;
}
for (i = 0; i < 3; i++, xyz_calib_value++) {
s32_t accel_g;
u8_t accel_val;
accel_g = sensor_ms2_to_g(xyz_calib_value);
if (accel_g == 0) {
accel_val = 3U;
} else if (accel_g == 1) {
accel_val = 1U;
} else if (accel_g == -1) {
accel_val = 2U;
} else {
accel_val = 0U;
}
reg_val |= (accel_val << foc_pos[i]);
}
if (bmi160_do_calibration(dev, reg_val) < 0) {
return -EIO;
}
/* activate accel HW compensation */
return bmi160_reg_field_update(dev, BMI160_REG_OFFSET_EN,
BMI160_ACC_OFS_EN_POS,
BIT(BMI160_ACC_OFS_EN_POS), 1);
}
static int bmi160_acc_config(struct device *dev, enum sensor_channel chan,
enum sensor_attribute attr,
const struct sensor_value *val)
{
switch (attr) {
#if defined(CONFIG_BMI160_ACCEL_RANGE_RUNTIME)
case SENSOR_ATTR_FULL_SCALE:
return bmi160_acc_range_set(dev, sensor_ms2_to_g(val));
#endif
#if defined(CONFIG_BMI160_ACCEL_ODR_RUNTIME)
case SENSOR_ATTR_SAMPLING_FREQUENCY:
return bmi160_acc_odr_set(dev, val->val1, val->val2 / 1000);
#endif
case SENSOR_ATTR_OFFSET:
return bmi160_acc_ofs_set(dev, chan, val);
case SENSOR_ATTR_CALIB_TARGET:
return bmi160_acc_calibrate(dev, chan, val);
#if defined(CONFIG_BMI160_TRIGGER)
case SENSOR_ATTR_SLOPE_TH:
case SENSOR_ATTR_SLOPE_DUR:
return bmi160_acc_slope_config(dev, attr, val);
#endif
default:
LOG_DBG("Accel attribute not supported.");
return -ENOTSUP;
}
return 0;
}
#endif /* !defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND) */
#if defined(CONFIG_BMI160_GYRO_ODR_RUNTIME)
static int bmi160_gyr_odr_set(struct device *dev, u16_t freq_int,
u16_t freq_milli)
{
int odr = bmi160_freq_to_odr_val(freq_int, freq_milli);
if (odr < 0) {
return odr;
}
if (odr < BMI160_ODR_25 || odr > BMI160_ODR_3200) {
return -ENOTSUP;
}
return bmi160_reg_field_update(dev, BMI160_REG_GYR_CONF,
BMI160_GYR_CONF_ODR_POS,
BMI160_GYR_CONF_ODR_MASK,
(u8_t) odr);
}
#endif
#if defined(CONFIG_BMI160_GYRO_RANGE_RUNTIME)
static int bmi160_gyr_range_set(struct device *dev, u16_t range)
{
struct bmi160_device_data *bmi160 = dev->driver_data;
s32_t reg_val = bmi160_range_to_reg_val(range,
bmi160_gyr_range_map,
BMI160_GYR_RANGE_MAP_SIZE);
if (reg_val < 0) {
return reg_val;
}
if (bmi160_byte_write(dev, BMI160_REG_GYR_RANGE, reg_val) < 0) {
return -EIO;
}
bmi160->scale.gyr = BMI160_GYR_SCALE(range);
return 0;
}
#endif
#if !defined(CONFIG_BMI160_GYRO_PMU_SUSPEND)
/*
* Gyro offset scale, taken from pg. 79, converted to micro rad/s:
* 0.061 * (pi / 180) * 1000000, where pi = 3.141592
*/
#define BMI160_GYR_OFS_LSB 1065
static int bmi160_gyr_ofs_set(struct device *dev, enum sensor_channel chan,
const struct sensor_value *ofs)
{
struct {
u8_t lsb_addr;
u8_t msb_pos;
} ofs_desc[] = {
{BMI160_REG_OFFSET_GYR_X, BMI160_GYR_MSB_OFS_X_POS},
{BMI160_REG_OFFSET_GYR_Y, BMI160_GYR_MSB_OFS_Y_POS},
{BMI160_REG_OFFSET_GYR_Z, BMI160_GYR_MSB_OFS_Z_POS},
};
int i;
s32_t ofs_u;
s16_t val;
/* we need the offsets for all axis */
if (chan != SENSOR_CHAN_GYRO_XYZ) {
return -ENOTSUP;
}
for (i = 0; i < 3; i++, ofs++) {
/* convert offset to micro rad/s */
ofs_u = ofs->val1 * 1000000ULL + ofs->val2;
val = ofs_u / BMI160_GYR_OFS_LSB;
/*
* The gyro offset is a 10 bit two-complement value. Make sure
* the passed value is within limits.
*/
if (val < -512 || val > 512) {
return -EINVAL;
}
/* write the LSB */
if (bmi160_byte_write(dev, ofs_desc[i].lsb_addr,
val & 0xff) < 0) {
return -EIO;
}
/* write the MSB */
if (bmi160_reg_field_update(dev, BMI160_REG_OFFSET_EN,
ofs_desc[i].msb_pos,
0x3 << ofs_desc[i].msb_pos,
(val >> 8) & 0x3) < 0) {
return -EIO;
}
}
/* activate gyro HW compensation */
return bmi160_reg_field_update(dev, BMI160_REG_OFFSET_EN,
BMI160_GYR_OFS_EN_POS,
BIT(BMI160_GYR_OFS_EN_POS), 1);
}
static int bmi160_gyr_calibrate(struct device *dev, enum sensor_channel chan)
{
struct bmi160_device_data *bmi160 = dev->driver_data;
ARG_UNUSED(chan);
/* Calibration has to be done in normal mode. */
if (bmi160->pmu_sts.gyr != BMI160_PMU_NORMAL) {
return -ENOTSUP;
}
if (bmi160_do_calibration(dev, BIT(BMI160_FOC_GYR_EN_POS)) < 0) {
return -EIO;
}
/* activate gyro HW compensation */
return bmi160_reg_field_update(dev, BMI160_REG_OFFSET_EN,
BMI160_GYR_OFS_EN_POS,
BIT(BMI160_GYR_OFS_EN_POS), 1);
}
static int bmi160_gyr_config(struct device *dev, enum sensor_channel chan,
enum sensor_attribute attr,
const struct sensor_value *val)
{
switch (attr) {
#if defined(CONFIG_BMI160_GYRO_RANGE_RUNTIME)
case SENSOR_ATTR_FULL_SCALE:
return bmi160_gyr_range_set(dev, sensor_rad_to_degrees(val));
#endif
#if defined(CONFIG_BMI160_GYRO_ODR_RUNTIME)
case SENSOR_ATTR_SAMPLING_FREQUENCY:
return bmi160_gyr_odr_set(dev, val->val1, val->val2 / 1000);
#endif
case SENSOR_ATTR_OFFSET:
return bmi160_gyr_ofs_set(dev, chan, val);
case SENSOR_ATTR_CALIB_TARGET:
return bmi160_gyr_calibrate(dev, chan);
default:
LOG_DBG("Gyro attribute not supported.");
return -ENOTSUP;
}
return 0;
}
#endif /* !defined(CONFIG_BMI160_GYRO_PMU_SUSPEND) */
static int bmi160_attr_set(struct device *dev, enum sensor_channel chan,
enum sensor_attribute attr, const struct sensor_value *val)
{
switch (chan) {
#if !defined(CONFIG_BMI160_GYRO_PMU_SUSPEND)
case SENSOR_CHAN_GYRO_X:
case SENSOR_CHAN_GYRO_Y:
case SENSOR_CHAN_GYRO_Z:
case SENSOR_CHAN_GYRO_XYZ:
return bmi160_gyr_config(dev, chan, attr, val);
#endif
#if !defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND)
case SENSOR_CHAN_ACCEL_X:
case SENSOR_CHAN_ACCEL_Y:
case SENSOR_CHAN_ACCEL_Z:
case SENSOR_CHAN_ACCEL_XYZ:
return bmi160_acc_config(dev, chan, attr, val);
#endif
default:
LOG_DBG("attr_set() not supported on this channel.");
return -ENOTSUP;
}
return 0;
}
#if defined(CONFIG_BMI160_GYRO_PMU_SUSPEND)
# define BMI160_SAMPLE_BURST_READ_ADDR BMI160_REG_DATA_ACC_X
# define BMI160_DATA_READY_BIT_MASK (1 << 7)
#else
# define BMI160_SAMPLE_BURST_READ_ADDR BMI160_REG_DATA_GYR_X
# define BMI160_DATA_READY_BIT_MASK (1 << 6)
#endif
static int bmi160_sample_fetch(struct device *dev, enum sensor_channel chan)
{
struct bmi160_device_data *bmi160 = dev->driver_data;
size_t i;
__ASSERT_NO_MSG(chan == SENSOR_CHAN_ALL);
bmi160->sample.raw[0] = 0U;
while ((bmi160->sample.raw[0] & BMI160_DATA_READY_BIT_MASK) == 0) {
if (bmi160_transceive(dev, BMI160_REG_STATUS | (1 << 7), false,
bmi160->sample.raw, 1) < 0) {
return -EIO;
}
}
if (bmi160_transceive(dev, BMI160_SAMPLE_BURST_READ_ADDR | (1 << 7),
false, bmi160->sample.raw, BMI160_BUF_SIZE) < 0) {
return -EIO;
}
/* convert samples to cpu endianness */
for (i = 0; i < BMI160_SAMPLE_SIZE; i += 2) {
u16_t *sample =
(u16_t *) &bmi160->sample.raw[i];
*sample = sys_le16_to_cpu(*sample);
}
return 0;
}
static void bmi160_to_fixed_point(s16_t raw_val, u16_t scale,
struct sensor_value *val)
{
s32_t converted_val;
/*
* maximum converted value we can get is: max(raw_val) * max(scale)
* max(raw_val) = +/- 2^15
* max(scale) = 4785
* max(converted_val) = 156794880 which is less than 2^31
*/
converted_val = raw_val * scale;
val->val1 = converted_val / 1000000;
val->val2 = converted_val % 1000000;
}
static void bmi160_channel_convert(enum sensor_channel chan,
u16_t scale,
u16_t *raw_xyz,
struct sensor_value *val)
{
int i;
u8_t ofs_start, ofs_stop;
switch (chan) {
case SENSOR_CHAN_ACCEL_X:
case SENSOR_CHAN_GYRO_X:
ofs_start = ofs_stop = 0U;
break;
case SENSOR_CHAN_ACCEL_Y:
case SENSOR_CHAN_GYRO_Y:
ofs_start = ofs_stop = 1U;
break;
case SENSOR_CHAN_ACCEL_Z:
case SENSOR_CHAN_GYRO_Z:
ofs_start = ofs_stop = 2U;
break;
default:
ofs_start = 0U; ofs_stop = 2U;
break;
}
for (i = ofs_start; i <= ofs_stop ; i++, val++) {
bmi160_to_fixed_point(raw_xyz[i], scale, val);
}
}
#if !defined(CONFIG_BMI160_GYRO_PMU_SUSPEND)
static inline void bmi160_gyr_channel_get(struct device *dev,
enum sensor_channel chan,
struct sensor_value *val)
{
struct bmi160_device_data *bmi160 = dev->driver_data;
bmi160_channel_convert(chan, bmi160->scale.gyr,
bmi160->sample.gyr, val);
}
#endif
#if !defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND)
static inline void bmi160_acc_channel_get(struct device *dev,
enum sensor_channel chan,
struct sensor_value *val)
{
struct bmi160_device_data *bmi160 = dev->driver_data;
bmi160_channel_convert(chan, bmi160->scale.acc,
bmi160->sample.acc, val);
}
#endif
static int bmi160_temp_channel_get(struct device *dev, struct sensor_value *val)
{
u16_t temp_raw = 0U;
s32_t temp_micro = 0;
struct bmi160_device_data *bmi160 = dev->driver_data;
if (bmi160->pmu_sts.raw == 0) {
return -EINVAL;
}
if (bmi160_word_read(dev, BMI160_REG_TEMPERATURE0, &temp_raw) < 0) {
return -EIO;
}
/* the scale is 1/2^9/LSB = 1953 micro degrees */
temp_micro = BMI160_TEMP_OFFSET * 1000000ULL + temp_raw * 1953ULL;
val->val1 = temp_micro / 1000000ULL;
val->val2 = temp_micro % 1000000ULL;
return 0;
}
static int bmi160_channel_get(struct device *dev,
enum sensor_channel chan,
struct sensor_value *val)
{
switch (chan) {
#if !defined(CONFIG_BMI160_GYRO_PMU_SUSPEND)
case SENSOR_CHAN_GYRO_X:
case SENSOR_CHAN_GYRO_Y:
case SENSOR_CHAN_GYRO_Z:
case SENSOR_CHAN_GYRO_XYZ:
bmi160_gyr_channel_get(dev, chan, val);
return 0;
#endif
#if !defined(CONFIG_BMI160_ACCEL_PMU_SUSPEND)
case SENSOR_CHAN_ACCEL_X:
case SENSOR_CHAN_ACCEL_Y:
case SENSOR_CHAN_ACCEL_Z:
case SENSOR_CHAN_ACCEL_XYZ:
bmi160_acc_channel_get(dev, chan, val);
return 0;
#endif
case SENSOR_CHAN_DIE_TEMP:
return bmi160_temp_channel_get(dev, val);
default:
LOG_DBG("Channel not supported.");
return -ENOTSUP;
}
return 0;
}
static const struct sensor_driver_api bmi160_api = {
.attr_set = bmi160_attr_set,
#ifdef CONFIG_BMI160_TRIGGER
.trigger_set = bmi160_trigger_set,
#endif
.sample_fetch = bmi160_sample_fetch,
.channel_get = bmi160_channel_get,
};
int bmi160_init(struct device *dev)
{
struct bmi160_device_data *bmi160 = dev->driver_data;
u8_t val = 0U;
s32_t acc_range, gyr_range;
bmi160->spi = device_get_binding(DT_BOSCH_BMI160_0_BUS_NAME);
if (!bmi160->spi) {
LOG_DBG("SPI master controller not found: %s.",
DT_BOSCH_BMI160_0_BUS_NAME);
return -EINVAL;
}
bmi160->spi_cfg.operation = SPI_WORD_SET(8);
bmi160->spi_cfg.frequency = DT_BOSCH_BMI160_0_SPI_MAX_FREQUENCY;
bmi160->spi_cfg.slave = DT_BOSCH_BMI160_0_BASE_ADDRESS;
/* reboot the chip */
if (bmi160_byte_write(dev, BMI160_REG_CMD, BMI160_CMD_SOFT_RESET) < 0) {
LOG_DBG("Cannot reboot chip.");
return -EIO;
}
k_busy_wait(1000);
/* do a dummy read from 0x7F to activate SPI */
if (bmi160_byte_read(dev, 0x7F, &val) < 0) {
LOG_DBG("Cannot read from 0x7F..");
return -EIO;
}
k_busy_wait(100);
if (bmi160_byte_read(dev, BMI160_REG_CHIPID, &val) < 0) {
LOG_DBG("Failed to read chip id.");
return -EIO;
}
if (val != BMI160_CHIP_ID) {
LOG_DBG("Unsupported chip detected (0x%x)!", val);
return -ENODEV;
}
/* set default PMU for gyro, accelerometer */
bmi160->pmu_sts.gyr = BMI160_DEFAULT_PMU_GYR;
bmi160->pmu_sts.acc = BMI160_DEFAULT_PMU_ACC;
/* compass not supported, yet */
bmi160->pmu_sts.mag = BMI160_PMU_SUSPEND;
/*
* The next command will take around 100ms (contains some necessary busy
* waits), but we cannot do it in a separate thread since we need to
* guarantee the BMI is up and running, before the app's main() is
* called.
*/
if (bmi160_pmu_set(dev, &bmi160->pmu_sts) < 0) {
LOG_DBG("Failed to set power mode.");
return -EIO;
}
/* set accelerometer default range */
if (bmi160_byte_write(dev, BMI160_REG_ACC_RANGE,
BMI160_DEFAULT_RANGE_ACC) < 0) {
LOG_DBG("Cannot set default range for accelerometer.");
return -EIO;
}
acc_range = bmi160_acc_reg_val_to_range(BMI160_DEFAULT_RANGE_ACC);
bmi160->scale.acc = BMI160_ACC_SCALE(acc_range);
/* set gyro default range */
if (bmi160_byte_write(dev, BMI160_REG_GYR_RANGE,
BMI160_DEFAULT_RANGE_GYR) < 0) {
LOG_DBG("Cannot set default range for gyroscope.");
return -EIO;
}
gyr_range = bmi160_gyr_reg_val_to_range(BMI160_DEFAULT_RANGE_GYR);
bmi160->scale.gyr = BMI160_GYR_SCALE(gyr_range);
if (bmi160_reg_field_update(dev, BMI160_REG_ACC_CONF,
BMI160_ACC_CONF_ODR_POS,
BMI160_ACC_CONF_ODR_MASK,
BMI160_DEFAULT_ODR_ACC) < 0) {
LOG_DBG("Failed to set accel's default ODR.");
return -EIO;
}
if (bmi160_reg_field_update(dev, BMI160_REG_GYR_CONF,
BMI160_GYR_CONF_ODR_POS,
BMI160_GYR_CONF_ODR_MASK,
BMI160_DEFAULT_ODR_GYR) < 0) {
LOG_DBG("Failed to set gyro's default ODR.");
return -EIO;
}
#ifdef CONFIG_BMI160_TRIGGER
if (bmi160_trigger_mode_init(dev) < 0) {
LOG_DBG("Cannot set up trigger mode.");
return -EINVAL;
}
#endif
return 0;
}
const struct bmi160_device_config bmi160_config = {
#if defined(CONFIG_BMI160_TRIGGER)
.gpio_port = DT_BOSCH_BMI160_0_INT_GPIOS_CONTROLLER,
.int_pin = DT_BOSCH_BMI160_0_INT_GPIOS_PIN,
#endif
};
DEVICE_AND_API_INIT(bmi160, DT_BOSCH_BMI160_0_LABEL, bmi160_init, &bmi160_data,
&bmi160_config, POST_KERNEL, CONFIG_SENSOR_INIT_PRIORITY,
&bmi160_api);
|
868299.c | /*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Linaro Ltd.
*
* 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.
*/
#include "py/mpconfig.h"
#if MICROPY_PY_USSL && MICROPY_SSL_MBEDTLS
#include <stdio.h>
#include <string.h>
#include <errno.h> // needed because mp_is_nonblocking_error uses system error codes
#include "py/nlr.h"
#include "py/runtime.h"
#include "py/stream.h"
#include "py/obj.h"
// mbedtls_time_t
#include "mbedtls/platform.h"
#include "mbedtls/net.h"
#include "mbedtls/ssl.h"
#include "mbedtls/x509_crt.h"
#include "mbedtls/pk.h"
#include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/debug.h"
typedef struct _mp_obj_ssl_socket_t {
mp_obj_base_t base;
mp_obj_t sock;
mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context ctr_drbg;
mbedtls_ssl_context ssl;
mbedtls_ssl_config conf;
mbedtls_x509_crt cacert;
mbedtls_x509_crt cert;
mbedtls_pk_context pkey;
} mp_obj_ssl_socket_t;
struct ssl_args {
mp_arg_val_t key;
mp_arg_val_t cert;
mp_arg_val_t server_side;
mp_arg_val_t server_hostname;
};
STATIC const mp_obj_type_t ussl_socket_type;
static void mbedtls_debug(void *ctx, int level, const char *file, int line, const char *str) {
printf("DBG:%s:%04d: %s\n", file, line, str);
}
// TODO: FIXME!
int null_entropy_func(void *data, unsigned char *output, size_t len) {
// enjoy random bytes
return 0;
}
int _mbedtls_ssl_send(void *ctx, const byte *buf, size_t len) {
mp_obj_t sock = *(mp_obj_t*)ctx;
const mp_stream_p_t *sock_stream = mp_get_stream_raise(sock, MP_STREAM_OP_WRITE);
int err;
int out_sz = sock_stream->write(sock, buf, len, &err);
if (out_sz == MP_STREAM_ERROR) {
if (mp_is_nonblocking_error(err)) {
return MBEDTLS_ERR_SSL_WANT_WRITE;
}
return -err;
} else {
return out_sz;
}
}
int _mbedtls_ssl_recv(void *ctx, byte *buf, size_t len) {
mp_obj_t sock = *(mp_obj_t*)ctx;
const mp_stream_p_t *sock_stream = mp_get_stream_raise(sock, MP_STREAM_OP_READ);
int err;
int out_sz = sock_stream->read(sock, buf, len, &err);
if (out_sz == MP_STREAM_ERROR) {
if (mp_is_nonblocking_error(err)) {
return MBEDTLS_ERR_SSL_WANT_READ;
}
return -err;
} else {
return out_sz;
}
}
STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) {
mp_obj_ssl_socket_t *o = m_new_obj(mp_obj_ssl_socket_t);
o->base.type = &ussl_socket_type;
int ret;
mbedtls_ssl_init(&o->ssl);
mbedtls_ssl_config_init(&o->conf);
mbedtls_x509_crt_init(&o->cacert);
mbedtls_x509_crt_init(&o->cert);
mbedtls_pk_init(&o->pkey);
mbedtls_ctr_drbg_init(&o->ctr_drbg);
// Debug level (0-4)
mbedtls_debug_set_threshold(0);
mbedtls_entropy_init(&o->entropy);
const byte seed[] = "upy";
ret = mbedtls_ctr_drbg_seed(&o->ctr_drbg, null_entropy_func/*mbedtls_entropy_func*/, &o->entropy, seed, sizeof(seed));
if (ret != 0) {
printf("ret=%d\n", ret);
assert(0);
}
ret = mbedtls_ssl_config_defaults(&o->conf,
args->server_side.u_bool ? MBEDTLS_SSL_IS_SERVER : MBEDTLS_SSL_IS_CLIENT,
MBEDTLS_SSL_TRANSPORT_STREAM,
MBEDTLS_SSL_PRESET_DEFAULT);
if (ret != 0) {
assert(0);
}
mbedtls_ssl_conf_authmode(&o->conf, MBEDTLS_SSL_VERIFY_NONE);
mbedtls_ssl_conf_rng(&o->conf, mbedtls_ctr_drbg_random, &o->ctr_drbg);
mbedtls_ssl_conf_dbg(&o->conf, mbedtls_debug, NULL);
ret = mbedtls_ssl_setup(&o->ssl, &o->conf);
if (ret != 0) {
assert(0);
}
if (args->server_hostname.u_obj != mp_const_none) {
const char *sni = mp_obj_str_get_str(args->server_hostname.u_obj);
ret = mbedtls_ssl_set_hostname(&o->ssl, sni);
if (ret != 0) {
assert(0);
}
}
o->sock = sock;
mbedtls_ssl_set_bio(&o->ssl, &o->sock, _mbedtls_ssl_send, _mbedtls_ssl_recv, NULL);
if (args->key.u_obj != MP_OBJ_NULL) {
size_t key_len;
const byte *key = (const byte*)mp_obj_str_get_data(args->key.u_obj, &key_len);
// len should include terminating null
ret = mbedtls_pk_parse_key(&o->pkey, key, key_len + 1, NULL, 0);
assert(ret == 0);
size_t cert_len;
const byte *cert = (const byte*)mp_obj_str_get_data(args->cert.u_obj, &cert_len);
// len should include terminating null
ret = mbedtls_x509_crt_parse(&o->cert, cert, cert_len + 1);
assert(ret == 0);
ret = mbedtls_ssl_conf_own_cert(&o->conf, &o->cert, &o->pkey);
assert(ret == 0);
}
while ((ret = mbedtls_ssl_handshake(&o->ssl)) != 0) {
if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
//assert(0);
printf("mbedtls_ssl_handshake error: -%x\n", -ret);
mp_raise_OSError(MP_EIO);
}
}
return o;
}
STATIC mp_obj_t mod_ssl_getpeercert(mp_obj_t o_in, mp_obj_t binary_form) {
mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(o_in);
if (!mp_obj_is_true(binary_form)) {
mp_raise_NotImplementedError(NULL);
}
const mbedtls_x509_crt* peer_cert = mbedtls_ssl_get_peer_cert(&o->ssl);
return mp_obj_new_bytes(peer_cert->raw.p, peer_cert->raw.len);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_ssl_getpeercert_obj, mod_ssl_getpeercert);
STATIC void socket_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
(void)kind;
mp_obj_ssl_socket_t *self = MP_OBJ_TO_PTR(self_in);
mp_printf(print, "<_SSLSocket %p>", self);
}
STATIC mp_uint_t socket_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *errcode) {
mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(o_in);
int ret = mbedtls_ssl_read(&o->ssl, buf, size);
if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
// end of stream
return 0;
}
if (ret >= 0) {
return ret;
}
if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
ret = MP_EWOULDBLOCK;
}
*errcode = ret;
return MP_STREAM_ERROR;
}
STATIC mp_uint_t socket_write(mp_obj_t o_in, const void *buf, mp_uint_t size, int *errcode) {
mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(o_in);
int ret = mbedtls_ssl_write(&o->ssl, buf, size);
if (ret >= 0) {
return ret;
}
if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
ret = MP_EWOULDBLOCK;
}
*errcode = ret;
return MP_STREAM_ERROR;
}
STATIC mp_obj_t socket_setblocking(mp_obj_t self_in, mp_obj_t flag_in) {
mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(self_in);
mp_obj_t sock = o->sock;
mp_obj_t dest[3];
mp_load_method(sock, MP_QSTR_setblocking, dest);
dest[2] = flag_in;
return mp_call_method_n_kw(1, 0, dest);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_setblocking_obj, socket_setblocking);
STATIC mp_obj_t socket_close(mp_obj_t self_in) {
mp_obj_ssl_socket_t *self = MP_OBJ_TO_PTR(self_in);
mbedtls_pk_free(&self->pkey);
mbedtls_x509_crt_free(&self->cert);
mbedtls_x509_crt_free(&self->cacert);
mbedtls_ssl_free(&self->ssl);
mbedtls_ssl_config_free(&self->conf);
mbedtls_ctr_drbg_free(&self->ctr_drbg);
mbedtls_entropy_free(&self->entropy);
return mp_stream_close(self->sock);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(socket_close_obj, socket_close);
STATIC const mp_rom_map_elem_t ussl_socket_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) },
{ MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) },
{ MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) },
{ MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) },
{ MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&socket_setblocking_obj) },
{ MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&socket_close_obj) },
{ MP_ROM_QSTR(MP_QSTR_getpeercert), MP_ROM_PTR(&mod_ssl_getpeercert_obj) },
};
STATIC MP_DEFINE_CONST_DICT(ussl_socket_locals_dict, ussl_socket_locals_dict_table);
STATIC const mp_stream_p_t ussl_socket_stream_p = {
.read = socket_read,
.write = socket_write,
};
STATIC const mp_obj_type_t ussl_socket_type = {
{ &mp_type_type },
// Save on qstr's, reuse same as for module
.name = MP_QSTR_ussl,
.print = socket_print,
.getiter = NULL,
.iternext = NULL,
.protocol = &ussl_socket_stream_p,
.locals_dict = (void*)&ussl_socket_locals_dict,
};
STATIC mp_obj_t mod_ssl_wrap_socket(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
// TODO: Implement more args
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_key, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
{ MP_QSTR_cert, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
{ MP_QSTR_server_side, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} },
{ MP_QSTR_server_hostname, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
};
// TODO: Check that sock implements stream protocol
mp_obj_t sock = pos_args[0];
struct ssl_args args;
mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args,
MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t*)&args);
return MP_OBJ_FROM_PTR(socket_new(sock, &args));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(mod_ssl_wrap_socket_obj, 1, mod_ssl_wrap_socket);
STATIC const mp_rom_map_elem_t mp_module_ssl_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ussl) },
{ MP_ROM_QSTR(MP_QSTR_wrap_socket), MP_ROM_PTR(&mod_ssl_wrap_socket_obj) },
};
STATIC MP_DEFINE_CONST_DICT(mp_module_ssl_globals, mp_module_ssl_globals_table);
const mp_obj_module_t mp_module_ussl = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&mp_module_ssl_globals,
};
#endif // MICROPY_PY_USSL
|
655208.c | #include <stdio.h>
#include <syslog.h>
#include <timer.h>
#include <plic.h>
#include <sysctl.h>
#include <fpioa.h>
#include "gpio.h"
#include "gpiohs.h"
#include "uarths.h"
#include "sleep.h"
#include "motor.h"
static const char *TAG = "MAIN";
int main(void)
{
sysctl_pll_set_freq(SYSCTL_PLL0, 320000000UL);
sysctl_pll_set_freq(SYSCTL_PLL1, 160000000UL);
sysctl_pll_set_freq(SYSCTL_PLL2, 45158400UL);
uarths_init();
plic_init();
sysctl_enable_irq();
LOGD(TAG, "MOTOR TEST");
motor_io_mux();
default_door();
msleep(3000);
while(1)
{
motor_control();
}
}
|
980422.c | /*
* SMB2 version specific operations
*
* Copyright (c) 2012, Jeff Layton <[email protected]>
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License v2 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 library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/pagemap.h>
#include <linux/vfs.h>
#include <linux/falloc.h>
#include "cifsglob.h"
#include "smb2pdu.h"
#include "smb2proto.h"
#include "cifsproto.h"
#include "cifs_debug.h"
#include "cifs_unicode.h"
#include "smb2status.h"
#include "smb2glob.h"
static int
change_conf(struct TCP_Server_Info *server)
{
server->credits += server->echo_credits + server->oplock_credits;
server->oplock_credits = server->echo_credits = 0;
switch (server->credits) {
case 0:
return -1;
case 1:
server->echoes = false;
server->oplocks = false;
cifs_dbg(VFS, "disabling echoes and oplocks\n");
break;
case 2:
server->echoes = true;
server->oplocks = false;
server->echo_credits = 1;
cifs_dbg(FYI, "disabling oplocks\n");
break;
default:
server->echoes = true;
if (enable_oplocks) {
server->oplocks = true;
server->oplock_credits = 1;
} else
server->oplocks = false;
server->echo_credits = 1;
}
server->credits -= server->echo_credits + server->oplock_credits;
return 0;
}
static void
smb2_add_credits(struct TCP_Server_Info *server, const unsigned int add,
const int optype)
{
int *val, rc = 0;
spin_lock(&server->req_lock);
val = server->ops->get_credits_field(server, optype);
*val += add;
server->in_flight--;
if (server->in_flight == 0 && (optype & CIFS_OP_MASK) != CIFS_NEG_OP)
rc = change_conf(server);
/*
* Sometimes server returns 0 credits on oplock break ack - we need to
* rebalance credits in this case.
*/
else if (server->in_flight > 0 && server->oplock_credits == 0 &&
server->oplocks) {
if (server->credits > 1) {
server->credits--;
server->oplock_credits++;
}
}
spin_unlock(&server->req_lock);
wake_up(&server->request_q);
if (rc)
cifs_reconnect(server);
}
static void
smb2_set_credits(struct TCP_Server_Info *server, const int val)
{
spin_lock(&server->req_lock);
server->credits = val;
spin_unlock(&server->req_lock);
}
static int *
smb2_get_credits_field(struct TCP_Server_Info *server, const int optype)
{
switch (optype) {
case CIFS_ECHO_OP:
return &server->echo_credits;
case CIFS_OBREAK_OP:
return &server->oplock_credits;
default:
return &server->credits;
}
}
static unsigned int
smb2_get_credits(struct mid_q_entry *mid)
{
return le16_to_cpu(((struct smb2_hdr *)mid->resp_buf)->CreditRequest);
}
static int
smb2_wait_mtu_credits(struct TCP_Server_Info *server, unsigned int size,
unsigned int *num, unsigned int *credits)
{
int rc = 0;
unsigned int scredits;
spin_lock(&server->req_lock);
while (1) {
if (server->credits <= 0) {
spin_unlock(&server->req_lock);
cifs_num_waiters_inc(server);
rc = wait_event_killable(server->request_q,
has_credits(server, &server->credits));
cifs_num_waiters_dec(server);
if (rc)
return rc;
spin_lock(&server->req_lock);
} else {
if (server->tcpStatus == CifsExiting) {
spin_unlock(&server->req_lock);
return -ENOENT;
}
scredits = server->credits;
/* can deadlock with reopen */
if (scredits == 1) {
*num = SMB2_MAX_BUFFER_SIZE;
*credits = 0;
break;
}
/* leave one credit for a possible reopen */
scredits--;
*num = min_t(unsigned int, size,
scredits * SMB2_MAX_BUFFER_SIZE);
*credits = DIV_ROUND_UP(*num, SMB2_MAX_BUFFER_SIZE);
server->credits -= *credits;
server->in_flight++;
break;
}
}
spin_unlock(&server->req_lock);
return rc;
}
static __u64
smb2_get_next_mid(struct TCP_Server_Info *server)
{
__u64 mid;
/* for SMB2 we need the current value */
spin_lock(&GlobalMid_Lock);
mid = server->CurrentMid++;
spin_unlock(&GlobalMid_Lock);
return mid;
}
static struct mid_q_entry *
smb2_find_mid(struct TCP_Server_Info *server, char *buf)
{
struct mid_q_entry *mid;
struct smb2_hdr *hdr = (struct smb2_hdr *)buf;
__u64 wire_mid = le64_to_cpu(hdr->MessageId);
if (hdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM) {
cifs_dbg(VFS, "encrypted frame parsing not supported yet");
return NULL;
}
spin_lock(&GlobalMid_Lock);
list_for_each_entry(mid, &server->pending_mid_q, qhead) {
if ((mid->mid == wire_mid) &&
(mid->mid_state == MID_REQUEST_SUBMITTED) &&
(mid->command == hdr->Command)) {
spin_unlock(&GlobalMid_Lock);
return mid;
}
}
spin_unlock(&GlobalMid_Lock);
return NULL;
}
static void
smb2_dump_detail(void *buf)
{
#ifdef CONFIG_CIFS_DEBUG2
struct smb2_hdr *smb = (struct smb2_hdr *)buf;
cifs_dbg(VFS, "Cmd: %d Err: 0x%x Flags: 0x%x Mid: %llu Pid: %d\n",
smb->Command, smb->Status, smb->Flags, smb->MessageId,
smb->ProcessId);
cifs_dbg(VFS, "smb buf %p len %u\n", smb, smb2_calc_size(smb));
#endif
}
static bool
smb2_need_neg(struct TCP_Server_Info *server)
{
return server->max_read == 0;
}
static int
smb2_negotiate(const unsigned int xid, struct cifs_ses *ses)
{
int rc;
ses->server->CurrentMid = 0;
rc = SMB2_negotiate(xid, ses);
/* BB we probably don't need to retry with modern servers */
if (rc == -EAGAIN)
rc = -EHOSTDOWN;
return rc;
}
static unsigned int
smb2_negotiate_wsize(struct cifs_tcon *tcon, struct smb_vol *volume_info)
{
struct TCP_Server_Info *server = tcon->ses->server;
unsigned int wsize;
/* start with specified wsize, or default */
wsize = volume_info->wsize ? volume_info->wsize : CIFS_DEFAULT_IOSIZE;
wsize = min_t(unsigned int, wsize, server->max_write);
if (!(server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
wsize = min_t(unsigned int, wsize, SMB2_MAX_BUFFER_SIZE);
return wsize;
}
static unsigned int
smb2_negotiate_rsize(struct cifs_tcon *tcon, struct smb_vol *volume_info)
{
struct TCP_Server_Info *server = tcon->ses->server;
unsigned int rsize;
/* start with specified rsize, or default */
rsize = volume_info->rsize ? volume_info->rsize : CIFS_DEFAULT_IOSIZE;
rsize = min_t(unsigned int, rsize, server->max_read);
if (!(server->capabilities & SMB2_GLOBAL_CAP_LARGE_MTU))
rsize = min_t(unsigned int, rsize, SMB2_MAX_BUFFER_SIZE);
return rsize;
}
#ifdef CONFIG_CIFS_STATS2
static int
SMB3_request_interfaces(const unsigned int xid, struct cifs_tcon *tcon)
{
int rc;
unsigned int ret_data_len = 0;
struct network_interface_info_ioctl_rsp *out_buf;
rc = SMB2_ioctl(xid, tcon, NO_FILE_ID, NO_FILE_ID,
FSCTL_QUERY_NETWORK_INTERFACE_INFO, true /* is_fsctl */,
NULL /* no data input */, 0 /* no data input */,
(char **)&out_buf, &ret_data_len);
if (rc != 0)
cifs_dbg(VFS, "error %d on ioctl to get interface list\n", rc);
else if (ret_data_len < sizeof(struct network_interface_info_ioctl_rsp)) {
cifs_dbg(VFS, "server returned bad net interface info buf\n");
rc = -EINVAL;
} else {
/* Dump info on first interface */
cifs_dbg(FYI, "Adapter Capability 0x%x\t",
le32_to_cpu(out_buf->Capability));
cifs_dbg(FYI, "Link Speed %lld\n",
le64_to_cpu(out_buf->LinkSpeed));
}
return rc;
}
#endif /* STATS2 */
static void
smb3_qfs_tcon(const unsigned int xid, struct cifs_tcon *tcon)
{
int rc;
__le16 srch_path = 0; /* Null - open root of share */
u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
struct cifs_open_parms oparms;
struct cifs_fid fid;
oparms.tcon = tcon;
oparms.desired_access = FILE_READ_ATTRIBUTES;
oparms.disposition = FILE_OPEN;
oparms.create_options = 0;
oparms.fid = &fid;
oparms.reconnect = false;
rc = SMB2_open(xid, &oparms, &srch_path, &oplock, NULL, NULL);
if (rc)
return;
#ifdef CONFIG_CIFS_STATS2
SMB3_request_interfaces(xid, tcon);
#endif /* STATS2 */
SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
FS_ATTRIBUTE_INFORMATION);
SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
FS_DEVICE_INFORMATION);
SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
FS_SECTOR_SIZE_INFORMATION); /* SMB3 specific */
SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
return;
}
static void
smb2_qfs_tcon(const unsigned int xid, struct cifs_tcon *tcon)
{
int rc;
__le16 srch_path = 0; /* Null - open root of share */
u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
struct cifs_open_parms oparms;
struct cifs_fid fid;
oparms.tcon = tcon;
oparms.desired_access = FILE_READ_ATTRIBUTES;
oparms.disposition = FILE_OPEN;
oparms.create_options = 0;
oparms.fid = &fid;
oparms.reconnect = false;
rc = SMB2_open(xid, &oparms, &srch_path, &oplock, NULL, NULL);
if (rc)
return;
SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
FS_ATTRIBUTE_INFORMATION);
SMB2_QFS_attr(xid, tcon, fid.persistent_fid, fid.volatile_fid,
FS_DEVICE_INFORMATION);
SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
return;
}
static int
smb2_is_path_accessible(const unsigned int xid, struct cifs_tcon *tcon,
struct cifs_sb_info *cifs_sb, const char *full_path)
{
int rc;
__le16 *utf16_path;
__u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
struct cifs_open_parms oparms;
struct cifs_fid fid;
utf16_path = cifs_convert_path_to_utf16(full_path, cifs_sb);
if (!utf16_path)
return -ENOMEM;
oparms.tcon = tcon;
oparms.desired_access = FILE_READ_ATTRIBUTES;
oparms.disposition = FILE_OPEN;
oparms.create_options = 0;
oparms.fid = &fid;
oparms.reconnect = false;
rc = SMB2_open(xid, &oparms, utf16_path, &oplock, NULL, NULL);
if (rc) {
kfree(utf16_path);
return rc;
}
rc = SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
kfree(utf16_path);
return rc;
}
static int
smb2_get_srv_inum(const unsigned int xid, struct cifs_tcon *tcon,
struct cifs_sb_info *cifs_sb, const char *full_path,
u64 *uniqueid, FILE_ALL_INFO *data)
{
*uniqueid = le64_to_cpu(data->IndexNumber);
return 0;
}
static int
smb2_query_file_info(const unsigned int xid, struct cifs_tcon *tcon,
struct cifs_fid *fid, FILE_ALL_INFO *data)
{
int rc;
struct smb2_file_all_info *smb2_data;
smb2_data = kzalloc(sizeof(struct smb2_file_all_info) + PATH_MAX * 2,
GFP_KERNEL);
if (smb2_data == NULL)
return -ENOMEM;
rc = SMB2_query_info(xid, tcon, fid->persistent_fid, fid->volatile_fid,
smb2_data);
if (!rc)
move_smb2_info_to_cifs(data, smb2_data);
kfree(smb2_data);
return rc;
}
static bool
smb2_can_echo(struct TCP_Server_Info *server)
{
return server->echoes;
}
static void
smb2_clear_stats(struct cifs_tcon *tcon)
{
#ifdef CONFIG_CIFS_STATS
int i;
for (i = 0; i < NUMBER_OF_SMB2_COMMANDS; i++) {
atomic_set(&tcon->stats.smb2_stats.smb2_com_sent[i], 0);
atomic_set(&tcon->stats.smb2_stats.smb2_com_failed[i], 0);
}
#endif
}
static void
smb2_dump_share_caps(struct seq_file *m, struct cifs_tcon *tcon)
{
seq_puts(m, "\n\tShare Capabilities:");
if (tcon->capabilities & SMB2_SHARE_CAP_DFS)
seq_puts(m, " DFS,");
if (tcon->capabilities & SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY)
seq_puts(m, " CONTINUOUS AVAILABILITY,");
if (tcon->capabilities & SMB2_SHARE_CAP_SCALEOUT)
seq_puts(m, " SCALEOUT,");
if (tcon->capabilities & SMB2_SHARE_CAP_CLUSTER)
seq_puts(m, " CLUSTER,");
if (tcon->capabilities & SMB2_SHARE_CAP_ASYMMETRIC)
seq_puts(m, " ASYMMETRIC,");
if (tcon->capabilities == 0)
seq_puts(m, " None");
if (tcon->ss_flags & SSINFO_FLAGS_ALIGNED_DEVICE)
seq_puts(m, " Aligned,");
if (tcon->ss_flags & SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE)
seq_puts(m, " Partition Aligned,");
if (tcon->ss_flags & SSINFO_FLAGS_NO_SEEK_PENALTY)
seq_puts(m, " SSD,");
if (tcon->ss_flags & SSINFO_FLAGS_TRIM_ENABLED)
seq_puts(m, " TRIM-support,");
seq_printf(m, "\tShare Flags: 0x%x", tcon->share_flags);
if (tcon->perf_sector_size)
seq_printf(m, "\tOptimal sector size: 0x%x",
tcon->perf_sector_size);
}
static void
smb2_print_stats(struct seq_file *m, struct cifs_tcon *tcon)
{
#ifdef CONFIG_CIFS_STATS
atomic_t *sent = tcon->stats.smb2_stats.smb2_com_sent;
atomic_t *failed = tcon->stats.smb2_stats.smb2_com_failed;
seq_printf(m, "\nNegotiates: %d sent %d failed",
atomic_read(&sent[SMB2_NEGOTIATE_HE]),
atomic_read(&failed[SMB2_NEGOTIATE_HE]));
seq_printf(m, "\nSessionSetups: %d sent %d failed",
atomic_read(&sent[SMB2_SESSION_SETUP_HE]),
atomic_read(&failed[SMB2_SESSION_SETUP_HE]));
seq_printf(m, "\nLogoffs: %d sent %d failed",
atomic_read(&sent[SMB2_LOGOFF_HE]),
atomic_read(&failed[SMB2_LOGOFF_HE]));
seq_printf(m, "\nTreeConnects: %d sent %d failed",
atomic_read(&sent[SMB2_TREE_CONNECT_HE]),
atomic_read(&failed[SMB2_TREE_CONNECT_HE]));
seq_printf(m, "\nTreeDisconnects: %d sent %d failed",
atomic_read(&sent[SMB2_TREE_DISCONNECT_HE]),
atomic_read(&failed[SMB2_TREE_DISCONNECT_HE]));
seq_printf(m, "\nCreates: %d sent %d failed",
atomic_read(&sent[SMB2_CREATE_HE]),
atomic_read(&failed[SMB2_CREATE_HE]));
seq_printf(m, "\nCloses: %d sent %d failed",
atomic_read(&sent[SMB2_CLOSE_HE]),
atomic_read(&failed[SMB2_CLOSE_HE]));
seq_printf(m, "\nFlushes: %d sent %d failed",
atomic_read(&sent[SMB2_FLUSH_HE]),
atomic_read(&failed[SMB2_FLUSH_HE]));
seq_printf(m, "\nReads: %d sent %d failed",
atomic_read(&sent[SMB2_READ_HE]),
atomic_read(&failed[SMB2_READ_HE]));
seq_printf(m, "\nWrites: %d sent %d failed",
atomic_read(&sent[SMB2_WRITE_HE]),
atomic_read(&failed[SMB2_WRITE_HE]));
seq_printf(m, "\nLocks: %d sent %d failed",
atomic_read(&sent[SMB2_LOCK_HE]),
atomic_read(&failed[SMB2_LOCK_HE]));
seq_printf(m, "\nIOCTLs: %d sent %d failed",
atomic_read(&sent[SMB2_IOCTL_HE]),
atomic_read(&failed[SMB2_IOCTL_HE]));
seq_printf(m, "\nCancels: %d sent %d failed",
atomic_read(&sent[SMB2_CANCEL_HE]),
atomic_read(&failed[SMB2_CANCEL_HE]));
seq_printf(m, "\nEchos: %d sent %d failed",
atomic_read(&sent[SMB2_ECHO_HE]),
atomic_read(&failed[SMB2_ECHO_HE]));
seq_printf(m, "\nQueryDirectories: %d sent %d failed",
atomic_read(&sent[SMB2_QUERY_DIRECTORY_HE]),
atomic_read(&failed[SMB2_QUERY_DIRECTORY_HE]));
seq_printf(m, "\nChangeNotifies: %d sent %d failed",
atomic_read(&sent[SMB2_CHANGE_NOTIFY_HE]),
atomic_read(&failed[SMB2_CHANGE_NOTIFY_HE]));
seq_printf(m, "\nQueryInfos: %d sent %d failed",
atomic_read(&sent[SMB2_QUERY_INFO_HE]),
atomic_read(&failed[SMB2_QUERY_INFO_HE]));
seq_printf(m, "\nSetInfos: %d sent %d failed",
atomic_read(&sent[SMB2_SET_INFO_HE]),
atomic_read(&failed[SMB2_SET_INFO_HE]));
seq_printf(m, "\nOplockBreaks: %d sent %d failed",
atomic_read(&sent[SMB2_OPLOCK_BREAK_HE]),
atomic_read(&failed[SMB2_OPLOCK_BREAK_HE]));
#endif
}
static void
smb2_set_fid(struct cifsFileInfo *cfile, struct cifs_fid *fid, __u32 oplock)
{
struct cifsInodeInfo *cinode = CIFS_I(d_inode(cfile->dentry));
struct TCP_Server_Info *server = tlink_tcon(cfile->tlink)->ses->server;
cfile->fid.persistent_fid = fid->persistent_fid;
cfile->fid.volatile_fid = fid->volatile_fid;
server->ops->set_oplock_level(cinode, oplock, fid->epoch,
&fid->purge_cache);
cinode->can_cache_brlcks = CIFS_CACHE_WRITE(cinode);
}
static void
smb2_close_file(const unsigned int xid, struct cifs_tcon *tcon,
struct cifs_fid *fid)
{
SMB2_close(xid, tcon, fid->persistent_fid, fid->volatile_fid);
}
static int
SMB2_request_res_key(const unsigned int xid, struct cifs_tcon *tcon,
u64 persistent_fid, u64 volatile_fid,
struct copychunk_ioctl *pcchunk)
{
int rc;
unsigned int ret_data_len;
struct resume_key_req *res_key;
rc = SMB2_ioctl(xid, tcon, persistent_fid, volatile_fid,
FSCTL_SRV_REQUEST_RESUME_KEY, true /* is_fsctl */,
NULL, 0 /* no input */,
(char **)&res_key, &ret_data_len);
if (rc) {
cifs_dbg(VFS, "refcpy ioctl error %d getting resume key\n", rc);
goto req_res_key_exit;
}
if (ret_data_len < sizeof(struct resume_key_req)) {
cifs_dbg(VFS, "Invalid refcopy resume key length\n");
rc = -EINVAL;
goto req_res_key_exit;
}
memcpy(pcchunk->SourceKey, res_key->ResumeKey, COPY_CHUNK_RES_KEY_SIZE);
req_res_key_exit:
kfree(res_key);
return rc;
}
static int
smb2_clone_range(const unsigned int xid,
struct cifsFileInfo *srcfile,
struct cifsFileInfo *trgtfile, u64 src_off,
u64 len, u64 dest_off)
{
int rc;
unsigned int ret_data_len;
struct copychunk_ioctl *pcchunk;
struct copychunk_ioctl_rsp *retbuf = NULL;
struct cifs_tcon *tcon;
int chunks_copied = 0;
bool chunk_sizes_updated = false;
pcchunk = kmalloc(sizeof(struct copychunk_ioctl), GFP_KERNEL);
if (pcchunk == NULL)
return -ENOMEM;
cifs_dbg(FYI, "in smb2_clone_range - about to call request res key\n");
/* Request a key from the server to identify the source of the copy */
rc = SMB2_request_res_key(xid, tlink_tcon(srcfile->tlink),
srcfile->fid.persistent_fid,
srcfile->fid.volatile_fid, pcchunk);
/* Note: request_res_key sets res_key null only if rc !=0 */
if (rc)
goto cchunk_out;
/* For now array only one chunk long, will make more flexible later */
pcchunk->ChunkCount = cpu_to_le32(1);
pcchunk->Reserved = 0;
pcchunk->Reserved2 = 0;
tcon = tlink_tcon(trgtfile->tlink);
while (len > 0) {
pcchunk->SourceOffset = cpu_to_le64(src_off);
pcchunk->TargetOffset = cpu_to_le64(dest_off);
pcchunk->Length =
cpu_to_le32(min_t(u32, len, tcon->max_bytes_chunk));
/* Request server copy to target from src identified by key */
rc = SMB2_ioctl(xid, tcon, trgtfile->fid.persistent_fid,
trgtfile->fid.volatile_fid, FSCTL_SRV_COPYCHUNK_WRITE,
true /* is_fsctl */, (char *)pcchunk,
sizeof(struct copychunk_ioctl), (char **)&retbuf,
&ret_data_len);
if (rc == 0) {
if (ret_data_len !=
sizeof(struct copychunk_ioctl_rsp)) {
cifs_dbg(VFS, "invalid cchunk response size\n");
rc = -EIO;
goto cchunk_out;
}
if (retbuf->TotalBytesWritten == 0) {
cifs_dbg(FYI, "no bytes copied\n");
rc = -EIO;
goto cchunk_out;
}
/*
* Check if server claimed to write more than we asked
*/
if (le32_to_cpu(retbuf->TotalBytesWritten) >
le32_to_cpu(pcchunk->Length)) {
cifs_dbg(VFS, "invalid copy chunk response\n");
rc = -EIO;
goto cchunk_out;
}
if (le32_to_cpu(retbuf->ChunksWritten) != 1) {
cifs_dbg(VFS, "invalid num chunks written\n");
rc = -EIO;
goto cchunk_out;
}
chunks_copied++;
src_off += le32_to_cpu(retbuf->TotalBytesWritten);
dest_off += le32_to_cpu(retbuf->TotalBytesWritten);
len -= le32_to_cpu(retbuf->TotalBytesWritten);
cifs_dbg(FYI, "Chunks %d PartialChunk %d Total %d\n",
le32_to_cpu(retbuf->ChunksWritten),
le32_to_cpu(retbuf->ChunkBytesWritten),
le32_to_cpu(retbuf->TotalBytesWritten));
} else if (rc == -EINVAL) {
if (ret_data_len != sizeof(struct copychunk_ioctl_rsp))
goto cchunk_out;
cifs_dbg(FYI, "MaxChunks %d BytesChunk %d MaxCopy %d\n",
le32_to_cpu(retbuf->ChunksWritten),
le32_to_cpu(retbuf->ChunkBytesWritten),
le32_to_cpu(retbuf->TotalBytesWritten));
/*
* Check if this is the first request using these sizes,
* (ie check if copy succeed once with original sizes
* and check if the server gave us different sizes after
* we already updated max sizes on previous request).
* if not then why is the server returning an error now
*/
if ((chunks_copied != 0) || chunk_sizes_updated)
goto cchunk_out;
/* Check that server is not asking us to grow size */
if (le32_to_cpu(retbuf->ChunkBytesWritten) <
tcon->max_bytes_chunk)
tcon->max_bytes_chunk =
le32_to_cpu(retbuf->ChunkBytesWritten);
else
goto cchunk_out; /* server gave us bogus size */
/* No need to change MaxChunks since already set to 1 */
chunk_sizes_updated = true;
} else
goto cchunk_out;
}
cchunk_out:
kfree(pcchunk);
return rc;
}
static int
smb2_flush_file(const unsigned int xid, struct cifs_tcon *tcon,
struct cifs_fid *fid)
{
return SMB2_flush(xid, tcon, fid->persistent_fid, fid->volatile_fid);
}
static unsigned int
smb2_read_data_offset(char *buf)
{
struct smb2_read_rsp *rsp = (struct smb2_read_rsp *)buf;
return rsp->DataOffset;
}
static unsigned int
smb2_read_data_length(char *buf)
{
struct smb2_read_rsp *rsp = (struct smb2_read_rsp *)buf;
return le32_to_cpu(rsp->DataLength);
}
static int
smb2_sync_read(const unsigned int xid, struct cifs_fid *pfid,
struct cifs_io_parms *parms, unsigned int *bytes_read,
char **buf, int *buf_type)
{
parms->persistent_fid = pfid->persistent_fid;
parms->volatile_fid = pfid->volatile_fid;
return SMB2_read(xid, parms, bytes_read, buf, buf_type);
}
static int
smb2_sync_write(const unsigned int xid, struct cifs_fid *pfid,
struct cifs_io_parms *parms, unsigned int *written,
struct kvec *iov, unsigned long nr_segs)
{
parms->persistent_fid = pfid->persistent_fid;
parms->volatile_fid = pfid->volatile_fid;
return SMB2_write(xid, parms, written, iov, nr_segs);
}
/* Set or clear the SPARSE_FILE attribute based on value passed in setsparse */
static bool smb2_set_sparse(const unsigned int xid, struct cifs_tcon *tcon,
struct cifsFileInfo *cfile, struct inode *inode, __u8 setsparse)
{
struct cifsInodeInfo *cifsi;
int rc;
cifsi = CIFS_I(inode);
/* if file already sparse don't bother setting sparse again */
if ((cifsi->cifsAttrs & FILE_ATTRIBUTE_SPARSE_FILE) && setsparse)
return true; /* already sparse */
if (!(cifsi->cifsAttrs & FILE_ATTRIBUTE_SPARSE_FILE) && !setsparse)
return true; /* already not sparse */
/*
* Can't check for sparse support on share the usual way via the
* FS attribute info (FILE_SUPPORTS_SPARSE_FILES) on the share
* since Samba server doesn't set the flag on the share, yet
* supports the set sparse FSCTL and returns sparse correctly
* in the file attributes. If we fail setting sparse though we
* mark that server does not support sparse files for this share
* to avoid repeatedly sending the unsupported fsctl to server
* if the file is repeatedly extended.
*/
if (tcon->broken_sparse_sup)
return false;
rc = SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
cfile->fid.volatile_fid, FSCTL_SET_SPARSE,
true /* is_fctl */, &setsparse, 1, NULL, NULL);
if (rc) {
tcon->broken_sparse_sup = true;
cifs_dbg(FYI, "set sparse rc = %d\n", rc);
return false;
}
if (setsparse)
cifsi->cifsAttrs |= FILE_ATTRIBUTE_SPARSE_FILE;
else
cifsi->cifsAttrs &= (~FILE_ATTRIBUTE_SPARSE_FILE);
return true;
}
static int
smb2_set_file_size(const unsigned int xid, struct cifs_tcon *tcon,
struct cifsFileInfo *cfile, __u64 size, bool set_alloc)
{
__le64 eof = cpu_to_le64(size);
struct inode *inode;
/*
* If extending file more than one page make sparse. Many Linux fs
* make files sparse by default when extending via ftruncate
*/
inode = d_inode(cfile->dentry);
if (!set_alloc && (size > inode->i_size + 8192)) {
__u8 set_sparse = 1;
/* whether set sparse succeeds or not, extend the file */
smb2_set_sparse(xid, tcon, cfile, inode, set_sparse);
}
return SMB2_set_eof(xid, tcon, cfile->fid.persistent_fid,
cfile->fid.volatile_fid, cfile->pid, &eof, false);
}
static int
smb2_duplicate_extents(const unsigned int xid,
struct cifsFileInfo *srcfile,
struct cifsFileInfo *trgtfile, u64 src_off,
u64 len, u64 dest_off)
{
int rc;
unsigned int ret_data_len;
char *retbuf = NULL;
struct duplicate_extents_to_file dup_ext_buf;
struct cifs_tcon *tcon = tlink_tcon(trgtfile->tlink);
/* server fileays advertise duplicate extent support with this flag */
if ((le32_to_cpu(tcon->fsAttrInfo.Attributes) &
FILE_SUPPORTS_BLOCK_REFCOUNTING) == 0)
return -EOPNOTSUPP;
dup_ext_buf.VolatileFileHandle = srcfile->fid.volatile_fid;
dup_ext_buf.PersistentFileHandle = srcfile->fid.persistent_fid;
dup_ext_buf.SourceFileOffset = cpu_to_le64(src_off);
dup_ext_buf.TargetFileOffset = cpu_to_le64(dest_off);
dup_ext_buf.ByteCount = cpu_to_le64(len);
cifs_dbg(FYI, "duplicate extents: src off %lld dst off %lld len %lld",
src_off, dest_off, len);
rc = smb2_set_file_size(xid, tcon, trgtfile, dest_off + len, false);
if (rc)
goto duplicate_extents_out;
rc = SMB2_ioctl(xid, tcon, trgtfile->fid.persistent_fid,
trgtfile->fid.volatile_fid,
FSCTL_DUPLICATE_EXTENTS_TO_FILE,
true /* is_fsctl */, (char *)&dup_ext_buf,
sizeof(struct duplicate_extents_to_file),
(char **)&retbuf,
&ret_data_len);
if (ret_data_len > 0)
cifs_dbg(FYI, "non-zero response length in duplicate extents");
duplicate_extents_out:
return rc;
}
static int
smb2_set_compression(const unsigned int xid, struct cifs_tcon *tcon,
struct cifsFileInfo *cfile)
{
return SMB2_set_compression(xid, tcon, cfile->fid.persistent_fid,
cfile->fid.volatile_fid);
}
static int
smb3_set_integrity(const unsigned int xid, struct cifs_tcon *tcon,
struct cifsFileInfo *cfile)
{
struct fsctl_set_integrity_information_req integr_info;
char *retbuf = NULL;
unsigned int ret_data_len;
integr_info.ChecksumAlgorithm = cpu_to_le16(CHECKSUM_TYPE_UNCHANGED);
integr_info.Flags = 0;
integr_info.Reserved = 0;
return SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
cfile->fid.volatile_fid,
FSCTL_SET_INTEGRITY_INFORMATION,
true /* is_fsctl */, (char *)&integr_info,
sizeof(struct fsctl_set_integrity_information_req),
(char **)&retbuf,
&ret_data_len);
}
static int
smb2_query_dir_first(const unsigned int xid, struct cifs_tcon *tcon,
const char *path, struct cifs_sb_info *cifs_sb,
struct cifs_fid *fid, __u16 search_flags,
struct cifs_search_info *srch_inf)
{
__le16 *utf16_path;
int rc;
__u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
struct cifs_open_parms oparms;
utf16_path = cifs_convert_path_to_utf16(path, cifs_sb);
if (!utf16_path)
return -ENOMEM;
oparms.tcon = tcon;
oparms.desired_access = FILE_READ_ATTRIBUTES | FILE_READ_DATA;
oparms.disposition = FILE_OPEN;
oparms.create_options = 0;
oparms.fid = fid;
oparms.reconnect = false;
rc = SMB2_open(xid, &oparms, utf16_path, &oplock, NULL, NULL);
kfree(utf16_path);
if (rc) {
cifs_dbg(VFS, "open dir failed\n");
return rc;
}
srch_inf->entries_in_buffer = 0;
srch_inf->index_of_last_entry = 0;
rc = SMB2_query_directory(xid, tcon, fid->persistent_fid,
fid->volatile_fid, 0, srch_inf);
if (rc) {
cifs_dbg(VFS, "query directory failed\n");
SMB2_close(xid, tcon, fid->persistent_fid, fid->volatile_fid);
}
return rc;
}
static int
smb2_query_dir_next(const unsigned int xid, struct cifs_tcon *tcon,
struct cifs_fid *fid, __u16 search_flags,
struct cifs_search_info *srch_inf)
{
return SMB2_query_directory(xid, tcon, fid->persistent_fid,
fid->volatile_fid, 0, srch_inf);
}
static int
smb2_close_dir(const unsigned int xid, struct cifs_tcon *tcon,
struct cifs_fid *fid)
{
return SMB2_close(xid, tcon, fid->persistent_fid, fid->volatile_fid);
}
/*
* If we negotiate SMB2 protocol and get STATUS_PENDING - update
* the number of credits and return true. Otherwise - return false.
*/
static bool
smb2_is_status_pending(char *buf, struct TCP_Server_Info *server, int length)
{
struct smb2_hdr *hdr = (struct smb2_hdr *)buf;
if (hdr->Status != STATUS_PENDING)
return false;
if (!length) {
spin_lock(&server->req_lock);
server->credits += le16_to_cpu(hdr->CreditRequest);
spin_unlock(&server->req_lock);
wake_up(&server->request_q);
}
return true;
}
static int
smb2_oplock_response(struct cifs_tcon *tcon, struct cifs_fid *fid,
struct cifsInodeInfo *cinode)
{
if (tcon->ses->server->capabilities & SMB2_GLOBAL_CAP_LEASING)
return SMB2_lease_break(0, tcon, cinode->lease_key,
smb2_get_lease_state(cinode));
return SMB2_oplock_break(0, tcon, fid->persistent_fid,
fid->volatile_fid,
CIFS_CACHE_READ(cinode) ? 1 : 0);
}
static int
smb2_queryfs(const unsigned int xid, struct cifs_tcon *tcon,
struct kstatfs *buf)
{
int rc;
__le16 srch_path = 0; /* Null - open root of share */
u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
struct cifs_open_parms oparms;
struct cifs_fid fid;
oparms.tcon = tcon;
oparms.desired_access = FILE_READ_ATTRIBUTES;
oparms.disposition = FILE_OPEN;
oparms.create_options = 0;
oparms.fid = &fid;
oparms.reconnect = false;
rc = SMB2_open(xid, &oparms, &srch_path, &oplock, NULL, NULL);
if (rc)
return rc;
buf->f_type = SMB2_MAGIC_NUMBER;
rc = SMB2_QFS_info(xid, tcon, fid.persistent_fid, fid.volatile_fid,
buf);
SMB2_close(xid, tcon, fid.persistent_fid, fid.volatile_fid);
return rc;
}
static bool
smb2_compare_fids(struct cifsFileInfo *ob1, struct cifsFileInfo *ob2)
{
return ob1->fid.persistent_fid == ob2->fid.persistent_fid &&
ob1->fid.volatile_fid == ob2->fid.volatile_fid;
}
static int
smb2_mand_lock(const unsigned int xid, struct cifsFileInfo *cfile, __u64 offset,
__u64 length, __u32 type, int lock, int unlock, bool wait)
{
if (unlock && !lock)
type = SMB2_LOCKFLAG_UNLOCK;
return SMB2_lock(xid, tlink_tcon(cfile->tlink),
cfile->fid.persistent_fid, cfile->fid.volatile_fid,
current->tgid, length, offset, type, wait);
}
static void
smb2_get_lease_key(struct inode *inode, struct cifs_fid *fid)
{
memcpy(fid->lease_key, CIFS_I(inode)->lease_key, SMB2_LEASE_KEY_SIZE);
}
static void
smb2_set_lease_key(struct inode *inode, struct cifs_fid *fid)
{
memcpy(CIFS_I(inode)->lease_key, fid->lease_key, SMB2_LEASE_KEY_SIZE);
}
static void
smb2_new_lease_key(struct cifs_fid *fid)
{
get_random_bytes(fid->lease_key, SMB2_LEASE_KEY_SIZE);
}
static int
smb2_query_symlink(const unsigned int xid, struct cifs_tcon *tcon,
const char *full_path, char **target_path,
struct cifs_sb_info *cifs_sb)
{
int rc;
__le16 *utf16_path;
__u8 oplock = SMB2_OPLOCK_LEVEL_NONE;
struct cifs_open_parms oparms;
struct cifs_fid fid;
struct smb2_err_rsp *err_buf = NULL;
struct smb2_symlink_err_rsp *symlink;
unsigned int sub_len, sub_offset;
cifs_dbg(FYI, "%s: path: %s\n", __func__, full_path);
utf16_path = cifs_convert_path_to_utf16(full_path, cifs_sb);
if (!utf16_path)
return -ENOMEM;
oparms.tcon = tcon;
oparms.desired_access = FILE_READ_ATTRIBUTES;
oparms.disposition = FILE_OPEN;
oparms.create_options = 0;
oparms.fid = &fid;
oparms.reconnect = false;
rc = SMB2_open(xid, &oparms, utf16_path, &oplock, NULL, &err_buf);
if (!rc || !err_buf) {
kfree(utf16_path);
return -ENOENT;
}
/* open must fail on symlink - reset rc */
rc = 0;
symlink = (struct smb2_symlink_err_rsp *)err_buf->ErrorData;
sub_len = le16_to_cpu(symlink->SubstituteNameLength);
sub_offset = le16_to_cpu(symlink->SubstituteNameOffset);
*target_path = cifs_strndup_from_utf16(
(char *)symlink->PathBuffer + sub_offset,
sub_len, true, cifs_sb->local_nls);
if (!(*target_path)) {
kfree(utf16_path);
return -ENOMEM;
}
convert_delimiter(*target_path, '/');
cifs_dbg(FYI, "%s: target path: %s\n", __func__, *target_path);
kfree(utf16_path);
return rc;
}
static long smb3_zero_range(struct file *file, struct cifs_tcon *tcon,
loff_t offset, loff_t len, bool keep_size)
{
struct inode *inode;
struct cifsInodeInfo *cifsi;
struct cifsFileInfo *cfile = file->private_data;
struct file_zero_data_information fsctl_buf;
long rc;
unsigned int xid;
xid = get_xid();
inode = d_inode(cfile->dentry);
cifsi = CIFS_I(inode);
/* if file not oplocked can't be sure whether asking to extend size */
if (!CIFS_CACHE_READ(cifsi))
if (keep_size == false)
return -EOPNOTSUPP;
/*
* Must check if file sparse since fallocate -z (zero range) assumes
* non-sparse allocation
*/
if (!(cifsi->cifsAttrs & FILE_ATTRIBUTE_SPARSE_FILE))
return -EOPNOTSUPP;
/*
* need to make sure we are not asked to extend the file since the SMB3
* fsctl does not change the file size. In the future we could change
* this to zero the first part of the range then set the file size
* which for a non sparse file would zero the newly extended range
*/
if (keep_size == false)
if (i_size_read(inode) < offset + len)
return -EOPNOTSUPP;
cifs_dbg(FYI, "offset %lld len %lld", offset, len);
fsctl_buf.FileOffset = cpu_to_le64(offset);
fsctl_buf.BeyondFinalZero = cpu_to_le64(offset + len);
rc = SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
cfile->fid.volatile_fid, FSCTL_SET_ZERO_DATA,
true /* is_fctl */, (char *)&fsctl_buf,
sizeof(struct file_zero_data_information), NULL, NULL);
free_xid(xid);
return rc;
}
static long smb3_punch_hole(struct file *file, struct cifs_tcon *tcon,
loff_t offset, loff_t len)
{
struct inode *inode;
struct cifsInodeInfo *cifsi;
struct cifsFileInfo *cfile = file->private_data;
struct file_zero_data_information fsctl_buf;
long rc;
unsigned int xid;
__u8 set_sparse = 1;
xid = get_xid();
inode = d_inode(cfile->dentry);
cifsi = CIFS_I(inode);
/* Need to make file sparse, if not already, before freeing range. */
/* Consider adding equivalent for compressed since it could also work */
if (!smb2_set_sparse(xid, tcon, cfile, inode, set_sparse))
return -EOPNOTSUPP;
cifs_dbg(FYI, "offset %lld len %lld", offset, len);
fsctl_buf.FileOffset = cpu_to_le64(offset);
fsctl_buf.BeyondFinalZero = cpu_to_le64(offset + len);
rc = SMB2_ioctl(xid, tcon, cfile->fid.persistent_fid,
cfile->fid.volatile_fid, FSCTL_SET_ZERO_DATA,
true /* is_fctl */, (char *)&fsctl_buf,
sizeof(struct file_zero_data_information), NULL, NULL);
free_xid(xid);
return rc;
}
static long smb3_simple_falloc(struct file *file, struct cifs_tcon *tcon,
loff_t off, loff_t len, bool keep_size)
{
struct inode *inode;
struct cifsInodeInfo *cifsi;
struct cifsFileInfo *cfile = file->private_data;
long rc = -EOPNOTSUPP;
unsigned int xid;
xid = get_xid();
inode = d_inode(cfile->dentry);
cifsi = CIFS_I(inode);
/* if file not oplocked can't be sure whether asking to extend size */
if (!CIFS_CACHE_READ(cifsi))
if (keep_size == false)
return -EOPNOTSUPP;
/*
* Files are non-sparse by default so falloc may be a no-op
* Must check if file sparse. If not sparse, and not extending
* then no need to do anything since file already allocated
*/
if ((cifsi->cifsAttrs & FILE_ATTRIBUTE_SPARSE_FILE) == 0) {
if (keep_size == true)
return 0;
/* check if extending file */
else if (i_size_read(inode) >= off + len)
/* not extending file and already not sparse */
return 0;
/* BB: in future add else clause to extend file */
else
return -EOPNOTSUPP;
}
if ((keep_size == true) || (i_size_read(inode) >= off + len)) {
/*
* Check if falloc starts within first few pages of file
* and ends within a few pages of the end of file to
* ensure that most of file is being forced to be
* fallocated now. If so then setting whole file sparse
* ie potentially making a few extra pages at the beginning
* or end of the file non-sparse via set_sparse is harmless.
*/
if ((off > 8192) || (off + len + 8192 < i_size_read(inode)))
return -EOPNOTSUPP;
rc = smb2_set_sparse(xid, tcon, cfile, inode, false);
}
/* BB: else ... in future add code to extend file and set sparse */
free_xid(xid);
return rc;
}
static long smb3_fallocate(struct file *file, struct cifs_tcon *tcon, int mode,
loff_t off, loff_t len)
{
/* KEEP_SIZE already checked for by do_fallocate */
if (mode & FALLOC_FL_PUNCH_HOLE)
return smb3_punch_hole(file, tcon, off, len);
else if (mode & FALLOC_FL_ZERO_RANGE) {
if (mode & FALLOC_FL_KEEP_SIZE)
return smb3_zero_range(file, tcon, off, len, true);
return smb3_zero_range(file, tcon, off, len, false);
} else if (mode == FALLOC_FL_KEEP_SIZE)
return smb3_simple_falloc(file, tcon, off, len, true);
else if (mode == 0)
return smb3_simple_falloc(file, tcon, off, len, false);
return -EOPNOTSUPP;
}
static void
smb2_downgrade_oplock(struct TCP_Server_Info *server,
struct cifsInodeInfo *cinode, bool set_level2)
{
if (set_level2)
server->ops->set_oplock_level(cinode, SMB2_OPLOCK_LEVEL_II,
0, NULL);
else
server->ops->set_oplock_level(cinode, 0, 0, NULL);
}
static void
smb2_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock,
unsigned int epoch, bool *purge_cache)
{
oplock &= 0xFF;
if (oplock == SMB2_OPLOCK_LEVEL_NOCHANGE)
return;
if (oplock == SMB2_OPLOCK_LEVEL_BATCH) {
cinode->oplock = CIFS_CACHE_RHW_FLG;
cifs_dbg(FYI, "Batch Oplock granted on inode %p\n",
&cinode->vfs_inode);
} else if (oplock == SMB2_OPLOCK_LEVEL_EXCLUSIVE) {
cinode->oplock = CIFS_CACHE_RW_FLG;
cifs_dbg(FYI, "Exclusive Oplock granted on inode %p\n",
&cinode->vfs_inode);
} else if (oplock == SMB2_OPLOCK_LEVEL_II) {
cinode->oplock = CIFS_CACHE_READ_FLG;
cifs_dbg(FYI, "Level II Oplock granted on inode %p\n",
&cinode->vfs_inode);
} else
cinode->oplock = 0;
}
static void
smb21_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock,
unsigned int epoch, bool *purge_cache)
{
char message[5] = {0};
oplock &= 0xFF;
if (oplock == SMB2_OPLOCK_LEVEL_NOCHANGE)
return;
cinode->oplock = 0;
if (oplock & SMB2_LEASE_READ_CACHING_HE) {
cinode->oplock |= CIFS_CACHE_READ_FLG;
strcat(message, "R");
}
if (oplock & SMB2_LEASE_HANDLE_CACHING_HE) {
cinode->oplock |= CIFS_CACHE_HANDLE_FLG;
strcat(message, "H");
}
if (oplock & SMB2_LEASE_WRITE_CACHING_HE) {
cinode->oplock |= CIFS_CACHE_WRITE_FLG;
strcat(message, "W");
}
if (!cinode->oplock)
strcat(message, "None");
cifs_dbg(FYI, "%s Lease granted on inode %p\n", message,
&cinode->vfs_inode);
}
static void
smb3_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock,
unsigned int epoch, bool *purge_cache)
{
unsigned int old_oplock = cinode->oplock;
smb21_set_oplock_level(cinode, oplock, epoch, purge_cache);
if (purge_cache) {
*purge_cache = false;
if (old_oplock == CIFS_CACHE_READ_FLG) {
if (cinode->oplock == CIFS_CACHE_READ_FLG &&
(epoch - cinode->epoch > 0))
*purge_cache = true;
else if (cinode->oplock == CIFS_CACHE_RH_FLG &&
(epoch - cinode->epoch > 1))
*purge_cache = true;
else if (cinode->oplock == CIFS_CACHE_RHW_FLG &&
(epoch - cinode->epoch > 1))
*purge_cache = true;
else if (cinode->oplock == 0 &&
(epoch - cinode->epoch > 0))
*purge_cache = true;
} else if (old_oplock == CIFS_CACHE_RH_FLG) {
if (cinode->oplock == CIFS_CACHE_RH_FLG &&
(epoch - cinode->epoch > 0))
*purge_cache = true;
else if (cinode->oplock == CIFS_CACHE_RHW_FLG &&
(epoch - cinode->epoch > 1))
*purge_cache = true;
}
cinode->epoch = epoch;
}
}
static bool
smb2_is_read_op(__u32 oplock)
{
return oplock == SMB2_OPLOCK_LEVEL_II;
}
static bool
smb21_is_read_op(__u32 oplock)
{
return (oplock & SMB2_LEASE_READ_CACHING_HE) &&
!(oplock & SMB2_LEASE_WRITE_CACHING_HE);
}
static __le32
map_oplock_to_lease(u8 oplock)
{
if (oplock == SMB2_OPLOCK_LEVEL_EXCLUSIVE)
return SMB2_LEASE_WRITE_CACHING | SMB2_LEASE_READ_CACHING;
else if (oplock == SMB2_OPLOCK_LEVEL_II)
return SMB2_LEASE_READ_CACHING;
else if (oplock == SMB2_OPLOCK_LEVEL_BATCH)
return SMB2_LEASE_HANDLE_CACHING | SMB2_LEASE_READ_CACHING |
SMB2_LEASE_WRITE_CACHING;
return 0;
}
static char *
smb2_create_lease_buf(u8 *lease_key, u8 oplock)
{
struct create_lease *buf;
buf = kzalloc(sizeof(struct create_lease), GFP_KERNEL);
if (!buf)
return NULL;
buf->lcontext.LeaseKeyLow = cpu_to_le64(*((u64 *)lease_key));
buf->lcontext.LeaseKeyHigh = cpu_to_le64(*((u64 *)(lease_key + 8)));
buf->lcontext.LeaseState = map_oplock_to_lease(oplock);
buf->ccontext.DataOffset = cpu_to_le16(offsetof
(struct create_lease, lcontext));
buf->ccontext.DataLength = cpu_to_le32(sizeof(struct lease_context));
buf->ccontext.NameOffset = cpu_to_le16(offsetof
(struct create_lease, Name));
buf->ccontext.NameLength = cpu_to_le16(4);
/* SMB2_CREATE_REQUEST_LEASE is "RqLs" */
buf->Name[0] = 'R';
buf->Name[1] = 'q';
buf->Name[2] = 'L';
buf->Name[3] = 's';
return (char *)buf;
}
static char *
smb3_create_lease_buf(u8 *lease_key, u8 oplock)
{
struct create_lease_v2 *buf;
buf = kzalloc(sizeof(struct create_lease_v2), GFP_KERNEL);
if (!buf)
return NULL;
buf->lcontext.LeaseKeyLow = cpu_to_le64(*((u64 *)lease_key));
buf->lcontext.LeaseKeyHigh = cpu_to_le64(*((u64 *)(lease_key + 8)));
buf->lcontext.LeaseState = map_oplock_to_lease(oplock);
buf->ccontext.DataOffset = cpu_to_le16(offsetof
(struct create_lease_v2, lcontext));
buf->ccontext.DataLength = cpu_to_le32(sizeof(struct lease_context_v2));
buf->ccontext.NameOffset = cpu_to_le16(offsetof
(struct create_lease_v2, Name));
buf->ccontext.NameLength = cpu_to_le16(4);
/* SMB2_CREATE_REQUEST_LEASE is "RqLs" */
buf->Name[0] = 'R';
buf->Name[1] = 'q';
buf->Name[2] = 'L';
buf->Name[3] = 's';
return (char *)buf;
}
static __u8
smb2_parse_lease_buf(void *buf, unsigned int *epoch)
{
struct create_lease *lc = (struct create_lease *)buf;
*epoch = 0; /* not used */
if (lc->lcontext.LeaseFlags & SMB2_LEASE_FLAG_BREAK_IN_PROGRESS)
return SMB2_OPLOCK_LEVEL_NOCHANGE;
return le32_to_cpu(lc->lcontext.LeaseState);
}
static __u8
smb3_parse_lease_buf(void *buf, unsigned int *epoch)
{
struct create_lease_v2 *lc = (struct create_lease_v2 *)buf;
*epoch = le16_to_cpu(lc->lcontext.Epoch);
if (lc->lcontext.LeaseFlags & SMB2_LEASE_FLAG_BREAK_IN_PROGRESS)
return SMB2_OPLOCK_LEVEL_NOCHANGE;
return le32_to_cpu(lc->lcontext.LeaseState);
}
static unsigned int
smb2_wp_retry_size(struct inode *inode)
{
return min_t(unsigned int, CIFS_SB(inode->i_sb)->wsize,
SMB2_MAX_BUFFER_SIZE);
}
static bool
smb2_dir_needs_close(struct cifsFileInfo *cfile)
{
return !cfile->invalidHandle;
}
struct smb_version_operations smb20_operations = {
.compare_fids = smb2_compare_fids,
.setup_request = smb2_setup_request,
.setup_async_request = smb2_setup_async_request,
.check_receive = smb2_check_receive,
.add_credits = smb2_add_credits,
.set_credits = smb2_set_credits,
.get_credits_field = smb2_get_credits_field,
.get_credits = smb2_get_credits,
.wait_mtu_credits = cifs_wait_mtu_credits,
.get_next_mid = smb2_get_next_mid,
.read_data_offset = smb2_read_data_offset,
.read_data_length = smb2_read_data_length,
.map_error = map_smb2_to_linux_error,
.find_mid = smb2_find_mid,
.check_message = smb2_check_message,
.dump_detail = smb2_dump_detail,
.clear_stats = smb2_clear_stats,
.print_stats = smb2_print_stats,
.is_oplock_break = smb2_is_valid_oplock_break,
.downgrade_oplock = smb2_downgrade_oplock,
.need_neg = smb2_need_neg,
.negotiate = smb2_negotiate,
.negotiate_wsize = smb2_negotiate_wsize,
.negotiate_rsize = smb2_negotiate_rsize,
.sess_setup = SMB2_sess_setup,
.logoff = SMB2_logoff,
.tree_connect = SMB2_tcon,
.tree_disconnect = SMB2_tdis,
.qfs_tcon = smb2_qfs_tcon,
.is_path_accessible = smb2_is_path_accessible,
.can_echo = smb2_can_echo,
.echo = SMB2_echo,
.query_path_info = smb2_query_path_info,
.get_srv_inum = smb2_get_srv_inum,
.query_file_info = smb2_query_file_info,
.set_path_size = smb2_set_path_size,
.set_file_size = smb2_set_file_size,
.set_file_info = smb2_set_file_info,
.set_compression = smb2_set_compression,
.mkdir = smb2_mkdir,
.mkdir_setinfo = smb2_mkdir_setinfo,
.rmdir = smb2_rmdir,
.unlink = smb2_unlink,
.rename = smb2_rename_path,
.create_hardlink = smb2_create_hardlink,
.query_symlink = smb2_query_symlink,
.open = smb2_open_file,
.set_fid = smb2_set_fid,
.close = smb2_close_file,
.flush = smb2_flush_file,
.async_readv = smb2_async_readv,
.async_writev = smb2_async_writev,
.sync_read = smb2_sync_read,
.sync_write = smb2_sync_write,
.query_dir_first = smb2_query_dir_first,
.query_dir_next = smb2_query_dir_next,
.close_dir = smb2_close_dir,
.calc_smb_size = smb2_calc_size,
.is_status_pending = smb2_is_status_pending,
.oplock_response = smb2_oplock_response,
.queryfs = smb2_queryfs,
.mand_lock = smb2_mand_lock,
.mand_unlock_range = smb2_unlock_range,
.push_mand_locks = smb2_push_mandatory_locks,
.get_lease_key = smb2_get_lease_key,
.set_lease_key = smb2_set_lease_key,
.new_lease_key = smb2_new_lease_key,
.calc_signature = smb2_calc_signature,
.is_read_op = smb2_is_read_op,
.set_oplock_level = smb2_set_oplock_level,
.create_lease_buf = smb2_create_lease_buf,
.parse_lease_buf = smb2_parse_lease_buf,
.clone_range = smb2_clone_range,
.wp_retry_size = smb2_wp_retry_size,
.dir_needs_close = smb2_dir_needs_close,
};
struct smb_version_operations smb21_operations = {
.compare_fids = smb2_compare_fids,
.setup_request = smb2_setup_request,
.setup_async_request = smb2_setup_async_request,
.check_receive = smb2_check_receive,
.add_credits = smb2_add_credits,
.set_credits = smb2_set_credits,
.get_credits_field = smb2_get_credits_field,
.get_credits = smb2_get_credits,
.wait_mtu_credits = smb2_wait_mtu_credits,
.get_next_mid = smb2_get_next_mid,
.read_data_offset = smb2_read_data_offset,
.read_data_length = smb2_read_data_length,
.map_error = map_smb2_to_linux_error,
.find_mid = smb2_find_mid,
.check_message = smb2_check_message,
.dump_detail = smb2_dump_detail,
.clear_stats = smb2_clear_stats,
.print_stats = smb2_print_stats,
.is_oplock_break = smb2_is_valid_oplock_break,
.downgrade_oplock = smb2_downgrade_oplock,
.need_neg = smb2_need_neg,
.negotiate = smb2_negotiate,
.negotiate_wsize = smb2_negotiate_wsize,
.negotiate_rsize = smb2_negotiate_rsize,
.sess_setup = SMB2_sess_setup,
.logoff = SMB2_logoff,
.tree_connect = SMB2_tcon,
.tree_disconnect = SMB2_tdis,
.qfs_tcon = smb2_qfs_tcon,
.is_path_accessible = smb2_is_path_accessible,
.can_echo = smb2_can_echo,
.echo = SMB2_echo,
.query_path_info = smb2_query_path_info,
.get_srv_inum = smb2_get_srv_inum,
.query_file_info = smb2_query_file_info,
.set_path_size = smb2_set_path_size,
.set_file_size = smb2_set_file_size,
.set_file_info = smb2_set_file_info,
.set_compression = smb2_set_compression,
.mkdir = smb2_mkdir,
.mkdir_setinfo = smb2_mkdir_setinfo,
.rmdir = smb2_rmdir,
.unlink = smb2_unlink,
.rename = smb2_rename_path,
.create_hardlink = smb2_create_hardlink,
.query_symlink = smb2_query_symlink,
.query_mf_symlink = smb3_query_mf_symlink,
.create_mf_symlink = smb3_create_mf_symlink,
.open = smb2_open_file,
.set_fid = smb2_set_fid,
.close = smb2_close_file,
.flush = smb2_flush_file,
.async_readv = smb2_async_readv,
.async_writev = smb2_async_writev,
.sync_read = smb2_sync_read,
.sync_write = smb2_sync_write,
.query_dir_first = smb2_query_dir_first,
.query_dir_next = smb2_query_dir_next,
.close_dir = smb2_close_dir,
.calc_smb_size = smb2_calc_size,
.is_status_pending = smb2_is_status_pending,
.oplock_response = smb2_oplock_response,
.queryfs = smb2_queryfs,
.mand_lock = smb2_mand_lock,
.mand_unlock_range = smb2_unlock_range,
.push_mand_locks = smb2_push_mandatory_locks,
.get_lease_key = smb2_get_lease_key,
.set_lease_key = smb2_set_lease_key,
.new_lease_key = smb2_new_lease_key,
.calc_signature = smb2_calc_signature,
.is_read_op = smb21_is_read_op,
.set_oplock_level = smb21_set_oplock_level,
.create_lease_buf = smb2_create_lease_buf,
.parse_lease_buf = smb2_parse_lease_buf,
.clone_range = smb2_clone_range,
.wp_retry_size = smb2_wp_retry_size,
.dir_needs_close = smb2_dir_needs_close,
};
struct smb_version_operations smb30_operations = {
.compare_fids = smb2_compare_fids,
.setup_request = smb2_setup_request,
.setup_async_request = smb2_setup_async_request,
.check_receive = smb2_check_receive,
.add_credits = smb2_add_credits,
.set_credits = smb2_set_credits,
.get_credits_field = smb2_get_credits_field,
.get_credits = smb2_get_credits,
.wait_mtu_credits = smb2_wait_mtu_credits,
.get_next_mid = smb2_get_next_mid,
.read_data_offset = smb2_read_data_offset,
.read_data_length = smb2_read_data_length,
.map_error = map_smb2_to_linux_error,
.find_mid = smb2_find_mid,
.check_message = smb2_check_message,
.dump_detail = smb2_dump_detail,
.clear_stats = smb2_clear_stats,
.print_stats = smb2_print_stats,
.dump_share_caps = smb2_dump_share_caps,
.is_oplock_break = smb2_is_valid_oplock_break,
.downgrade_oplock = smb2_downgrade_oplock,
.need_neg = smb2_need_neg,
.negotiate = smb2_negotiate,
.negotiate_wsize = smb2_negotiate_wsize,
.negotiate_rsize = smb2_negotiate_rsize,
.sess_setup = SMB2_sess_setup,
.logoff = SMB2_logoff,
.tree_connect = SMB2_tcon,
.tree_disconnect = SMB2_tdis,
.qfs_tcon = smb3_qfs_tcon,
.is_path_accessible = smb2_is_path_accessible,
.can_echo = smb2_can_echo,
.echo = SMB2_echo,
.query_path_info = smb2_query_path_info,
.get_srv_inum = smb2_get_srv_inum,
.query_file_info = smb2_query_file_info,
.set_path_size = smb2_set_path_size,
.set_file_size = smb2_set_file_size,
.set_file_info = smb2_set_file_info,
.set_compression = smb2_set_compression,
.mkdir = smb2_mkdir,
.mkdir_setinfo = smb2_mkdir_setinfo,
.rmdir = smb2_rmdir,
.unlink = smb2_unlink,
.rename = smb2_rename_path,
.create_hardlink = smb2_create_hardlink,
.query_symlink = smb2_query_symlink,
.query_mf_symlink = smb3_query_mf_symlink,
.create_mf_symlink = smb3_create_mf_symlink,
.open = smb2_open_file,
.set_fid = smb2_set_fid,
.close = smb2_close_file,
.flush = smb2_flush_file,
.async_readv = smb2_async_readv,
.async_writev = smb2_async_writev,
.sync_read = smb2_sync_read,
.sync_write = smb2_sync_write,
.query_dir_first = smb2_query_dir_first,
.query_dir_next = smb2_query_dir_next,
.close_dir = smb2_close_dir,
.calc_smb_size = smb2_calc_size,
.is_status_pending = smb2_is_status_pending,
.oplock_response = smb2_oplock_response,
.queryfs = smb2_queryfs,
.mand_lock = smb2_mand_lock,
.mand_unlock_range = smb2_unlock_range,
.push_mand_locks = smb2_push_mandatory_locks,
.get_lease_key = smb2_get_lease_key,
.set_lease_key = smb2_set_lease_key,
.new_lease_key = smb2_new_lease_key,
.generate_signingkey = generate_smb30signingkey,
.calc_signature = smb3_calc_signature,
.set_integrity = smb3_set_integrity,
.is_read_op = smb21_is_read_op,
.set_oplock_level = smb3_set_oplock_level,
.create_lease_buf = smb3_create_lease_buf,
.parse_lease_buf = smb3_parse_lease_buf,
.clone_range = smb2_clone_range,
.duplicate_extents = smb2_duplicate_extents,
.validate_negotiate = smb3_validate_negotiate,
.wp_retry_size = smb2_wp_retry_size,
.dir_needs_close = smb2_dir_needs_close,
.fallocate = smb3_fallocate,
};
#ifdef CONFIG_CIFS_SMB311
struct smb_version_operations smb311_operations = {
.compare_fids = smb2_compare_fids,
.setup_request = smb2_setup_request,
.setup_async_request = smb2_setup_async_request,
.check_receive = smb2_check_receive,
.add_credits = smb2_add_credits,
.set_credits = smb2_set_credits,
.get_credits_field = smb2_get_credits_field,
.get_credits = smb2_get_credits,
.wait_mtu_credits = smb2_wait_mtu_credits,
.get_next_mid = smb2_get_next_mid,
.read_data_offset = smb2_read_data_offset,
.read_data_length = smb2_read_data_length,
.map_error = map_smb2_to_linux_error,
.find_mid = smb2_find_mid,
.check_message = smb2_check_message,
.dump_detail = smb2_dump_detail,
.clear_stats = smb2_clear_stats,
.print_stats = smb2_print_stats,
.dump_share_caps = smb2_dump_share_caps,
.is_oplock_break = smb2_is_valid_oplock_break,
.downgrade_oplock = smb2_downgrade_oplock,
.need_neg = smb2_need_neg,
.negotiate = smb2_negotiate,
.negotiate_wsize = smb2_negotiate_wsize,
.negotiate_rsize = smb2_negotiate_rsize,
.sess_setup = SMB2_sess_setup,
.logoff = SMB2_logoff,
.tree_connect = SMB2_tcon,
.tree_disconnect = SMB2_tdis,
.qfs_tcon = smb3_qfs_tcon,
.is_path_accessible = smb2_is_path_accessible,
.can_echo = smb2_can_echo,
.echo = SMB2_echo,
.query_path_info = smb2_query_path_info,
.get_srv_inum = smb2_get_srv_inum,
.query_file_info = smb2_query_file_info,
.set_path_size = smb2_set_path_size,
.set_file_size = smb2_set_file_size,
.set_file_info = smb2_set_file_info,
.set_compression = smb2_set_compression,
.mkdir = smb2_mkdir,
.mkdir_setinfo = smb2_mkdir_setinfo,
.rmdir = smb2_rmdir,
.unlink = smb2_unlink,
.rename = smb2_rename_path,
.create_hardlink = smb2_create_hardlink,
.query_symlink = smb2_query_symlink,
.query_mf_symlink = smb3_query_mf_symlink,
.create_mf_symlink = smb3_create_mf_symlink,
.open = smb2_open_file,
.set_fid = smb2_set_fid,
.close = smb2_close_file,
.flush = smb2_flush_file,
.async_readv = smb2_async_readv,
.async_writev = smb2_async_writev,
.sync_read = smb2_sync_read,
.sync_write = smb2_sync_write,
.query_dir_first = smb2_query_dir_first,
.query_dir_next = smb2_query_dir_next,
.close_dir = smb2_close_dir,
.calc_smb_size = smb2_calc_size,
.is_status_pending = smb2_is_status_pending,
.oplock_response = smb2_oplock_response,
.queryfs = smb2_queryfs,
.mand_lock = smb2_mand_lock,
.mand_unlock_range = smb2_unlock_range,
.push_mand_locks = smb2_push_mandatory_locks,
.get_lease_key = smb2_get_lease_key,
.set_lease_key = smb2_set_lease_key,
.new_lease_key = smb2_new_lease_key,
.generate_signingkey = generate_smb311signingkey,
.calc_signature = smb3_calc_signature,
.set_integrity = smb3_set_integrity,
.is_read_op = smb21_is_read_op,
.set_oplock_level = smb3_set_oplock_level,
.create_lease_buf = smb3_create_lease_buf,
.parse_lease_buf = smb3_parse_lease_buf,
.clone_range = smb2_clone_range,
.duplicate_extents = smb2_duplicate_extents,
/* .validate_negotiate = smb3_validate_negotiate, */ /* not used in 3.11 */
.wp_retry_size = smb2_wp_retry_size,
.dir_needs_close = smb2_dir_needs_close,
.fallocate = smb3_fallocate,
};
#endif /* CIFS_SMB311 */
struct smb_version_values smb20_values = {
.version_string = SMB20_VERSION_STRING,
.protocol_id = SMB20_PROT_ID,
.req_capabilities = 0, /* MBZ */
.large_lock_type = 0,
.exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE_LOCK,
.shared_lock_type = SMB2_LOCKFLAG_SHARED_LOCK,
.unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
.header_size = sizeof(struct smb2_hdr),
.max_header_size = MAX_SMB2_HDR_SIZE,
.read_rsp_size = sizeof(struct smb2_read_rsp) - 1,
.lock_cmd = SMB2_LOCK,
.cap_unix = 0,
.cap_nt_find = SMB2_NT_FIND,
.cap_large_files = SMB2_LARGE_FILES,
.signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
.signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
.create_lease_size = sizeof(struct create_lease),
};
struct smb_version_values smb21_values = {
.version_string = SMB21_VERSION_STRING,
.protocol_id = SMB21_PROT_ID,
.req_capabilities = 0, /* MBZ on negotiate req until SMB3 dialect */
.large_lock_type = 0,
.exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE_LOCK,
.shared_lock_type = SMB2_LOCKFLAG_SHARED_LOCK,
.unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
.header_size = sizeof(struct smb2_hdr),
.max_header_size = MAX_SMB2_HDR_SIZE,
.read_rsp_size = sizeof(struct smb2_read_rsp) - 1,
.lock_cmd = SMB2_LOCK,
.cap_unix = 0,
.cap_nt_find = SMB2_NT_FIND,
.cap_large_files = SMB2_LARGE_FILES,
.signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
.signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
.create_lease_size = sizeof(struct create_lease),
};
struct smb_version_values smb30_values = {
.version_string = SMB30_VERSION_STRING,
.protocol_id = SMB30_PROT_ID,
.req_capabilities = SMB2_GLOBAL_CAP_DFS | SMB2_GLOBAL_CAP_LEASING | SMB2_GLOBAL_CAP_LARGE_MTU | SMB2_GLOBAL_CAP_PERSISTENT_HANDLES | SMB2_GLOBAL_CAP_ENCRYPTION,
.large_lock_type = 0,
.exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE_LOCK,
.shared_lock_type = SMB2_LOCKFLAG_SHARED_LOCK,
.unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
.header_size = sizeof(struct smb2_hdr),
.max_header_size = MAX_SMB2_HDR_SIZE,
.read_rsp_size = sizeof(struct smb2_read_rsp) - 1,
.lock_cmd = SMB2_LOCK,
.cap_unix = 0,
.cap_nt_find = SMB2_NT_FIND,
.cap_large_files = SMB2_LARGE_FILES,
.signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
.signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
.create_lease_size = sizeof(struct create_lease_v2),
};
struct smb_version_values smb302_values = {
.version_string = SMB302_VERSION_STRING,
.protocol_id = SMB302_PROT_ID,
.req_capabilities = SMB2_GLOBAL_CAP_DFS | SMB2_GLOBAL_CAP_LEASING | SMB2_GLOBAL_CAP_LARGE_MTU | SMB2_GLOBAL_CAP_PERSISTENT_HANDLES | SMB2_GLOBAL_CAP_ENCRYPTION,
.large_lock_type = 0,
.exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE_LOCK,
.shared_lock_type = SMB2_LOCKFLAG_SHARED_LOCK,
.unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
.header_size = sizeof(struct smb2_hdr),
.max_header_size = MAX_SMB2_HDR_SIZE,
.read_rsp_size = sizeof(struct smb2_read_rsp) - 1,
.lock_cmd = SMB2_LOCK,
.cap_unix = 0,
.cap_nt_find = SMB2_NT_FIND,
.cap_large_files = SMB2_LARGE_FILES,
.signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
.signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
.create_lease_size = sizeof(struct create_lease_v2),
};
#ifdef CONFIG_CIFS_SMB311
struct smb_version_values smb311_values = {
.version_string = SMB311_VERSION_STRING,
.protocol_id = SMB311_PROT_ID,
.req_capabilities = SMB2_GLOBAL_CAP_DFS | SMB2_GLOBAL_CAP_LEASING | SMB2_GLOBAL_CAP_LARGE_MTU | SMB2_GLOBAL_CAP_PERSISTENT_HANDLES,
.large_lock_type = 0,
.exclusive_lock_type = SMB2_LOCKFLAG_EXCLUSIVE_LOCK,
.shared_lock_type = SMB2_LOCKFLAG_SHARED_LOCK,
.unlock_lock_type = SMB2_LOCKFLAG_UNLOCK,
.header_size = sizeof(struct smb2_hdr),
.max_header_size = MAX_SMB2_HDR_SIZE,
.read_rsp_size = sizeof(struct smb2_read_rsp) - 1,
.lock_cmd = SMB2_LOCK,
.cap_unix = 0,
.cap_nt_find = SMB2_NT_FIND,
.cap_large_files = SMB2_LARGE_FILES,
.signing_enabled = SMB2_NEGOTIATE_SIGNING_ENABLED | SMB2_NEGOTIATE_SIGNING_REQUIRED,
.signing_required = SMB2_NEGOTIATE_SIGNING_REQUIRED,
.create_lease_size = sizeof(struct create_lease_v2),
};
#endif /* SMB311 */
|
693380.c | /*
********************************************************************************
*
* GSM AMR-NB speech codec R98 Version 7.6.0 December 12, 2001
* R99 Version 3.3.0
* REL-4 Version 4.1.0
*
********************************************************************************
*
* File : c3_14pf.c
* Purpose : Searches a 14 bit algebraic codebook containing 3 pulses
* in a frame of 40 samples.
*
********************************************************************************
*/
/*
********************************************************************************
* MODULE INCLUDE FILE AND VERSION ID
********************************************************************************
*/
#include "c3_14pf.h"
const char c3_14pf_id[] = "@(#)$Id $" c3_14pf_h;
/*
********************************************************************************
* INCLUDE FILES
********************************************************************************
*/
#include "typedef.h"
#include "basic_op.h"
#include "count.h"
#include "inv_sqrt.h"
#include "cnst.h"
#include "cor_h.h"
#include "set_sign.h"
/*
********************************************************************************
* LOCAL VARIABLES AND TABLES
********************************************************************************
*/
#define NB_PULSE 3
/*
********************************************************************************
* DECLARATION OF PROTOTYPES
********************************************************************************
*/
static void search_3i40(
Word16 dn[], /* i : correlation between target and h[] */
Word16 dn2[], /* i : maximum of corr. in each track. */
Word16 rr[][L_CODE],/* i : matrix of autocorrelation */
Word16 codvec[] /* o : algebraic codebook vector */
);
static Word16 build_code(
Word16 codvec[], /* i : algebraic codebook vector */
Word16 dn_sign[], /* i : sign of dn[] */
Word16 cod[], /* o : algebraic (fixed) codebook excitation */
Word16 h[], /* i : impulse response of weighted synthesis filter */
Word16 y[], /* o : filtered fixed codebook excitation */
Word16 sign[] /* o : sign of 3 pulses */
);
/*
********************************************************************************
* PUBLIC PROGRAM CODE
********************************************************************************
*/
/*************************************************************************
*
* FUNCTION: code_3i40_14bits()
*
* PURPOSE: Searches a 14 bit algebraic codebook containing 3 pulses
* in a frame of 40 samples.
*
* DESCRIPTION:
* The code length is 40, containing 3 nonzero pulses: i0...i2.
* All pulses can have two possible amplitudes: +1 or -1.
* Pulse i0 can have 8 possible positions, pulses i1 and i2 can have
* 2x8=16 positions.
*
* i0 : 0, 5, 10, 15, 20, 25, 30, 35.
* i1 : 1, 6, 11, 16, 21, 26, 31, 36.
* 3, 8, 13, 18, 23, 28, 33, 38.
* i2 : 2, 7, 12, 17, 22, 27, 32, 37.
* 4, 9, 14, 19, 24, 29, 34, 39.
*
*************************************************************************/
Word16 code_3i40_14bits(
Word16 x[], /* i : target vector */
Word16 h[], /* i : impulse response of weighted synthesis filter */
/* h[-L_subfr..-1] must be set to zero. */
Word16 T0, /* i : Pitch lag */
Word16 pitch_sharp, /* i : Last quantized pitch gain */
Word16 code[], /* o : Innovative codebook */
Word16 y[], /* o : filtered fixed codebook excitation */
Word16 * sign /* o : Signs of 3 pulses */
)
{
Word16 codvec[NB_PULSE];
Word16 dn[L_CODE], dn2[L_CODE], dn_sign[L_CODE];
Word16 rr[L_CODE][L_CODE];
Word16 i, index, sharp;
sharp = shl(pitch_sharp, 1);
test ();
if (sub(T0, L_CODE) < 0)
{
for (i = T0; i < L_CODE; i++) {
h[i] = add(h[i], mult(h[i - T0], sharp)); move16 ();
}
}
cor_h_x(h, x, dn, 1);
set_sign(dn, dn_sign, dn2, 6);
cor_h(h, dn_sign, rr);
search_3i40(dn, dn2, rr, codvec);
move16 (); /* function result */
index = build_code(codvec, dn_sign, code, h, y, sign);
/*-----------------------------------------------------------------*
* Compute innovation vector gain. *
* Include fixed-gain pitch contribution into code[]. *
*-----------------------------------------------------------------*/
test ();
if (sub(T0, L_CODE) < 0)
{
for (i = T0; i < L_CODE; i++) {
code[i] = add(code[i], mult(code[i - T0], sharp)); move16 ();
}
}
return index;
}
/*
********************************************************************************
* PRIVATE PROGRAM CODE
********************************************************************************
*/
/*************************************************************************
*
* FUNCTION search_3i40()
*
* PURPOSE: Search the best codevector; determine positions of the 3 pulses
* in the 40-sample frame.
*
*************************************************************************/
#define _1_2 (Word16)(32768L/2)
#define _1_4 (Word16)(32768L/4)
#define _1_8 (Word16)(32768L/8)
#define _1_16 (Word16)(32768L/16)
static void search_3i40(
Word16 dn[], /* i : correlation between target and h[] */
Word16 dn2[], /* i : maximum of corr. in each track. */
Word16 rr[][L_CODE], /* i : matrix of autocorrelation */
Word16 codvec[] /* o : algebraic codebook vector */
)
{
Word16 i0, i1, i2;
Word16 ix = 0; /* initialization only needed to keep gcc silent */
Word16 ps = 0; /* initialization only needed to keep gcc silent */
Word16 i, pos, track1, track2, ipos[NB_PULSE];
Word16 psk, ps0, ps1, sq, sq1;
Word16 alpk, alp, alp_16;
Word32 s, alp0, alp1;
psk = -1; move16 ();
alpk = 1; move16 ();
for (i = 0; i < NB_PULSE; i++)
{
codvec[i] = i; move16 ();
}
for (track1 = 1; track1 < 4; track1 += 2)
{
for (track2 = 2; track2 < 5; track2 += 2)
{
/* fix starting position */
ipos[0] = 0; move16 ();
ipos[1] = track1; move16 ();
ipos[2] = track2; move16 ();
/*------------------------------------------------------------------*
* main loop: try 3 tracks. *
*------------------------------------------------------------------*/
for (i = 0; i < NB_PULSE; i++)
{
/*----------------------------------------------------------------*
* i0 loop: try 8 positions. *
*----------------------------------------------------------------*/
move16 (); /* account for ptr. init. (rr[io]) */
for (i0 = ipos[0]; i0 < L_CODE; i0 += STEP)
{
test ();
if (dn2[i0] >= 0)
{
ps0 = dn[i0]; move16 ();
alp0 = L_mult(rr[i0][i0], _1_4);
/*----------------------------------------------------------------*
* i1 loop: 8 positions. *
*----------------------------------------------------------------*/
sq = -1; move16 ();
alp = 1; move16 ();
ps = 0; move16 ();
ix = ipos[1]; move16 ();
/* initialize 4 index for next loop. */
/*-------------------------------------------------------------------*
* These index have low complexity address computation because *
* they are, in fact, pointers with fixed increment. For example, *
* "rr[i0][i2]" is a pointer initialized to "&rr[i0][ipos[2]]" *
* and incremented by "STEP". *
*-------------------------------------------------------------------*/
move16 (); /* account for ptr. init. (rr[i1]) */
move16 (); /* account for ptr. init. (dn[i1]) */
move16 (); /* account for ptr. init. (rr[io]) */
for (i1 = ipos[1]; i1 < L_CODE; i1 += STEP)
{
ps1 = add(ps0, dn[i1]); /* idx increment = STEP */
/* alp1 = alp0 + rr[i0][i1] + 1/2*rr[i1][i1]; */
alp1 = L_mac(alp0, rr[i1][i1], _1_4); /* idx incr = STEP */
alp1 = L_mac(alp1, rr[i0][i1], _1_2); /* idx incr = STEP */
sq1 = mult(ps1, ps1);
alp_16 = round(alp1);
s = L_msu(L_mult(alp, sq1), sq, alp_16);
test ();
if (s > 0)
{
sq = sq1; move16 ();
ps = ps1; move16 ();
alp = alp_16; move16 ();
ix = i1; move16 ();
}
}
i1 = ix; move16 ();
/*----------------------------------------------------------------*
* i2 loop: 8 positions. *
*----------------------------------------------------------------*/
ps0 = ps; move16 ();
alp0 = L_mult(alp, _1_4);
sq = -1; move16 ();
alp = 1; move16 ();
ps = 0; move16 ();
ix = ipos[2]; move16 ();
/* initialize 4 index for next loop (see i1 loop) */
move16 (); /* account for ptr. init. (rr[i2]) */
move16 (); /* account for ptr. init. (rr[i1]) */
move16 (); /* account for ptr. init. (dn[i2]) */
move16 (); /* account for ptr. init. (rr[io]) */
for (i2 = ipos[2]; i2 < L_CODE; i2 += STEP)
{
ps1 = add(ps0, dn[i2]); /* index increment = STEP */
/* alp1 = alp0 + rr[i0][i2] + rr[i1][i2] + 1/2*rr[i2][i2]; */
alp1 = L_mac(alp0, rr[i2][i2], _1_16); /* idx incr = STEP */
alp1 = L_mac(alp1, rr[i1][i2], _1_8); /* idx incr = STEP */
alp1 = L_mac(alp1, rr[i0][i2], _1_8); /* idx incr = STEP */
sq1 = mult(ps1, ps1);
alp_16 = round(alp1);
s = L_msu(L_mult(alp, sq1), sq, alp_16);
test ();
if (s > 0)
{
sq = sq1; move16 ();
ps = ps1; move16 ();
alp = alp_16; move16 ();
ix = i2; move16 ();
}
}
i2 = ix; move16 ();
/*----------------------------------------------------------------*
* memorise codevector if this one is better than the last one. *
*----------------------------------------------------------------*/
s = L_msu(L_mult(alpk, sq), psk, alp);
test ();
if (s > 0)
{
psk = sq; move16 ();
alpk = alp; move16 ();
codvec[0] = i0; move16 ();
codvec[1] = i1; move16 ();
codvec[2] = i2; move16 ();
}
}
}
/*----------------------------------------------------------------*
* Cyclic permutation of i0, i1 and i2. *
*----------------------------------------------------------------*/
pos = ipos[2]; move16 ();
ipos[2] = ipos[1]; move16 ();
ipos[1] = ipos[0]; move16 ();
ipos[0] = pos; move16 ();
}
}
}
return;
}
/*************************************************************************
*
* FUNCTION: build_code()
*
* PURPOSE: Builds the codeword, the filtered codeword and index of the
* codevector, based on the signs and positions of 3 pulses.
*
*************************************************************************/
static Word16
build_code(
Word16 codvec[], /* i : position of pulses */
Word16 dn_sign[], /* i : sign of pulses */
Word16 cod[], /* o : innovative code vector */
Word16 h[], /* i : impulse response of weighted synthesis filter */
Word16 y[], /* o : filtered innovative code */
Word16 sign[] /* o : sign of 3 pulses */
)
{
Word16 i, j, k, track, index, _sign[NB_PULSE], indx, rsign;
Word16 *p0, *p1, *p2;
Word32 s;
for (i = 0; i < L_CODE; i++) {
cod[i] = 0; move16 ();
}
indx = 0; move16 ();
rsign = 0; move16 ();
for (k = 0; k < NB_PULSE; k++)
{
i = codvec[k]; move16 (); /* read pulse position */
j = dn_sign[i]; move16 (); /* read sign */
index = mult(i, 6554); /* index = pos/5 */
/* track = pos%5 */
track = sub(i, extract_l(L_shr(L_mult(index, 5), 1)));
test ();
if (sub(track, 1) == 0)
index = shl(index, 4);
else if (sub(track, 2) == 0)
{
test ();
track = 2; move16 ();
index = shl(index, 8);
}
else if (sub(track, 3) == 0)
{
test (); test ();
track = 1; move16 ();
index = add(shl(index, 4), 8);
}
else if (sub(track, 4) == 0)
{
test (); test (); test ();
track = 2; move16 ();
index = add(shl(index, 8), 128);
}
test ();
if (j > 0)
{
cod[i] = 8191; move16 ();
_sign[k] = 32767; move16 ();
rsign = add(rsign, shl(1, track));
} else {
cod[i] = -8192; move16 ();
_sign[k] = (Word16) - 32768L; move16 ();
}
indx = add(indx, index);
}
*sign = rsign; move16 ();
p0 = h - codvec[0]; move16 ();
p1 = h - codvec[1]; move16 ();
p2 = h - codvec[2]; move16 ();
for (i = 0; i < L_CODE; i++)
{
s = 0; move32 ();
s = L_mac(s, *p0++, _sign[0]);
s = L_mac(s, *p1++, _sign[1]);
s = L_mac(s, *p2++, _sign[2]);
y[i] = round(s); move16 ();
}
return indx;
}
|
392855.c | /****************************************************************************
* boards/arm/stm32l5/stm32l562e-dk/src/stm32_autoleds.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 <stdbool.h>
#include <debug.h>
#include <nuttx/board.h>
#include "chip.h"
#include "arm_arch.h"
#include "arm_internal.h"
#include "stm32l5_gpio.h"
#include "stm32l562e-dk.h"
#include <arch/board/board.h>
#ifdef CONFIG_ARCH_LEDS
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
#define ARRAYSIZE(x) (sizeof((x)) / sizeof((x)[0]))
/****************************************************************************
* Private Data
****************************************************************************/
/* Indexed by BOARD_LED_<color> */
static const uint32_t g_ledmap[BOARD_NLEDS] =
{
GPIO_LD10,
GPIO_LD9,
};
/****************************************************************************
* Private Functions
****************************************************************************/
static void phy_set_led(int led, bool state)
{
/* Active Low */
stm32l5_gpiowrite(g_ledmap[led], !state);
}
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: board_autoled_initialize
****************************************************************************/
void board_autoled_initialize(void)
{
int i;
/* Configure the LD9 and LD10 GPIOs for output. Initial state is OFF */
for (i = 0; i < ARRAYSIZE(g_ledmap); i++)
{
stm32l5_configgpio(g_ledmap[i]);
}
}
/****************************************************************************
* Name: board_autoled_on
****************************************************************************/
void board_autoled_on(int led)
{
switch (led)
{
default:
break;
case LED_HEAPALLOCATE:
phy_set_led(BOARD_LED_RED, true);
phy_set_led(BOARD_LED_GREEN, false);
break;
case LED_IRQSENABLED:
phy_set_led(BOARD_LED_RED, true);
phy_set_led(BOARD_LED_GREEN, true);
break;
case LED_STACKCREATED:
phy_set_led(BOARD_LED_RED, false);
phy_set_led(BOARD_LED_GREEN, true);
break;
case LED_INIRQ:
phy_set_led(BOARD_LED_RED, true);
break;
case LED_SIGNAL:
phy_set_led(BOARD_LED_RED, true);
break;
case LED_ASSERTION:
phy_set_led(BOARD_LED_RED, true);
break;
case LED_PANIC:
phy_set_led(BOARD_LED_RED, true);
phy_set_led(BOARD_LED_GREEN, false);
break;
case LED_IDLE:
phy_set_led(BOARD_LED_GREEN, true);
break;
}
}
/****************************************************************************
* Name: board_autoled_off
****************************************************************************/
void board_autoled_off(int led)
{
switch (led)
{
default:
break;
case LED_SIGNAL:
phy_set_led(BOARD_LED_RED, false);
break;
case LED_INIRQ:
phy_set_led(BOARD_LED_RED, false);
break;
case LED_ASSERTION:
phy_set_led(BOARD_LED_RED, false);
break;
case LED_PANIC:
phy_set_led(BOARD_LED_RED, false);
phy_set_led(BOARD_LED_GREEN, false);
break;
case LED_IDLE:
phy_set_led(BOARD_LED_GREEN, false);
break;
}
}
#endif /* CONFIG_ARCH_LEDS */
|
869111.c | void __errno_location() {} ;
void __h_errno_location() {} ;
void __libc_current_sigrtmax() {} ;
void __libc_current_sigrtmin() {} ;
void _pthread_cleanup_pop() {} ;
void _pthread_cleanup_push() {} ;
void accept() {} ;
void close() {} ;
void connect() {} ;
void fcntl() {} ;
void flockfile() {} ;
void fork() {} ;
void fsync() {} ;
void ftrylockfile() {} ;
void funlockfile() {} ;
void longjmp() {} ;
void lseek() {} ;
void lseek64() {} ;
void msync() {} ;
void nanosleep() {} ;
void open() {} ;
void open64() {} ;
void pause() {} ;
void pread() {} ;
void pread64() {} ;
void pthread_attr_destroy() {} ;
void pthread_attr_getdetachstate() {} ;
void pthread_attr_getguardsize() {} ;
void pthread_attr_getinheritsched() {} ;
void pthread_attr_getschedparam() {} ;
void pthread_attr_getschedpolicy() {} ;
void pthread_attr_getscope() {} ;
void pthread_attr_getstack() {} ;
void pthread_attr_getstackaddr() {} ;
void pthread_attr_getstacksize() {} ;
void pthread_attr_init() {} ;
void pthread_attr_setdetachstate() {} ;
void pthread_attr_setguardsize() {} ;
void pthread_attr_setinheritsched() {} ;
void pthread_attr_setschedparam() {} ;
void pthread_attr_setschedpolicy() {} ;
void pthread_attr_setscope() {} ;
void pthread_attr_setstack() {} ;
void pthread_attr_setstackaddr() {} ;
void pthread_attr_setstacksize() {} ;
void pthread_barrier_destroy() {} ;
void pthread_barrier_init() {} ;
void pthread_barrier_wait() {} ;
void pthread_barrierattr_destroy() {} ;
void pthread_barrierattr_getpshared() {} ;
void pthread_barrierattr_init() {} ;
void pthread_barrierattr_setpshared() {} ;
void pthread_cancel() {} ;
void pthread_cond_broadcast() {} ;
void pthread_cond_destroy() {} ;
void pthread_cond_init() {} ;
void pthread_cond_signal() {} ;
void pthread_cond_timedwait() {} ;
void pthread_cond_wait() {} ;
void pthread_condattr_destroy() {} ;
void pthread_condattr_getpshared() {} ;
void pthread_condattr_init() {} ;
void pthread_condattr_setpshared() {} ;
void pthread_create() {} ;
void pthread_detach() {} ;
void pthread_equal() {} ;
void pthread_exit() {} ;
void pthread_getattr_np() {} ;
void pthread_getconcurrency() {} ;
void pthread_getcpuclockid() {} ;
void pthread_getschedparam() {} ;
void pthread_getspecific() {} ;
void pthread_join() {} ;
void pthread_key_create() {} ;
void pthread_key_delete() {} ;
void pthread_kill() {} ;
void pthread_mutex_consistent_np() {} ;
void pthread_mutex_destroy() {} ;
void pthread_mutex_getprioceiling() {} ;
void pthread_mutex_init() {} ;
void pthread_mutex_lock() {} ;
void pthread_mutex_setprioceiling() {} ;
void pthread_mutex_timedlock() {} ;
void pthread_mutex_trylock() {} ;
void pthread_mutex_unlock() {} ;
void pthread_mutexattr_destroy() {} ;
void pthread_mutexattr_getprioceiling() {} ;
void pthread_mutexattr_getprotocol() {} ;
void pthread_mutexattr_getpshared() {} ;
void pthread_mutexattr_getrobust_np() {} ;
void pthread_mutexattr_gettype() {} ;
void pthread_mutexattr_init() {} ;
void pthread_mutexattr_setprioceiling() {} ;
void pthread_mutexattr_setprotocol() {} ;
void pthread_mutexattr_setpshared() {} ;
void pthread_mutexattr_setrobust_np() {} ;
void pthread_mutexattr_settype() {} ;
void pthread_once() {} ;
void pthread_rwlock_destroy() {} ;
void pthread_rwlock_init() {} ;
void pthread_rwlock_rdlock() {} ;
void pthread_rwlock_timedrdlock() {} ;
void pthread_rwlock_timedwrlock() {} ;
void pthread_rwlock_tryrdlock() {} ;
void pthread_rwlock_trywrlock() {} ;
void pthread_rwlock_unlock() {} ;
void pthread_rwlock_wrlock() {} ;
void pthread_rwlockattr_destroy() {} ;
void pthread_rwlockattr_getkind_np() {} ;
void pthread_rwlockattr_getpshared() {} ;
void pthread_rwlockattr_init() {} ;
void pthread_rwlockattr_setkind_np() {} ;
void pthread_rwlockattr_setpshared() {} ;
void pthread_self() {} ;
void pthread_setcancelstate() {} ;
void pthread_setcanceltype() {} ;
void pthread_setconcurrency() {} ;
void pthread_setschedparam() {} ;
void pthread_setschedprio() {} ;
void pthread_setspecific() {} ;
void pthread_sigmask() {} ;
void pthread_spin_destroy() {} ;
void pthread_spin_init() {} ;
void pthread_spin_lock() {} ;
void pthread_spin_trylock() {} ;
void pthread_spin_unlock() {} ;
void pthread_testcancel() {} ;
void pwrite() {} ;
void pwrite64() {} ;
void raise() {} ;
void read() {} ;
void recv() {} ;
void recvfrom() {} ;
void recvmsg() {} ;
void sem_close() {} ;
void sem_destroy() {} ;
void sem_getvalue() {} ;
void sem_init() {} ;
void sem_open() {} ;
void sem_post() {} ;
void sem_timedwait() {} ;
void sem_trywait() {} ;
void sem_unlink() {} ;
void sem_wait() {} ;
void send() {} ;
void sendmsg() {} ;
void sendto() {} ;
void sigaction() {} ;
void siglongjmp() {} ;
void sigwait() {} ;
void system() {} ;
void tcdrain() {} ;
void vfork() {} ;
void wait() {} ;
void waitpid() {} ;
void write() {} ;
|
692008.c | /*
** $Id: lparser.c,v 2.178 2018/02/17 19:20:00 roberto Exp roberto $
** Lua Parser
** See Copyright Notice in lua.h
*/
#define lparser_c
#define LUA_CORE
#include "lprefix.h"
#include <string.h>
#include "lua.h"
#include "lcode.h"
#include "ldebug.h"
#include "ldo.h"
#include "lfunc.h"
#include "llex.h"
#include "lmem.h"
#include "lobject.h"
#include "lopcodes.h"
#include "lparser.h"
#include "lstate.h"
#include "lstring.h"
#include "ltable.h"
/* maximum number of local variables per function (must be smaller
than 250, due to the bytecode format) */
#define MAXVARS 200
#define hasmultret(k) ((k) == VCALL || (k) == VVARARG)
/* because all strings are unified by the scanner, the parser
can use pointer equality for string equality */
#define eqstr(a,b) ((a) == (b))
/*
** nodes for block list (list of active blocks)
*/
typedef struct BlockCnt {
struct BlockCnt *previous; /* chain */
int firstlabel; /* index of first label in this block */
int firstgoto; /* index of first pending goto in this block */
int brks; /* list of break jumps in this block */
lu_byte brkcls; /* true if some 'break' needs to close upvalues */
lu_byte nactvar; /* # active locals outside the block */
lu_byte upval; /* true if some variable in the block is an upvalue */
lu_byte isloop; /* true if 'block' is a loop */
} BlockCnt;
/*
** prototypes for recursive non-terminal functions
*/
static void statement (LexState *ls);
static void expr (LexState *ls, expdesc *v);
static l_noret error_expected (LexState *ls, int token) {
luaX_syntaxerror(ls,
luaO_pushfstring(ls->L, "%s expected", luaX_token2str(ls, token)));
}
static l_noret errorlimit (FuncState *fs, int limit, const char *what) {
lua_State *L = fs->ls->L;
const char *msg;
int line = fs->f->linedefined;
const char *where = (line == 0)
? "main function"
: luaO_pushfstring(L, "function at line %d", line);
msg = luaO_pushfstring(L, "too many %s (limit is %d) in %s",
what, limit, where);
luaX_syntaxerror(fs->ls, msg);
}
static void checklimit (FuncState *fs, int v, int l, const char *what) {
if (v > l) errorlimit(fs, l, what);
}
static int testnext (LexState *ls, int c) {
if (ls->t.token == c) {
luaX_next(ls);
return 1;
}
else return 0;
}
static void check (LexState *ls, int c) {
if (ls->t.token != c)
error_expected(ls, c);
}
static void checknext (LexState *ls, int c) {
check(ls, c);
luaX_next(ls);
}
#define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); }
static void check_match (LexState *ls, int what, int who, int where) {
if (!testnext(ls, what)) {
if (where == ls->linenumber)
error_expected(ls, what);
else {
luaX_syntaxerror(ls, luaO_pushfstring(ls->L,
"%s expected (to close %s at line %d)",
luaX_token2str(ls, what), luaX_token2str(ls, who), where));
}
}
}
static TString *str_checkname (LexState *ls) {
TString *ts;
check(ls, TK_NAME);
ts = ls->t.seminfo.ts;
luaX_next(ls);
return ts;
}
static void init_exp (expdesc *e, expkind k, int i) {
e->f = e->t = NO_JUMP;
e->k = k;
e->u.info = i;
}
static void codestring (LexState *ls, expdesc *e, TString *s) {
init_exp(e, VK, luaK_stringK(ls->fs, s));
}
static void checkname (LexState *ls, expdesc *e) {
codestring(ls, e, str_checkname(ls));
}
static int registerlocalvar (LexState *ls, TString *varname) {
FuncState *fs = ls->fs;
Proto *f = fs->f;
int oldsize = f->sizelocvars;
luaM_growvector(ls->L, f->locvars, fs->nlocvars, f->sizelocvars,
LocVar, SHRT_MAX, "local variables");
while (oldsize < f->sizelocvars)
f->locvars[oldsize++].varname = NULL;
f->locvars[fs->nlocvars].varname = varname;
luaC_objbarrier(ls->L, f, varname);
return fs->nlocvars++;
}
static void new_localvar (LexState *ls, TString *name) {
FuncState *fs = ls->fs;
Dyndata *dyd = ls->dyd;
int reg = registerlocalvar(ls, name);
checklimit(fs, dyd->actvar.n + 1 - fs->firstlocal,
MAXVARS, "local variables");
luaM_growvector(ls->L, dyd->actvar.arr, dyd->actvar.n + 1,
dyd->actvar.size, Vardesc, MAX_INT, "local variables");
dyd->actvar.arr[dyd->actvar.n++].idx = cast(short, reg);
}
static void new_localvarliteral_ (LexState *ls, const char *name, size_t sz) {
new_localvar(ls, luaX_newstring(ls, name, sz));
}
#define new_localvarliteral(ls,v) \
new_localvarliteral_(ls, "" v, (sizeof(v)/sizeof(char))-1)
static LocVar *getlocvar (FuncState *fs, int i) {
int idx = fs->ls->dyd->actvar.arr[fs->firstlocal + i].idx;
lua_assert(idx < fs->nlocvars);
return &fs->f->locvars[idx];
}
static void adjustlocalvars (LexState *ls, int nvars) {
FuncState *fs = ls->fs;
fs->nactvar = cast_byte(fs->nactvar + nvars);
for (; nvars; nvars--) {
getlocvar(fs, fs->nactvar - nvars)->startpc = fs->pc;
}
}
static void removevars (FuncState *fs, int tolevel) {
fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel);
while (fs->nactvar > tolevel)
getlocvar(fs, --fs->nactvar)->endpc = fs->pc;
}
static int searchupvalue (FuncState *fs, TString *name) {
int i;
Upvaldesc *up = fs->f->upvalues;
for (i = 0; i < fs->nups; i++) {
if (eqstr(up[i].name, name)) return i;
}
return -1; /* not found */
}
static int newupvalue (FuncState *fs, TString *name, expdesc *v) {
Proto *f = fs->f;
int oldsize = f->sizeupvalues;
checklimit(fs, fs->nups + 1, MAXUPVAL, "upvalues");
luaM_growvector(fs->ls->L, f->upvalues, fs->nups, f->sizeupvalues,
Upvaldesc, MAXUPVAL, "upvalues");
while (oldsize < f->sizeupvalues)
f->upvalues[oldsize++].name = NULL;
f->upvalues[fs->nups].instack = (v->k == VLOCAL);
f->upvalues[fs->nups].idx = cast_byte(v->u.info);
f->upvalues[fs->nups].name = name;
luaC_objbarrier(fs->ls->L, f, name);
return fs->nups++;
}
static int searchvar (FuncState *fs, TString *n) {
int i;
for (i = cast_int(fs->nactvar) - 1; i >= 0; i--) {
if (eqstr(n, getlocvar(fs, i)->varname))
return i;
}
return -1; /* not found */
}
/*
Mark block where variable at given level was defined
(to emit close instructions later).
*/
static void markupval (FuncState *fs, int level) {
BlockCnt *bl = fs->bl;
while (bl->nactvar > level)
bl = bl->previous;
bl->upval = 1;
}
/*
Find variable with given name 'n'. If it is an upvalue, add this
upvalue into all intermediate functions.
*/
static void singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {
if (fs == NULL) /* no more levels? */
init_exp(var, VVOID, 0); /* default is global */
else {
int v = searchvar(fs, n); /* look up locals at current level */
if (v >= 0) { /* found? */
init_exp(var, VLOCAL, v); /* variable is local */
if (!base)
markupval(fs, v); /* local will be used as an upval */
}
else { /* not found as local at current level; try upvalues */
int idx = searchupvalue(fs, n); /* try existing upvalues */
if (idx < 0) { /* not found? */
singlevaraux(fs->prev, n, var, 0); /* try upper levels */
if (var->k == VVOID) /* not found? */
return; /* it is a global */
/* else was LOCAL or UPVAL */
idx = newupvalue(fs, n, var); /* will be a new upvalue */
}
init_exp(var, VUPVAL, idx); /* new or old upvalue */
}
}
}
static void singlevar (LexState *ls, expdesc *var) {
TString *varname = str_checkname(ls);
FuncState *fs = ls->fs;
singlevaraux(fs, varname, var, 1);
if (var->k == VVOID) { /* global name? */
expdesc key;
singlevaraux(fs, ls->envn, var, 1); /* get environment variable */
lua_assert(var->k != VVOID); /* this one must exist */
codestring(ls, &key, varname); /* key is variable name */
luaK_indexed(fs, var, &key); /* env[varname] */
}
}
static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) {
FuncState *fs = ls->fs;
int extra = nvars - nexps;
if (hasmultret(e->k)) {
extra++; /* includes call itself */
if (extra < 0) extra = 0;
luaK_setreturns(fs, e, extra); /* last exp. provides the difference */
if (extra > 1) luaK_reserveregs(fs, extra-1);
}
else {
if (e->k != VVOID) luaK_exp2nextreg(fs, e); /* close last expression */
if (extra > 0) {
int reg = fs->freereg;
luaK_reserveregs(fs, extra);
luaK_nil(fs, reg, extra);
}
}
if (nexps > nvars)
ls->fs->freereg -= nexps - nvars; /* remove extra values */
}
#define enterlevel(ls) luaE_incCcalls((ls)->L)
#define leavelevel(ls) ((ls)->L->nCcalls--)
static void closegoto (LexState *ls, int g, Labeldesc *label) {
int i;
FuncState *fs = ls->fs;
Labellist *gl = &ls->dyd->gt;
Labeldesc *gt = &gl->arr[g];
lua_assert(eqstr(gt->name, label->name));
if (gt->nactvar < label->nactvar) {
TString *vname = getlocvar(fs, gt->nactvar)->varname;
const char *msg = luaO_pushfstring(ls->L,
"<goto %s> at line %d jumps into the scope of local '%s'",
getstr(gt->name), gt->line, getstr(vname));
luaK_semerror(ls, msg);
}
luaK_patchgoto(fs, gt->pc, label->pc, 1);
/* remove goto from pending list */
for (i = g; i < gl->n - 1; i++)
gl->arr[i] = gl->arr[i + 1];
gl->n--;
}
/*
** try to close a goto with existing labels; this solves backward jumps
*/
static int solvelabel (LexState *ls, int g) {
int i;
BlockCnt *bl = ls->fs->bl;
Dyndata *dyd = ls->dyd;
Labeldesc *gt = &dyd->gt.arr[g];
/* check labels in current block for a match */
for (i = bl->firstlabel; i < dyd->label.n; i++) {
Labeldesc *lb = &dyd->label.arr[i];
if (eqstr(lb->name, gt->name)) { /* correct label? */
if (gt->nactvar > lb->nactvar &&
(bl->upval || dyd->label.n > bl->firstlabel))
luaK_patchclose(ls->fs, gt->pc);
closegoto(ls, g, lb); /* close it */
return 1;
}
}
return 0; /* label not found; cannot close goto */
}
static int newlabelentry (LexState *ls, Labellist *l, TString *name,
int line, int pc) {
int n = l->n;
luaM_growvector(ls->L, l->arr, n, l->size,
Labeldesc, SHRT_MAX, "labels/gotos");
l->arr[n].name = name;
l->arr[n].line = line;
l->arr[n].nactvar = ls->fs->nactvar;
l->arr[n].pc = pc;
l->n = n + 1;
return n;
}
/*
** check whether new label 'lb' matches any pending gotos in current
** block; solves forward jumps
*/
static void solvegotos (LexState *ls, Labeldesc *lb) {
Labellist *gl = &ls->dyd->gt;
int i = ls->fs->bl->firstgoto;
while (i < gl->n) {
if (eqstr(gl->arr[i].name, lb->name))
closegoto(ls, i, lb); /* will remove 'i' from the list */
else
i++;
}
}
/*
** export pending gotos to outer level, to check them against
** outer labels; if the block being exited has upvalues, and
** the goto exits the scope of any variable (which can be the
** upvalue), close those variables being exited. Also export
** break list.
*/
static void movegotosout (FuncState *fs, BlockCnt *bl) {
int i = bl->firstgoto;
Labellist *gl = &fs->ls->dyd->gt;
/* correct pending gotos to current block and try to close it
with visible labels */
while (i < gl->n) { /* for each pending goto */
Labeldesc *gt = &gl->arr[i];
if (gt->nactvar > bl->nactvar) { /* leaving a variable scope? */
if (bl->upval) /* variable may be an upvalue? */
luaK_patchclose(fs, gt->pc); /* jump will need a close */
gt->nactvar = bl->nactvar; /* update goto level */
}
if (!solvelabel(fs->ls, i))
i++; /* move to next one */
/* else, 'solvelabel' removed current goto from the list
and 'i' now points to next one */
}
/* handles break list */
if (bl->upval) /* exiting the scope of an upvalue? */
luaK_patchclose(fs, bl->brks); /* breaks will need OP_CLOSE */
/* move breaks to outer block */
luaK_concat(fs, &bl->previous->brks, bl->brks);
bl->previous->brkcls |= bl->brkcls;
}
static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isloop) {
bl->isloop = isloop;
bl->nactvar = fs->nactvar;
bl->firstlabel = fs->ls->dyd->label.n;
bl->firstgoto = fs->ls->dyd->gt.n;
bl->brks = NO_JUMP;
bl->brkcls = 0;
bl->upval = 0;
bl->previous = fs->bl;
fs->bl = bl;
lua_assert(fs->freereg == fs->nactvar);
}
/*
** Fix all breaks in block 'bl' to jump to the end of the block.
*/
static void fixbreaks (FuncState *fs, BlockCnt *bl) {
int target = fs->pc;
if (bl->brkcls) /* does the block need to close upvalues? */
luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
luaK_patchgoto(fs, bl->brks, target, bl->brkcls);
bl->brks = NO_JUMP; /* no more breaks to fix */
bl->brkcls = 0; /* no more need to close upvalues */
lua_assert(!bl->upval); /* loop body cannot have local variables */
}
/*
** generates an error for an undefined 'goto'.
*/
static l_noret undefgoto (LexState *ls, Labeldesc *gt) {
const char *msg = "no visible label '%s' for <goto> at line %d";
msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line);
luaK_semerror(ls, msg);
}
static void leaveblock (FuncState *fs) {
BlockCnt *bl = fs->bl;
LexState *ls = fs->ls;
if (bl->upval && bl->brks != NO_JUMP) /* breaks in upvalue scopes? */
bl->brkcls = 1; /* these breaks must close the upvalues */
if (bl->isloop)
fixbreaks(fs, bl); /* fix pending breaks */
if (bl->previous && bl->upval)
luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
fs->bl = bl->previous;
removevars(fs, bl->nactvar);
lua_assert(bl->nactvar == fs->nactvar);
fs->freereg = fs->nactvar; /* free registers */
ls->dyd->label.n = bl->firstlabel; /* remove local labels */
if (bl->previous) /* inner block? */
movegotosout(fs, bl); /* update pending gotos to outer block */
else {
lua_assert(bl->brks == NO_JUMP); /* no pending breaks */
if (bl->firstgoto < ls->dyd->gt.n) /* pending gotos in outer block? */
undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]); /* error */
}
}
/*
** adds a new prototype into list of prototypes
*/
static Proto *addprototype (LexState *ls) {
Proto *clp;
lua_State *L = ls->L;
FuncState *fs = ls->fs;
Proto *f = fs->f; /* prototype of current function */
if (fs->np >= f->sizep) {
int oldsize = f->sizep;
luaM_growvector(L, f->p, fs->np, f->sizep, Proto *, MAXARG_Bx, "functions");
while (oldsize < f->sizep)
f->p[oldsize++] = NULL;
}
f->p[fs->np++] = clp = luaF_newproto(L);
luaC_objbarrier(L, f, clp);
return clp;
}
/*
** codes instruction to create new closure in parent function.
** The OP_CLOSURE instruction must use the last available register,
** so that, if it invokes the GC, the GC knows which registers
** are in use at that time.
*/
static void codeclosure (LexState *ls, expdesc *v) {
FuncState *fs = ls->fs->prev;
init_exp(v, VRELOC, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np - 1));
luaK_exp2nextreg(fs, v); /* fix it at the last register */
}
static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) {
Proto *f = fs->f;
fs->prev = ls->fs; /* linked list of funcstates */
fs->ls = ls;
ls->fs = fs;
fs->pc = 0;
fs->previousline = f->linedefined;
fs->iwthabs = 0;
fs->lasttarget = 0;
fs->freereg = 0;
fs->nk = 0;
fs->nabslineinfo = 0;
fs->np = 0;
fs->nups = 0;
fs->nlocvars = 0;
fs->nactvar = 0;
fs->firstlocal = ls->dyd->actvar.n;
fs->bl = NULL;
f->source = ls->source;
f->maxstacksize = 2; /* registers 0/1 are always valid */
enterblock(fs, bl, 0);
}
static void close_func (LexState *ls) {
lua_State *L = ls->L;
FuncState *fs = ls->fs;
Proto *f = fs->f;
luaK_ret(fs, 0, 0); /* final return */
leaveblock(fs);
lua_assert(fs->bl == NULL);
luaK_finish(fs);
luaM_shrinkvector(L, f->code, f->sizecode, fs->pc, Instruction);
luaM_shrinkvector(L, f->lineinfo, f->sizelineinfo, fs->pc, ls_byte);
luaM_shrinkvector(L, f->abslineinfo, f->sizeabslineinfo,
fs->nabslineinfo, AbsLineInfo);
luaM_shrinkvector(L, f->k, f->sizek, fs->nk, TValue);
luaM_shrinkvector(L, f->p, f->sizep, fs->np, Proto *);
luaM_shrinkvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar);
luaM_shrinkvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc);
ls->fs = fs->prev;
luaC_checkGC(L);
}
/*============================================================*/
/* GRAMMAR RULES */
/*============================================================*/
/*
** check whether current token is in the follow set of a block.
** 'until' closes syntactical blocks, but do not close scope,
** so it is handled in separate.
*/
static int block_follow (LexState *ls, int withuntil) {
switch (ls->t.token) {
case TK_ELSE: case TK_ELSEIF:
case TK_END: case TK_EOS:
return 1;
case TK_UNTIL: return withuntil;
default: return 0;
}
}
static void statlist (LexState *ls) {
/* statlist -> { stat [';'] } */
while (!block_follow(ls, 1)) {
if (ls->t.token == TK_RETURN) {
statement(ls);
return; /* 'return' must be last statement */
}
statement(ls);
}
}
static void fieldsel (LexState *ls, expdesc *v) {
/* fieldsel -> ['.' | ':'] NAME */
FuncState *fs = ls->fs;
expdesc key;
luaK_exp2anyregup(fs, v);
luaX_next(ls); /* skip the dot or colon */
checkname(ls, &key);
luaK_indexed(fs, v, &key);
}
static void yindex (LexState *ls, expdesc *v) {
/* index -> '[' expr ']' */
luaX_next(ls); /* skip the '[' */
expr(ls, v);
luaK_exp2val(ls->fs, v);
checknext(ls, ']');
}
/*
** {======================================================================
** Rules for Constructors
** =======================================================================
*/
struct ConsControl {
expdesc v; /* last list item read */
expdesc *t; /* table descriptor */
int nh; /* total number of 'record' elements */
int na; /* total number of array elements */
int tostore; /* number of array elements pending to be stored */
};
static void recfield (LexState *ls, struct ConsControl *cc) {
/* recfield -> (NAME | '['exp']') = exp */
FuncState *fs = ls->fs;
int reg = ls->fs->freereg;
expdesc tab, key, val;
if (ls->t.token == TK_NAME) {
checklimit(fs, cc->nh, MAX_INT, "items in a constructor");
checkname(ls, &key);
}
else /* ls->t.token == '[' */
yindex(ls, &key);
cc->nh++;
checknext(ls, '=');
tab = *cc->t;
luaK_indexed(fs, &tab, &key);
expr(ls, &val);
luaK_storevar(fs, &tab, &val);
fs->freereg = reg; /* free registers */
}
static void closelistfield (FuncState *fs, struct ConsControl *cc) {
if (cc->v.k == VVOID) return; /* there is no list item */
luaK_exp2nextreg(fs, &cc->v);
cc->v.k = VVOID;
if (cc->tostore == LFIELDS_PER_FLUSH) {
luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); /* flush */
cc->tostore = 0; /* no more items pending */
}
}
static void lastlistfield (FuncState *fs, struct ConsControl *cc) {
if (cc->tostore == 0) return;
if (hasmultret(cc->v.k)) {
luaK_setmultret(fs, &cc->v);
luaK_setlist(fs, cc->t->u.info, cc->na, LUA_MULTRET);
cc->na--; /* do not count last expression (unknown number of elements) */
}
else {
if (cc->v.k != VVOID)
luaK_exp2nextreg(fs, &cc->v);
luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore);
}
}
static void listfield (LexState *ls, struct ConsControl *cc) {
/* listfield -> exp */
expr(ls, &cc->v);
checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor");
cc->na++;
cc->tostore++;
}
static void field (LexState *ls, struct ConsControl *cc) {
/* field -> listfield | recfield */
switch(ls->t.token) {
case TK_NAME: { /* may be 'listfield' or 'recfield' */
if (luaX_lookahead(ls) != '=') /* expression? */
listfield(ls, cc);
else
recfield(ls, cc);
break;
}
case '[': {
recfield(ls, cc);
break;
}
default: {
listfield(ls, cc);
break;
}
}
}
static void constructor (LexState *ls, expdesc *t) {
/* constructor -> '{' [ field { sep field } [sep] ] '}'
sep -> ',' | ';' */
FuncState *fs = ls->fs;
int line = ls->linenumber;
int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
struct ConsControl cc;
cc.na = cc.nh = cc.tostore = 0;
cc.t = t;
init_exp(t, VRELOC, pc);
init_exp(&cc.v, VVOID, 0); /* no value (yet) */
luaK_exp2nextreg(ls->fs, t); /* fix it at stack top */
checknext(ls, '{');
do {
lua_assert(cc.v.k == VVOID || cc.tostore > 0);
if (ls->t.token == '}') break;
closelistfield(fs, &cc);
field(ls, &cc);
} while (testnext(ls, ',') || testnext(ls, ';'));
check_match(ls, '}', '{', line);
lastlistfield(fs, &cc);
SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */
SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh)); /* set initial table size */
}
/* }====================================================================== */
static void setvararg (FuncState *fs, int nparams) {
fs->f->is_vararg = 1;
luaK_codeABC(fs, OP_PREPVARARG, nparams, 0, 0);
}
static void parlist (LexState *ls) {
/* parlist -> [ param { ',' param } ] */
FuncState *fs = ls->fs;
Proto *f = fs->f;
int nparams = 0;
int isvararg = 0;
if (ls->t.token != ')') { /* is 'parlist' not empty? */
do {
switch (ls->t.token) {
case TK_NAME: { /* param -> NAME */
new_localvar(ls, str_checkname(ls));
nparams++;
break;
}
case TK_DOTS: { /* param -> '...' */
luaX_next(ls);
isvararg = 1;
break;
}
default: luaX_syntaxerror(ls, "<name> or '...' expected");
}
} while (!isvararg && testnext(ls, ','));
}
adjustlocalvars(ls, nparams);
f->numparams = cast_byte(fs->nactvar);
if (isvararg)
setvararg(fs, f->numparams); /* declared vararg */
luaK_reserveregs(fs, fs->nactvar); /* reserve registers for parameters */
}
static void body (LexState *ls, expdesc *e, int ismethod, int line) {
/* body -> '(' parlist ')' block END */
FuncState new_fs;
BlockCnt bl;
new_fs.f = addprototype(ls);
new_fs.f->linedefined = line;
open_func(ls, &new_fs, &bl);
checknext(ls, '(');
if (ismethod) {
new_localvarliteral(ls, "self"); /* create 'self' parameter */
adjustlocalvars(ls, 1);
}
parlist(ls);
checknext(ls, ')');
statlist(ls);
new_fs.f->lastlinedefined = ls->linenumber;
check_match(ls, TK_END, TK_FUNCTION, line);
codeclosure(ls, e);
close_func(ls);
}
static int explist (LexState *ls, expdesc *v) {
/* explist -> expr { ',' expr } */
int n = 1; /* at least one expression */
expr(ls, v);
while (testnext(ls, ',')) {
luaK_exp2nextreg(ls->fs, v);
expr(ls, v);
n++;
}
return n;
}
static void funcargs (LexState *ls, expdesc *f, int line) {
FuncState *fs = ls->fs;
expdesc args;
int base, nparams;
switch (ls->t.token) {
case '(': { /* funcargs -> '(' [ explist ] ')' */
luaX_next(ls);
if (ls->t.token == ')') /* arg list is empty? */
args.k = VVOID;
else {
explist(ls, &args);
luaK_setmultret(fs, &args);
}
check_match(ls, ')', '(', line);
break;
}
case '{': { /* funcargs -> constructor */
constructor(ls, &args);
break;
}
case TK_STRING: { /* funcargs -> STRING */
codestring(ls, &args, ls->t.seminfo.ts);
luaX_next(ls); /* must use 'seminfo' before 'next' */
break;
}
default: {
luaX_syntaxerror(ls, "function arguments expected");
}
}
lua_assert(f->k == VNONRELOC);
base = f->u.info; /* base register for call */
if (hasmultret(args.k))
nparams = LUA_MULTRET; /* open call */
else {
if (args.k != VVOID)
luaK_exp2nextreg(fs, &args); /* close last argument */
nparams = fs->freereg - (base+1);
}
init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));
luaK_fixline(fs, line);
fs->freereg = base+1; /* call remove function and arguments and leaves
(unless changed) one result */
}
/*
** {======================================================================
** Expression parsing
** =======================================================================
*/
static void primaryexp (LexState *ls, expdesc *v) {
/* primaryexp -> NAME | '(' expr ')' */
switch (ls->t.token) {
case '(': {
int line = ls->linenumber;
luaX_next(ls);
expr(ls, v);
check_match(ls, ')', '(', line);
luaK_dischargevars(ls->fs, v);
return;
}
case TK_NAME: {
singlevar(ls, v);
return;
}
case TK_UNDEF: {
luaX_next(ls);
init_exp(v, VUNDEF, 0);
return;
}
default: {
luaX_syntaxerror(ls, "unexpected symbol");
}
}
}
static void suffixedexp (LexState *ls, expdesc *v) {
/* suffixedexp ->
primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */
FuncState *fs = ls->fs;
int line = ls->linenumber;
primaryexp(ls, v);
for (;;) {
switch (ls->t.token) {
case '.': { /* fieldsel */
fieldsel(ls, v);
break;
}
case '[': { /* '[' exp ']' */
expdesc key;
luaK_exp2anyregup(fs, v);
yindex(ls, &key);
luaK_indexed(fs, v, &key);
break;
}
case ':': { /* ':' NAME funcargs */
expdesc key;
luaX_next(ls);
checkname(ls, &key);
luaK_self(fs, v, &key);
funcargs(ls, v, line);
break;
}
case '(': case TK_STRING: case '{': { /* funcargs */
luaK_exp2nextreg(fs, v);
funcargs(ls, v, line);
break;
}
default: return;
}
}
}
static void simpleexp (LexState *ls, expdesc *v) {
/* simpleexp -> FLT | INT | STRING | NIL | TRUE | FALSE | ... |
constructor | FUNCTION body | suffixedexp */
switch (ls->t.token) {
case TK_FLT: {
init_exp(v, VKFLT, 0);
v->u.nval = ls->t.seminfo.r;
break;
}
case TK_INT: {
init_exp(v, VKINT, 0);
v->u.ival = ls->t.seminfo.i;
break;
}
case TK_STRING: {
codestring(ls, v, ls->t.seminfo.ts);
break;
}
case TK_NIL: {
init_exp(v, VNIL, 0);
break;
}
case TK_TRUE: {
init_exp(v, VTRUE, 0);
break;
}
case TK_FALSE: {
init_exp(v, VFALSE, 0);
break;
}
case TK_DOTS: { /* vararg */
FuncState *fs = ls->fs;
check_condition(ls, fs->f->is_vararg,
"cannot use '...' outside a vararg function");
init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 0, 1));
break;
}
case '{': { /* constructor */
constructor(ls, v);
return;
}
case TK_FUNCTION: {
luaX_next(ls);
body(ls, v, 0, ls->linenumber);
return;
}
default: {
suffixedexp(ls, v);
return;
}
}
luaX_next(ls);
}
static UnOpr getunopr (int op) {
switch (op) {
case TK_NOT: return OPR_NOT;
case '-': return OPR_MINUS;
case '~': return OPR_BNOT;
case '#': return OPR_LEN;
default: return OPR_NOUNOPR;
}
}
static BinOpr getbinopr (int op) {
switch (op) {
case '+': return OPR_ADD;
case '-': return OPR_SUB;
case '*': return OPR_MUL;
case '%': return OPR_MOD;
case '^': return OPR_POW;
case '/': return OPR_DIV;
case TK_IDIV: return OPR_IDIV;
case '&': return OPR_BAND;
case '|': return OPR_BOR;
case '~': return OPR_BXOR;
case TK_SHL: return OPR_SHL;
case TK_SHR: return OPR_SHR;
case TK_CONCAT: return OPR_CONCAT;
case TK_NE: return OPR_NE;
case TK_EQ: return OPR_EQ;
case '<': return OPR_LT;
case TK_LE: return OPR_LE;
case '>': return OPR_GT;
case TK_GE: return OPR_GE;
case TK_AND: return OPR_AND;
case TK_OR: return OPR_OR;
default: return OPR_NOBINOPR;
}
}
static const struct {
lu_byte left; /* left priority for each binary operator */
lu_byte right; /* right priority */
} priority[] = { /* ORDER OPR */
{10, 10}, {10, 10}, /* '+' '-' */
{11, 11}, {11, 11}, /* '*' '%' */
{14, 13}, /* '^' (right associative) */
{11, 11}, {11, 11}, /* '/' '//' */
{6, 6}, {4, 4}, {5, 5}, /* '&' '|' '~' */
{7, 7}, {7, 7}, /* '<<' '>>' */
{9, 8}, /* '..' (right associative) */
{3, 3}, {3, 3}, {3, 3}, /* ==, <, <= */
{3, 3}, {3, 3}, {3, 3}, /* ~=, >, >= */
{2, 2}, {1, 1} /* and, or */
};
#define UNARY_PRIORITY 12 /* priority for unary operators */
/*
** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
** where 'binop' is any binary operator with a priority higher than 'limit'
*/
static BinOpr subexpr (LexState *ls, expdesc *v, int limit) {
BinOpr op;
UnOpr uop;
enterlevel(ls);
uop = getunopr(ls->t.token);
if (uop != OPR_NOUNOPR) {
int line = ls->linenumber;
luaX_next(ls);
subexpr(ls, v, UNARY_PRIORITY);
luaK_prefix(ls->fs, uop, v, line);
}
else simpleexp(ls, v);
/* expand while operators have priorities higher than 'limit' */
op = getbinopr(ls->t.token);
while (op != OPR_NOBINOPR && priority[op].left > limit) {
expdesc v2;
BinOpr nextop;
int line = ls->linenumber;
luaX_next(ls);
luaK_infix(ls->fs, op, v);
/* read sub-expression with higher priority */
nextop = subexpr(ls, &v2, priority[op].right);
luaK_posfix(ls->fs, op, v, &v2, line);
op = nextop;
}
leavelevel(ls);
return op; /* return first untreated operator */
}
static void expr (LexState *ls, expdesc *v) {
subexpr(ls, v, 0);
}
/* }==================================================================== */
/*
** {======================================================================
** Rules for Statements
** =======================================================================
*/
static void block (LexState *ls) {
/* block -> statlist */
FuncState *fs = ls->fs;
BlockCnt bl;
enterblock(fs, &bl, 0);
statlist(ls);
leaveblock(fs);
}
/*
** structure to chain all variables in the left-hand side of an
** assignment
*/
struct LHS_assign {
struct LHS_assign *prev;
expdesc v; /* variable (global, local, upvalue, or indexed) */
};
/*
** check whether, in an assignment to an upvalue/local variable, the
** upvalue/local variable is begin used in a previous assignment to a
** table. If so, save original upvalue/local value in a safe place and
** use this safe copy in the previous assignment.
*/
static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
FuncState *fs = ls->fs;
int extra = fs->freereg; /* eventual position to save local variable */
int conflict = 0;
for (; lh; lh = lh->prev) { /* check all previous assignments */
if (vkisindexed(lh->v.k)) { /* assignment to table field? */
if (lh->v.k == VINDEXUP) { /* is table an upvalue? */
if (v->k == VUPVAL && lh->v.u.ind.t == v->u.info) {
conflict = 1; /* table is the upvalue being assigned now */
lh->v.k = VINDEXSTR;
lh->v.u.ind.t = extra; /* assignment will use safe copy */
}
}
else { /* table is a register */
if (v->k == VLOCAL && lh->v.u.ind.t == v->u.info) {
conflict = 1; /* table is the local being assigned now */
lh->v.u.ind.t = extra; /* assignment will use safe copy */
}
/* is index the local being assigned? */
if (lh->v.k == VINDEXED && v->k == VLOCAL &&
lh->v.u.ind.idx == v->u.info) {
conflict = 1;
lh->v.u.ind.idx = extra; /* previous assignment will use safe copy */
}
}
}
}
if (conflict) {
/* copy upvalue/local value to a temporary (in position 'extra') */
OpCode op = (v->k == VLOCAL) ? OP_MOVE : OP_GETUPVAL;
luaK_codeABC(fs, op, extra, v->u.info, 0);
luaK_reserveregs(fs, 1);
}
}
static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) {
expdesc e;
check_condition(ls, vkisvar(lh->v.k), "syntax error");
if (testnext(ls, ',')) { /* assignment -> ',' suffixedexp assignment */
struct LHS_assign nv;
nv.prev = lh;
suffixedexp(ls, &nv.v);
if (!vkisindexed(nv.v.k))
check_conflict(ls, lh, &nv.v);
luaE_incCcalls(ls->L); /* control recursion depth */
assignment(ls, &nv, nvars+1);
ls->L->nCcalls--;
}
else { /* assignment -> '=' explist */
int nexps;
checknext(ls, '=');
if (nvars == 1 && testnext(ls, TK_UNDEF)) {
luaK_codeundef(ls->fs, &lh->v);
return;
}
nexps = explist(ls, &e);
if (nexps != nvars)
adjust_assign(ls, nvars, nexps, &e);
else {
luaK_setoneret(ls->fs, &e); /* close last expression */
luaK_storevar(ls->fs, &lh->v, &e);
return; /* avoid default */
}
}
init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */
luaK_storevar(ls->fs, &lh->v, &e);
}
static int cond (LexState *ls) {
/* cond -> exp */
expdesc v;
expr(ls, &v); /* read condition */
if (v.k == VNIL) v.k = VFALSE; /* 'falses' are all equal here */
luaK_goiftrue(ls->fs, &v);
return v.f;
}
static void gotostat (LexState *ls, int pc) {
int line = ls->linenumber;
int g;
luaX_next(ls); /* skip 'goto' */
g = newlabelentry(ls, &ls->dyd->gt, str_checkname(ls), line, pc);
solvelabel(ls, g); /* close it if label already defined */
}
static void breakstat (LexState *ls, int pc) {
FuncState *fs = ls->fs;
BlockCnt *bl = fs->bl;
luaX_next(ls); /* skip break */
while (bl && !bl->isloop) { bl = bl->previous; }
if (!bl)
luaX_syntaxerror(ls, "no loop to break");
luaK_concat(fs, &fs->bl->brks, pc);
}
/* check for repeated labels on the same block */
static void checkrepeated (FuncState *fs, Labellist *ll, TString *label) {
int i;
for (i = fs->bl->firstlabel; i < ll->n; i++) {
if (eqstr(label, ll->arr[i].name)) {
const char *msg = luaO_pushfstring(fs->ls->L,
"label '%s' already defined on line %d",
getstr(label), ll->arr[i].line);
luaK_semerror(fs->ls, msg);
}
}
}
/* skip no-op statements */
static void skipnoopstat (LexState *ls) {
while (ls->t.token == ';' || ls->t.token == TK_DBCOLON)
statement(ls);
}
static void labelstat (LexState *ls, TString *label, int line) {
/* label -> '::' NAME '::' */
FuncState *fs = ls->fs;
Labellist *ll = &ls->dyd->label;
int l; /* index of new label being created */
checkrepeated(fs, ll, label); /* check for repeated labels */
checknext(ls, TK_DBCOLON); /* skip double colon */
/* create new entry for this label */
l = newlabelentry(ls, ll, label, line, luaK_getlabel(fs));
luaK_codeABC(fs, OP_CLOSE, fs->nactvar, 0, 0);
skipnoopstat(ls); /* skip other no-op statements */
if (block_follow(ls, 0)) { /* label is last no-op statement in the block? */
/* assume that locals are already out of scope */
ll->arr[l].nactvar = fs->bl->nactvar;
}
solvegotos(ls, &ll->arr[l]);
}
static void whilestat (LexState *ls, int line) {
/* whilestat -> WHILE cond DO block END */
FuncState *fs = ls->fs;
int whileinit;
int condexit;
BlockCnt bl;
luaX_next(ls); /* skip WHILE */
whileinit = luaK_getlabel(fs);
condexit = cond(ls);
enterblock(fs, &bl, 1);
checknext(ls, TK_DO);
block(ls);
luaK_jumpto(fs, whileinit);
check_match(ls, TK_END, TK_WHILE, line);
leaveblock(fs);
luaK_patchtohere(fs, condexit); /* false conditions finish the loop */
}
static void repeatstat (LexState *ls, int line) {
/* repeatstat -> REPEAT block UNTIL cond */
int condexit;
FuncState *fs = ls->fs;
int repeat_init = luaK_getlabel(fs);
BlockCnt bl1, bl2;
enterblock(fs, &bl1, 1); /* loop block */
enterblock(fs, &bl2, 0); /* scope block */
luaX_next(ls); /* skip REPEAT */
statlist(ls);
check_match(ls, TK_UNTIL, TK_REPEAT, line);
condexit = cond(ls); /* read condition (inside scope block) */
if (bl2.upval) /* upvalues? */
luaK_patchclose(fs, condexit);
leaveblock(fs); /* finish scope */
if (bl2.upval) { /* upvalues? */
int exit = luaK_jump(fs); /* normal exit must jump over fix */
luaK_patchtohere(fs, condexit); /* repetition must close upvalues */
luaK_codeABC(fs, OP_CLOSE, bl2.nactvar, 0, 0);
condexit = luaK_jump(fs); /* repeat after closing upvalues */
luaK_patchtohere(fs, exit); /* normal exit comes to here */
}
luaK_patchlist(fs, condexit, repeat_init); /* close the loop */
leaveblock(fs); /* finish loop */
}
/*
** Read an expression and generate code to put its results in next
** stack slot. Return true if expression is a constant integer and,
** if 'i' is not-zero, its value is equal to 'i'.
**
*/
static int exp1 (LexState *ls, int i) {
expdesc e;
int res;
expr(ls, &e);
res = luaK_isKint(&e) && (i == 0 || i == e.u.ival);
luaK_exp2nextreg(ls->fs, &e);
lua_assert(e.k == VNONRELOC);
return res;
}
/*
** Fix for instruction at position 'pc' to jump to 'dest'.
** (Jump addresses are relative in Lua). 'back' true means
** a back jump.
*/
static void fixforjump (FuncState *fs, int pc, int dest, int back) {
Instruction *jmp = &fs->f->code[pc];
int offset = dest - (pc + 1);
if (back)
offset = -offset;
if (offset > MAXARG_Bx)
luaX_syntaxerror(fs->ls, "control structure too long");
SETARG_Bx(*jmp, offset);
}
/*
** Generate code for a 'for' loop. 'kind' can be zero (a common for
** loop), one (a basic for loop, with integer values and increment of
** 1), or two (a generic for loop).
*/
static void forbody (LexState *ls, int base, int line, int nvars, int kind) {
/* forbody -> DO block */
BlockCnt bl;
FuncState *fs = ls->fs;
int prep, endfor;
adjustlocalvars(ls, 3); /* control variables */
checknext(ls, TK_DO);
prep = (kind == 0) ? luaK_codeABx(fs, OP_FORPREP, base, 0)
: (kind == 1) ? luaK_codeABx(fs, OP_FORPREP1, base, 0)
: luaK_jump(fs);
enterblock(fs, &bl, 0); /* scope for declared variables */
adjustlocalvars(ls, nvars);
luaK_reserveregs(fs, nvars);
block(ls);
leaveblock(fs); /* end of scope for declared variables */
if (kind == 2) { /* generic for? */
luaK_patchtohere(fs, prep);
luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars);
luaK_fixline(fs, line);
endfor = luaK_codeABx(fs, OP_TFORLOOP, base + 2, 0);
}
else {
fixforjump(fs, prep, luaK_getlabel(fs), 0);
endfor = (kind == 0) ? luaK_codeABx(fs, OP_FORLOOP, base, 0)
: luaK_codeABx(fs, OP_FORLOOP1, base, 0);
}
fixforjump(fs, endfor, prep + 1, 1);
luaK_fixline(fs, line);
}
static void fornum (LexState *ls, TString *varname, int line) {
/* fornum -> NAME = exp,exp[,exp] forbody */
FuncState *fs = ls->fs;
int base = fs->freereg;
int basicfor = 1; /* true if it is a "basic" 'for' (integer + 1) */
new_localvarliteral(ls, "(for index)");
new_localvarliteral(ls, "(for limit)");
new_localvarliteral(ls, "(for step)");
new_localvar(ls, varname);
checknext(ls, '=');
if (!exp1(ls, 0)) /* initial value not an integer? */
basicfor = 0; /* not a basic 'for' */
checknext(ls, ',');
exp1(ls, 0); /* limit */
if (testnext(ls, ',')) {
if (!exp1(ls, 1)) /* optional step not 1? */
basicfor = 0; /* not a basic 'for' */
}
else { /* default step = 1 */
luaK_int(fs, fs->freereg, 1);
luaK_reserveregs(fs, 1);
}
forbody(ls, base, line, 1, basicfor);
}
static void forlist (LexState *ls, TString *indexname) {
/* forlist -> NAME {,NAME} IN explist forbody */
FuncState *fs = ls->fs;
expdesc e;
int nvars = 4; /* gen, state, control, plus at least one declared var */
int line;
int base = fs->freereg;
/* create control variables */
new_localvarliteral(ls, "(for generator)");
new_localvarliteral(ls, "(for state)");
new_localvarliteral(ls, "(for control)");
/* create declared variables */
new_localvar(ls, indexname);
while (testnext(ls, ',')) {
new_localvar(ls, str_checkname(ls));
nvars++;
}
checknext(ls, TK_IN);
line = ls->linenumber;
adjust_assign(ls, 3, explist(ls, &e), &e);
luaK_checkstack(fs, 3); /* extra space to call generator */
forbody(ls, base, line, nvars - 3, 2);
}
static void forstat (LexState *ls, int line) {
/* forstat -> FOR (fornum | forlist) END */
FuncState *fs = ls->fs;
TString *varname;
BlockCnt bl;
enterblock(fs, &bl, 1); /* scope for loop and control variables */
luaX_next(ls); /* skip 'for' */
varname = str_checkname(ls); /* first variable name */
switch (ls->t.token) {
case '=': fornum(ls, varname, line); break;
case ',': case TK_IN: forlist(ls, varname); break;
default: luaX_syntaxerror(ls, "'=' or 'in' expected");
}
check_match(ls, TK_END, TK_FOR, line);
leaveblock(fs); /* loop scope ('break' jumps to this point) */
}
static void test_then_block (LexState *ls, int *escapelist) {
/* test_then_block -> [IF | ELSEIF] cond THEN block */
BlockCnt bl;
FuncState *fs = ls->fs;
expdesc v;
int jf; /* instruction to skip 'then' code (if condition is false) */
luaX_next(ls); /* skip IF or ELSEIF */
expr(ls, &v); /* read condition */
checknext(ls, TK_THEN);
if (ls->t.token == TK_GOTO || ls->t.token == TK_BREAK) {
luaK_goiffalse(ls->fs, &v); /* will jump to label if condition is true */
enterblock(fs, &bl, 0); /* must enter block before 'goto' */
if (ls->t.token == TK_GOTO)
gotostat(ls, v.t); /* handle goto */
else
breakstat(ls, v.t); /* handle break */
while (testnext(ls, ';')) {} /* skip semicolons */
if (block_follow(ls, 0)) { /* 'goto'/'break' is the entire block? */
leaveblock(fs);
return; /* and that is it */
}
else /* must skip over 'then' part if condition is false */
jf = luaK_jump(fs);
}
else { /* regular case (not goto/break) */
luaK_goiftrue(ls->fs, &v); /* skip over block if condition is false */
enterblock(fs, &bl, 0);
jf = v.f;
}
statlist(ls); /* 'then' part */
leaveblock(fs);
if (ls->t.token == TK_ELSE ||
ls->t.token == TK_ELSEIF) /* followed by 'else'/'elseif'? */
luaK_concat(fs, escapelist, luaK_jump(fs)); /* must jump over it */
luaK_patchtohere(fs, jf);
}
static void ifstat (LexState *ls, int line) {
/* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
FuncState *fs = ls->fs;
int escapelist = NO_JUMP; /* exit list for finished parts */
test_then_block(ls, &escapelist); /* IF cond THEN block */
while (ls->t.token == TK_ELSEIF)
test_then_block(ls, &escapelist); /* ELSEIF cond THEN block */
if (testnext(ls, TK_ELSE))
block(ls); /* 'else' part */
check_match(ls, TK_END, TK_IF, line);
luaK_patchtohere(fs, escapelist); /* patch escape list to 'if' end */
}
static void localfunc (LexState *ls) {
expdesc b;
FuncState *fs = ls->fs;
new_localvar(ls, str_checkname(ls)); /* new local variable */
adjustlocalvars(ls, 1); /* enter its scope */
body(ls, &b, 0, ls->linenumber); /* function created in next register */
/* debug information will only see the variable after this point! */
getlocvar(fs, b.u.info)->startpc = fs->pc;
}
static void localstat (LexState *ls) {
/* stat -> LOCAL NAME {',' NAME} ['=' explist] */
int nvars = 0;
int nexps;
expdesc e;
do {
new_localvar(ls, str_checkname(ls));
nvars++;
} while (testnext(ls, ','));
if (testnext(ls, '='))
nexps = explist(ls, &e);
else {
e.k = VVOID;
nexps = 0;
}
adjust_assign(ls, nvars, nexps, &e);
adjustlocalvars(ls, nvars);
}
static int funcname (LexState *ls, expdesc *v) {
/* funcname -> NAME {fieldsel} [':' NAME] */
int ismethod = 0;
singlevar(ls, v);
while (ls->t.token == '.')
fieldsel(ls, v);
if (ls->t.token == ':') {
ismethod = 1;
fieldsel(ls, v);
}
return ismethod;
}
static void funcstat (LexState *ls, int line) {
/* funcstat -> FUNCTION funcname body */
int ismethod;
expdesc v, b;
luaX_next(ls); /* skip FUNCTION */
ismethod = funcname(ls, &v);
body(ls, &b, ismethod, line);
luaK_storevar(ls->fs, &v, &b);
luaK_fixline(ls->fs, line); /* definition "happens" in the first line */
}
static void exprstat (LexState *ls) {
/* stat -> func | assignment */
FuncState *fs = ls->fs;
struct LHS_assign v;
suffixedexp(ls, &v.v);
if (ls->t.token == '=' || ls->t.token == ',') { /* stat -> assignment ? */
v.prev = NULL;
assignment(ls, &v, 1);
}
else { /* stat -> func */
Instruction *inst = &getinstruction(fs, &v.v);
check_condition(ls, v.v.k == VCALL, "syntax error");
SETARG_C(*inst, 1); /* call statement uses no results */
}
}
static void retstat (LexState *ls) {
/* stat -> RETURN [explist] [';'] */
FuncState *fs = ls->fs;
expdesc e;
int first, nret; /* registers with returned values */
if (block_follow(ls, 1) || ls->t.token == ';')
first = nret = 0; /* return no values */
else {
nret = explist(ls, &e); /* optional return values */
if (hasmultret(e.k)) {
luaK_setmultret(fs, &e);
if (e.k == VCALL && nret == 1) { /* tail call? */
SET_OPCODE(getinstruction(fs,&e), OP_TAILCALL);
lua_assert(GETARG_A(getinstruction(fs,&e)) == fs->nactvar);
}
first = fs->nactvar;
nret = LUA_MULTRET; /* return all values */
}
else {
if (nret == 1) /* only one single value? */
first = luaK_exp2anyreg(fs, &e);
else {
luaK_exp2nextreg(fs, &e); /* values must go to the stack */
first = fs->nactvar; /* return all active values */
lua_assert(nret == fs->freereg - first);
}
}
}
luaK_ret(fs, first, nret);
testnext(ls, ';'); /* skip optional semicolon */
}
static void statement (LexState *ls) {
int line = ls->linenumber; /* may be needed for error messages */
enterlevel(ls);
switch (ls->t.token) {
case ';': { /* stat -> ';' (empty statement) */
luaX_next(ls); /* skip ';' */
break;
}
case TK_IF: { /* stat -> ifstat */
ifstat(ls, line);
break;
}
case TK_WHILE: { /* stat -> whilestat */
whilestat(ls, line);
break;
}
case TK_DO: { /* stat -> DO block END */
luaX_next(ls); /* skip DO */
block(ls);
check_match(ls, TK_END, TK_DO, line);
break;
}
case TK_FOR: { /* stat -> forstat */
forstat(ls, line);
break;
}
case TK_REPEAT: { /* stat -> repeatstat */
repeatstat(ls, line);
break;
}
case TK_FUNCTION: { /* stat -> funcstat */
funcstat(ls, line);
break;
}
case TK_LOCAL: { /* stat -> localstat */
luaX_next(ls); /* skip LOCAL */
if (testnext(ls, TK_FUNCTION)) /* local function? */
localfunc(ls);
else if (testnext(ls, TK_UNDEF))
(void)0; /* ignore */
/* old versions may need to declare 'local undef'
when using 'undef' with no environment; so this
version accepts (and ignores) these declarations */
else
localstat(ls);
break;
}
case TK_DBCOLON: { /* stat -> label */
luaX_next(ls); /* skip double colon */
labelstat(ls, str_checkname(ls), line);
break;
}
case TK_RETURN: { /* stat -> retstat */
luaX_next(ls); /* skip RETURN */
retstat(ls);
break;
}
case TK_BREAK: { /* stat -> breakstat */
breakstat(ls, luaK_jump(ls->fs));
break;
}
case TK_GOTO: { /* stat -> 'goto' NAME */
gotostat(ls, luaK_jump(ls->fs));
break;
}
default: { /* stat -> func | assignment */
exprstat(ls);
break;
}
}
lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
ls->fs->freereg >= ls->fs->nactvar);
ls->fs->freereg = ls->fs->nactvar; /* free registers */
leavelevel(ls);
}
/* }====================================================================== */
/*
** compiles the main function, which is a regular vararg function with an
** upvalue named LUA_ENV
*/
static void mainfunc (LexState *ls, FuncState *fs) {
BlockCnt bl;
expdesc v;
open_func(ls, fs, &bl);
setvararg(fs, 0); /* main function is always declared vararg */
init_exp(&v, VLOCAL, 0); /* create and... */
newupvalue(fs, ls->envn, &v); /* ...set environment upvalue */
luaX_next(ls); /* read first token */
statlist(ls); /* parse main body */
check(ls, TK_EOS);
close_func(ls);
}
LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
Dyndata *dyd, const char *name, int firstchar) {
LexState lexstate;
FuncState funcstate;
LClosure *cl = luaF_newLclosure(L, 1); /* create main closure */
setclLvalue2s(L, L->top, cl); /* anchor it (to avoid being collected) */
luaD_inctop(L);
lexstate.h = luaH_new(L); /* create table for scanner */
sethvalue2s(L, L->top, lexstate.h); /* anchor it */
luaD_inctop(L);
funcstate.f = cl->p = luaF_newproto(L);
funcstate.f->source = luaS_new(L, name); /* create and anchor TString */
lua_assert(iswhite(funcstate.f)); /* do not need barrier here */
lexstate.buff = buff;
lexstate.dyd = dyd;
dyd->actvar.n = dyd->gt.n = dyd->label.n = 0;
luaX_setinput(L, &lexstate, z, funcstate.f->source, firstchar);
mainfunc(&lexstate, &funcstate);
lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs);
/* all scopes should be correctly finished */
lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0);
L->top--; /* remove scanner's table */
return cl; /* closure is on the stack, too */
}
|
433494.c | /*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2012 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. |
+----------------------------------------------------------------------+
| Author: Rasmus Lerdorf <[email protected]> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#include <stdio.h>
#include "php.h"
#include "ext/standard/php_standard.h"
#include "ext/date/php_date.h"
#include "SAPI.h"
#include "php_main.h"
#include "head.h"
#ifdef TM_IN_SYS_TIME
#include <sys/time.h>
#else
#include <time.h>
#endif
#include "php_globals.h"
/* Implementation of the language Header() function */
/* {{{ proto void header(string header [, bool replace, [int http_response_code]])
Sends a raw HTTP header */
PHP_FUNCTION(header)
{
zend_bool rep = 1;
sapi_header_line ctr = {0};
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|bl", &ctr.line,
&ctr.line_len, &rep, &ctr.response_code) == FAILURE)
return;
sapi_header_op(rep ? SAPI_HEADER_REPLACE:SAPI_HEADER_ADD, &ctr TSRMLS_CC);
}
/* }}} */
/* {{{ proto void header_remove([string name])
Removes an HTTP header previously set using header() */
PHP_FUNCTION(header_remove)
{
sapi_header_line ctr = {0};
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &ctr.line,
&ctr.line_len) == FAILURE)
return;
sapi_header_op(ZEND_NUM_ARGS() == 0 ? SAPI_HEADER_DELETE_ALL : SAPI_HEADER_DELETE, &ctr TSRMLS_CC);
}
/* }}} */
PHPAPI int php_header(TSRMLS_D)
{
if (sapi_send_headers(TSRMLS_C)==FAILURE || SG(request_info).headers_only) {
return 0; /* don't allow output */
} else {
return 1; /* allow output */
}
}
PHPAPI int php_setcookie(char *name, int name_len, char *value, int value_len, time_t expires, char *path, int path_len, char *domain, int domain_len, int secure, int url_encode, int httponly TSRMLS_DC)
{
char *cookie, *encoded_value = NULL;
int len=sizeof("Set-Cookie: ");
char *dt;
sapi_header_line ctr = {0};
int result;
if (name && strpbrk(name, "=,; \t\r\n\013\014") != NULL) { /* man isspace for \013 and \014 */
zend_error( E_WARNING, "Cookie names cannot contain any of the following '=,; \\t\\r\\n\\013\\014'" );
return FAILURE;
}
if (!url_encode && value && strpbrk(value, ",; \t\r\n\013\014") != NULL) { /* man isspace for \013 and \014 */
zend_error( E_WARNING, "Cookie values cannot contain any of the following ',; \\t\\r\\n\\013\\014'" );
return FAILURE;
}
len += name_len;
if (value && url_encode) {
int encoded_value_len;
encoded_value = php_url_encode(value, value_len, &encoded_value_len);
len += encoded_value_len;
} else if ( value ) {
encoded_value = estrdup(value);
len += value_len;
}
if (path) {
len += path_len;
}
if (domain) {
len += domain_len;
}
cookie = emalloc(len + 100);
if (value && value_len == 0) {
/*
* MSIE doesn't delete a cookie when you set it to a null value
* so in order to force cookies to be deleted, even on MSIE, we
* pick an expiry date in the past
*/
dt = php_format_date("D, d-M-Y H:i:s T", sizeof("D, d-M-Y H:i:s T")-1, 1, 0 TSRMLS_CC);
snprintf(cookie, len + 100, "Set-Cookie: %s=deleted; expires=%s", name, dt);
efree(dt);
} else {
snprintf(cookie, len + 100, "Set-Cookie: %s=%s", name, value ? encoded_value : "");
if (expires > 0) {
const char *p;
strlcat(cookie, "; expires=", len + 100);
dt = php_format_date("D, d-M-Y H:i:s T", sizeof("D, d-M-Y H:i:s T")-1, expires, 0 TSRMLS_CC);
/* check to make sure that the year does not exceed 4 digits in length */
p = zend_memrchr(dt, '-', strlen(dt));
if (!p || *(p + 5) != ' ') {
efree(dt);
efree(cookie);
efree(encoded_value);
zend_error(E_WARNING, "Expiry date cannot have a year greater then 9999");
return FAILURE;
}
strlcat(cookie, dt, len + 100);
efree(dt);
}
}
if (encoded_value) {
efree(encoded_value);
}
if (path && path_len > 0) {
strlcat(cookie, "; path=", len + 100);
strlcat(cookie, path, len + 100);
}
if (domain && domain_len > 0) {
strlcat(cookie, "; domain=", len + 100);
strlcat(cookie, domain, len + 100);
}
if (secure) {
strlcat(cookie, "; secure", len + 100);
}
if (httponly) {
strlcat(cookie, "; httponly", len + 100);
}
ctr.line = cookie;
ctr.line_len = strlen(cookie);
result = sapi_header_op(SAPI_HEADER_ADD, &ctr TSRMLS_CC);
efree(cookie);
return result;
}
/* php_set_cookie(name, value, expires, path, domain, secure) */
/* {{{ proto bool setcookie(string name [, string value [, int expires [, string path [, string domain [, bool secure[, bool httponly]]]]]])
Send a cookie */
PHP_FUNCTION(setcookie)
{
char *name, *value = NULL, *path = NULL, *domain = NULL;
long expires = 0;
zend_bool secure = 0, httponly = 0;
int name_len, value_len = 0, path_len = 0, domain_len = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|slssbb", &name,
&name_len, &value, &value_len, &expires, &path,
&path_len, &domain, &domain_len, &secure, &httponly) == FAILURE) {
return;
}
if (php_setcookie(name, name_len, value, value_len, expires, path, path_len, domain, domain_len, secure, 1, httponly TSRMLS_CC) == SUCCESS) {
RETVAL_TRUE;
} else {
RETVAL_FALSE;
}
}
/* }}} */
/* {{{ proto bool setrawcookie(string name [, string value [, int expires [, string path [, string domain [, bool secure[, bool httponly]]]]]])
Send a cookie with no url encoding of the value */
PHP_FUNCTION(setrawcookie)
{
char *name, *value = NULL, *path = NULL, *domain = NULL;
long expires = 0;
zend_bool secure = 0, httponly = 0;
int name_len, value_len = 0, path_len = 0, domain_len = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|slssbb", &name,
&name_len, &value, &value_len, &expires, &path,
&path_len, &domain, &domain_len, &secure, &httponly) == FAILURE) {
return;
}
if (php_setcookie(name, name_len, value, value_len, expires, path, path_len, domain, domain_len, secure, 0, httponly TSRMLS_CC) == SUCCESS) {
RETVAL_TRUE;
} else {
RETVAL_FALSE;
}
}
/* }}} */
/* {{{ proto bool headers_sent([string &$file [, int &$line]])
Returns true if headers have already been sent, false otherwise */
PHP_FUNCTION(headers_sent)
{
zval *arg1 = NULL, *arg2 = NULL;
const char *file="";
int line=0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|zz", &arg1, &arg2) == FAILURE)
return;
if (SG(headers_sent)) {
line = php_output_get_start_lineno(TSRMLS_C);
file = php_output_get_start_filename(TSRMLS_C);
}
switch(ZEND_NUM_ARGS()) {
case 2:
zval_dtor(arg2);
ZVAL_LONG(arg2, line);
case 1:
zval_dtor(arg1);
if (file) {
ZVAL_STRING(arg1, file, 1);
} else {
ZVAL_STRING(arg1, "", 1);
}
break;
}
if (SG(headers_sent)) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
/* }}} */
/* {{{ php_head_apply_header_list_to_hash
Turn an llist of sapi_header_struct headers into a numerically indexed zval hash */
static void php_head_apply_header_list_to_hash(void *data, void *arg TSRMLS_DC)
{
sapi_header_struct *sapi_header = (sapi_header_struct *)data;
if (arg && sapi_header) {
add_next_index_string((zval *)arg, (char *)(sapi_header->header), 1);
}
}
/* {{{ proto array headers_list(void)
Return list of headers to be sent / already sent */
PHP_FUNCTION(headers_list)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (!&SG(sapi_headers).headers) {
RETURN_FALSE;
}
array_init(return_value);
zend_llist_apply_with_argument(&SG(sapi_headers).headers, php_head_apply_header_list_to_hash, return_value TSRMLS_CC);
}
/* }}} */
/* {{{ proto long http_response_code([int response_code])
Sets a response code, or returns the current HTTP response code */
PHP_FUNCTION(http_response_code)
{
long response_code = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &response_code) == FAILURE) {
return;
}
if (response_code)
{
long old_response_code;
old_response_code = SG(sapi_headers).http_response_code;
SG(sapi_headers).http_response_code = response_code;
if (old_response_code) {
RETURN_LONG(old_response_code);
}
RETURN_TRUE;
}
if (!SG(sapi_headers).http_response_code) {
RETURN_FALSE;
}
RETURN_LONG(SG(sapi_headers).http_response_code);
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4 * End:
*/
|
115807.c | /**
* Description:
* Author:created by bob on 17-12-20.
*/
//
#include <malloc.h>
#include <pthread.h>
#include <assert.h>
#include <unistd.h>
#include <asm/poll.h>
#include <poll.h>
#include <sys/socket.h>
#include "tcp_client.h"
#include "tcp_server.h"
#define tag "TCP_CLIENT"
static int udp_send_frame(int type, uint8_t *buf, uint32_t size, tcp_cli_t *client)
{
switch (type)
{
case TYPE_RTS_PCM:
rtp_pcm_send_frame(buf, size, client->media->sample);
break;
case TYPE_RTS_JPEG:
rtp_jpeg_send_frame(buf, size, client->media->width, client->media->height);
break;
case TYPE_RTS_H264:
rtp_h264_send_frame(buf, size, client->media->fps);
break;
default:
return -1;
}
return 0;
}
static void status_update_callback(tcp_cli_t *tcp_cli, int status)
{
if (tcp_cli)
{
tcp_cli->status = status;
logi(tag, "status=%s", get_play_state_str(status));
if (tcp_cli->state_changed_cb) tcp_cli->state_changed_cb(status);
}
}
static void *tcp_client_runnable(void *arg)
{
tcp_cli_t *tcp_cli = arg;
assert(tcp_cli != NULL);
struct pollfd pollfds[1];
int timeout = 1000;//milliseconds
int timeout_count = 0;
int max_timeout_count = (tcp_cli->timeout==0?NETWORK_TIMEOUT: tcp_cli->timeout)/ timeout;
int start = 1, type = -1;
int receive_len;
uint8_t hdr_buf[PAYLOAD_HEADER_SIZE];
int is_playing = 0;
packet_hdr_t packet_hdr;
packet_hdr_t *packetHdr = &packet_hdr;
static uint8_t buffer[MAX_FRAME_SIZE];
static uint8_t frame_buffer[MAX_FRAME_SIZE];
uint8_t *pBuffer = buffer;
uint8_t *pFrameBuffer = frame_buffer;
memset(frame_buffer, 0, MAX_FRAME_SIZE);
memset(buffer, 0, MAX_FRAME_SIZE);
pollfds[0].fd = tcp_cli->sockfd; //设置监控sockfd
pollfds[0].events = POLLIN | POLLPRI; //设置监控的事件
status_update_callback(tcp_cli, RTS_STATE_PREPARE);
tcp_cli->abort = 0;
while (!tcp_cli->abort)
{
switch (poll(pollfds, 1, timeout))
{
case -1: //函数调用出错
loge(tag, "poll error:%s ", strerror(errno));
if (tcp_cli->error_cb) tcp_cli->error_cb(RTS_ERR_EXCEPTION, strerror(errno));
goto err_output;
case 0://poll timeout
if (timeout_count >= max_timeout_count)
{
if (tcp_cli->error_cb) tcp_cli->error_cb(RTS_ERR_TIMEOUT, "Receive data timeout");
goto err_output;
}
timeout_count++;
break;
default: //得到数据返回
if (!is_playing)
{
is_playing = 1;
status_update_callback(tcp_cli, RTS_STATE_PLAYING);
}
timeout_count = 0;//re-count timeout
if (start)
{
receive_len = (int) recv(tcp_cli->sockfd, hdr_buf, PAYLOAD_HEADER_SIZE, MSG_WAITALL);
switch (receive_len)
{
case 0://server has disconnected
logw(tag, "1 socket has closed: %s", strerror(errno));
goto err_output;
case -1:
loge(tag, "error:%s", strerror(errno));
if (tcp_cli->error_cb) tcp_cli->error_cb(RTS_ERR_EXCEPTION, strerror(errno));
goto err_output;
default://OK
break;
}
memset(packetHdr, 0, sizeof(packet_hdr_t));
memcpy(packetHdr, hdr_buf, (size_t) receive_len);
type = packetHdr->frame_info.info.type;
start = 0;
//loge(tag, "type=%d, frame size=%d, receive_len=%d", type, packetHdr->frame_size, receive_len);
}
else
{
receive_len = (int) recv(tcp_cli->sockfd, pBuffer, packetHdr->frame_size, MSG_WAITALL);
//logi(tag, "receive len=%d, packetHdr.frame_size=%d", receive_len, packetHdr->frame_size);
if (receive_len == 0)
{
logw(tag, "2 client socket has closed");
goto err_output;
}
else if (receive_len < 0)
{
if (tcp_cli->error_cb) tcp_cli->error_cb(RTS_ERR_EXCEPTION, strerror(errno));
goto err_output;
}
else if (receive_len == packetHdr->frame_size)
{
switch (type)
{
case TYPE_RTS_PCM:
case TYPE_RTS_JPEG:
case TYPE_RTS_H264:
case TYPE_RTS_TIME:
memcpy(pFrameBuffer, pBuffer, packetHdr->frame_size);
if (tcp_cli->frame_received_cb)
tcp_cli->frame_received_cb(type, pFrameBuffer, packetHdr->frame_size, packetHdr->sequence, packetHdr->timestamp);
udp_send_frame(type, pFrameBuffer, packetHdr->frame_size, tcp_cli);
break;
default:
loge(tag, "Unknown type:%d", type);
break;
}
memset(pBuffer, 0, MAX_FRAME_SIZE);
start = 1;
}
}
break;
}
}
err_output:
if (tcp_cli->sockfd > 0) close(tcp_cli->sockfd);
tcp_cli->sockfd = -1;
status_update_callback(tcp_cli, RTS_STATE_STOP);
logi(tag, "TCP client exit");
pthread_exit(NULL);
return NULL;
}
int tcp_client_create(tcp_cli_t *tcp_cli)
{
logi(tag, "%s", __func__);
assert(tcp_cli != NULL);
if (rtp_create_socket() < 0)
{
loge(tag, "%s: create rtp socket failed", __func__);
return JNI_FALSE;
}
if (pthread_create(&tcp_cli->cli_tid, NULL, tcp_client_runnable, tcp_cli) != 0)
{
logw(tag, "Create tcp client runnable failed");
goto err_output;
}
return 0;
err_output:
logw(tag, "Create tcp client failed");
return -1;
}
int tcp_client_close(tcp_cli_t *tcp_cli)
{
logi(tag, "%s", __func__);
rtp_close_socket();
if (tcp_cli)
{
tcp_cli->abort = 1;
if (tcp_cli->sockfd > 0) close(tcp_cli->sockfd);
tcp_cli->sockfd = -1;
if (tcp_cli->cli_tid) pthread_join(tcp_cli->cli_tid, NULL);
}
return 0;
}
void tcp_client_set_frame_received_callback(tcp_cli_t *client, void *cb)
{
if (client ) client->frame_received_cb = (on_update_cb) cb;
}
void tcp_client_set_error_callback(tcp_cli_t *client, void *cb)
{
if (client) client->error_cb = cb;
}
void tcp_client_set_state_changed_callback(tcp_cli_t *server, void *cb)
{
if (server) server->state_changed_cb = cb;
}
void tcp_client_set_resolution(tcp_cli_t *client, int width, int height)
{
if (client)
{
client->width = width;
client->height = height;
}
}
void tcp_client_set_fps(tcp_cli_t *client, uint32_t fps)
{
if (client) client->v_fps = fps;
}
void tcp_client_set_sample_rate(tcp_cli_t *client, uint32_t sr)
{
if (client) client->a_sr = sr;
}
int tcp_client_is_receiving(tcp_cli_t * cli)
{
if (cli) return cli->status == RTS_STATE_PLAYING ? 0 : -1;
return -2;
}
|
960164.c | /* calc_arr2d.c -- 对输入的二维数组进行计算 */
#include <stdio.h>
void populate_arr2d(int rows, int cols, double src[rows][cols]);
double aver_arr(int n, double src[n]);
double aver_arr2d(int rows, int cols, double src[rows][cols]);
double max_arr2d(int rows, int cols, double src[rows][cols]);
int main(void)
{
int rows = 3, cols = 5;
double src[rows][cols];
int i;
populate_arr2d(rows, cols, src);
printf("average values:\n");
for (i = 0; i < rows; i++)
printf("%.2f ", aver_arr(cols, src[i]));
putchar('\n');
printf("average of arr2d: %.2f\n", aver_arr2d(rows, cols, src));
printf("max of arr2d: %.2f\n", max_arr2d(rows, cols, src));
printf("\n---------------------------------------------\n");
return 0;
}
void populate_arr2d(int rows, int cols, double src[rows][cols])
{
int i, j;
for (j = 0; j < rows; j++) {
printf("Input 5 numbers:");
for (i = 0; i < cols; i++)
scanf("%lf", &src[j][i]);
}
}
double aver_arr(int n, double src[n])
{
int i;
double sum = 0;
for (i = 0; i < n; i++)
sum += src[i];
return sum / n;
}
double aver_arr2d(int rows, int cols, double src[rows][cols])
{
int i, j;
double sum = 0;
for (i = 0; i < rows; i++)
for (j = 0; j < cols; j++)
sum += src[i][j];
return sum / (rows * cols);
}
double max_arr2d(int rows, int cols, double src[rows][cols])
{
int i, j;
double max = src[0][0];
for (i = 0; i < rows; i++)
for (j = 0; j < cols; j++)
if (max < src[i][j])
max = src[i][j];
return max;
} |
654180.c | /* Copyright (C) 2005-2020 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Jakub Jelinek <[email protected]>, 2005.
The GNU C 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.
The GNU C 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 the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <libc-diag.h>
static int errors = 0;
static void
merror (const char *msg)
{
++errors;
printf ("Error: %s\n", msg);
}
static int
do_test (void)
{
void *p, *q;
errno = 0;
DIAG_PUSH_NEEDS_COMMENT;
#if __GNUC_PREREQ (7, 0)
/* GCC 7 warns about too-large allocations; here we want to test
that they fail. */
DIAG_IGNORE_NEEDS_COMMENT (7, "-Walloc-size-larger-than=");
#endif
p = malloc (-1);
DIAG_POP_NEEDS_COMMENT;
if (p != NULL)
merror ("malloc (-1) succeeded.");
else if (errno != ENOMEM)
merror ("errno is not set correctly.");
p = malloc (10);
if (p == NULL)
merror ("malloc (10) failed.");
p = realloc (p, 0);
if (p != NULL)
merror ("realloc (p, 0) failed.");
p = malloc (0);
if (p == NULL)
merror ("malloc (0) failed.");
p = realloc (p, 0);
if (p != NULL)
merror ("realloc (p, 0) failed.");
q = malloc (256);
if (q == NULL)
merror ("malloc (256) failed.");
p = malloc (512);
if (p == NULL)
merror ("malloc (512) failed.");
DIAG_PUSH_NEEDS_COMMENT;
#if __GNUC_PREREQ (7, 0)
/* GCC 7 warns about too-large allocations; here we want to test
that they fail. */
DIAG_IGNORE_NEEDS_COMMENT (7, "-Walloc-size-larger-than=");
#endif
if (realloc (p, -256) != NULL)
merror ("realloc (p, -256) succeeded.");
else if (errno != ENOMEM)
merror ("errno is not set correctly.");
DIAG_POP_NEEDS_COMMENT;
free (p);
p = malloc (512);
if (p == NULL)
merror ("malloc (512) failed.");
DIAG_PUSH_NEEDS_COMMENT;
#if __GNUC_PREREQ (7, 0)
/* GCC 7 warns about too-large allocations; here we want to test
that they fail. */
DIAG_IGNORE_NEEDS_COMMENT (7, "-Walloc-size-larger-than=");
#endif
if (realloc (p, -1) != NULL)
merror ("realloc (p, -1) succeeded.");
else if (errno != ENOMEM)
merror ("errno is not set correctly.");
DIAG_POP_NEEDS_COMMENT;
free (p);
free (q);
return errors != 0;
}
#define TEST_FUNCTION do_test ()
#include "../test-skeleton.c"
|
947622.c | /*
* Copyright (C) 2003-2018 D. Gilbert
* 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, or (at your option)
* any later version.
*
* SPDX-License-Identifier: GPL-2.0-or-later
*
* This is a simple program that tests the O_EXCL flag in sg while
* executing a SCSI INQUIRY command and a
* TEST UNIT READY command using the SCSI generic (sg) driver
*
* Invocation: sg_excl [-x] <sg_device>
*
* Version 3.62 (20181227)
*
* 6 byte INQUIRY command:
* [0x12][ |lu][pg cde][res ][al len][cntrl ]
*
* 6 byte TEST UNIT READY command:
* [0x00][ |lu][res ][res ][res ][res ]
*
*/
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "sg_lib.h"
#include "sg_io_linux.h"
#define INQ_REPLY_LEN 96
#define INQ_CMD_LEN 6
#define TUR_CMD_LEN 6
#define EBUFF_SZ 256
#define ME "sg_excl: "
int main(int argc, char * argv[])
{
int sg_fd, k, ok /*, sg_fd2 */;
uint8_t inq_cdb [INQ_CMD_LEN] = {0x12, 0, 0, 0, INQ_REPLY_LEN, 0};
uint8_t tur_cdb [TUR_CMD_LEN] = {0x00, 0, 0, 0, 0, 0};
uint8_t inqBuff[INQ_REPLY_LEN];
sg_io_hdr_t io_hdr;
char * file_name = 0;
char ebuff[EBUFF_SZ];
uint8_t sense_buffer[32];
int do_extra = 0;
for (k = 1; k < argc; ++k) {
if (0 == memcmp("-x", argv[k], 2))
do_extra = 1;
else if (*argv[k] == '-') {
printf("Unrecognized switch: %s\n", argv[k]);
file_name = 0;
break;
}
else if (0 == file_name)
file_name = argv[k];
else {
printf("too many arguments\n");
file_name = 0;
break;
}
}
if (0 == file_name) {
printf("Usage: 'sg_excl [-x] <sg_device>'\n");
return 1;
}
/* N.B. An access mode of O_RDWR is required for some SCSI commands */
if ((sg_fd = open(file_name, O_RDWR | O_EXCL | O_NONBLOCK)) < 0) {
snprintf(ebuff, EBUFF_SZ, ME "error opening file: %s", file_name);
perror(ebuff);
return 1;
}
/* Just to be safe, check we have a new sg device by trying an ioctl */
if ((ioctl(sg_fd, SG_GET_VERSION_NUM, &k) < 0) || (k < 30000)) {
printf(ME "%s doesn't seem to be an new sg device\n",
file_name);
close(sg_fd);
return 1;
}
#if 0
if ((sg_fd2 = open(file_name, O_RDWR | O_EXCL)) < 0) {
snprintf(ebuff, EBUFF_SZ,
ME "error opening file: %s a second time", file_name);
perror(ebuff);
return 1;
} else {
printf(ME "second open of %s in violation of O_EXCL\n", file_name);
close(sg_fd2);
}
#endif
/* Prepare INQUIRY command */
memset(&io_hdr, 0, sizeof(sg_io_hdr_t));
io_hdr.interface_id = 'S';
io_hdr.cmd_len = sizeof(inq_cdb);
/* io_hdr.iovec_count = 0; */ /* memset takes care of this */
io_hdr.mx_sb_len = sizeof(sense_buffer);
io_hdr.dxfer_direction = SG_DXFER_FROM_DEV;
io_hdr.dxfer_len = INQ_REPLY_LEN;
io_hdr.dxferp = inqBuff;
io_hdr.cmdp = inq_cdb;
io_hdr.sbp = sense_buffer;
io_hdr.timeout = 20000; /* 20000 millisecs == 20 seconds */
/* io_hdr.flags = 0; */ /* take defaults: indirect IO, etc */
/* io_hdr.pack_id = 0; */
/* io_hdr.usr_ptr = NULL; */
if (ioctl(sg_fd, SG_IO, &io_hdr) < 0) {
perror(ME "Inquiry SG_IO ioctl error");
close(sg_fd);
return 1;
}
/* now for the error processing */
ok = 0;
switch (sg_err_category3(&io_hdr)) {
case SG_LIB_CAT_CLEAN:
ok = 1;
break;
case SG_LIB_CAT_RECOVERED:
printf("Recovered error on INQUIRY, continuing\n");
ok = 1;
break;
default: /* won't bother decoding other categories */
sg_chk_n_print3("INQUIRY command error", &io_hdr, 1);
break;
}
if (ok) { /* output result if it is available */
char * p = (char *)inqBuff;
int f = (int)*(p + 7);
printf("Some of the INQUIRY command's results:\n");
printf(" %.8s %.16s %.4s ", p + 8, p + 16, p + 32);
printf("[wide=%d sync=%d cmdque=%d sftre=%d]\n",
!!(f & 0x20), !!(f & 0x10), !!(f & 2), !!(f & 1));
/* Extra info, not necessary to look at */
if (do_extra)
printf("INQUIRY duration=%u millisecs, resid=%d, msg_status=%d\n",
io_hdr.duration, io_hdr.resid, (int)io_hdr.msg_status);
}
/* Prepare TEST UNIT READY command */
memset(&io_hdr, 0, sizeof(sg_io_hdr_t));
io_hdr.interface_id = 'S';
io_hdr.cmd_len = sizeof(tur_cdb);
io_hdr.mx_sb_len = sizeof(sense_buffer);
io_hdr.dxfer_direction = SG_DXFER_NONE;
io_hdr.cmdp = tur_cdb;
io_hdr.sbp = sense_buffer;
io_hdr.timeout = 20000; /* 20000 millisecs == 20 seconds */
if (ioctl(sg_fd, SG_IO, &io_hdr) < 0) {
perror(ME "Test Unit Ready SG_IO ioctl error");
close(sg_fd);
return 1;
}
/* now for the error processing */
ok = 0;
switch (sg_err_category3(&io_hdr)) {
case SG_LIB_CAT_CLEAN:
ok = 1;
break;
case SG_LIB_CAT_RECOVERED:
printf("Recovered error on Test Unit Ready, continuing\n");
ok = 1;
break;
default: /* won't bother decoding other categories */
sg_chk_n_print3("Test Unit Ready command error", &io_hdr, 1);
break;
}
if (ok)
printf("Test Unit Ready successful so unit is ready!\n");
else
printf("Test Unit Ready failed so unit may _not_ be ready!\n");
if (do_extra)
printf("TEST UNIT READY duration=%u millisecs, resid=%d, "
"msg_status=%d\n", io_hdr.duration, io_hdr.resid,
(int)io_hdr.msg_status);
printf("Wait for 60 seconds with O_EXCL help on %s\n", file_name);
sleep(60);
close(sg_fd);
return 0;
}
|
74113.c | /**
* \file
* \brief Microchip CryptoAuthentication device command builder - this is the main object that builds the command
* byte strings for the given device. It does not execute the command. The basic flow is to call
* a command method to build the command you want given the parameters and then send that byte string
* through the device interface.
*
* The primary goal of the command builder is to wrap the given parameters with the correct packet size and CRC.
* The caller should first fill in the parameters required in the ATCAPacket parameter given to the command.
* The command builder will deal with the mechanics of creating a valid packet using the parameter information.
*
* \copyright (c) 2015-2018 Microchip Technology Inc. and its subsidiaries.
*
* \page License
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to comply with third party license terms applicable to your
* use of third party software (including open source software) that may
* accompany Microchip software.
*
* THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
* EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
* WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT,
* SPECIAL, PUNITIVE, INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE
* OF ANY KIND WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF
* MICROCHIP HAS BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE
* FORESEEABLE. TO THE FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL
* LIABILITY ON ALL CLAIMS IN ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED
* THE AMOUNT OF FEES, IF ANY, THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR
* THIS SOFTWARE.
*/
#include <stdlib.h>
#include <string.h>
#include "atca_command.h"
#include "atca_devtypes.h"
#include "../../config/cryptoauthlib_config.h"
/** \brief ATCACommand CheckMAC method
* \param[in] ca_cmd instance
* \param[in] packet pointer to the packet containing the command being built
* \return ATCA_SUCCESS
*/
ATCA_STATUS atCheckMAC(ATCACommand ca_cmd, ATCAPacket *packet)
{
// Set the opcode & parameters
packet->opcode = ATCA_CHECKMAC;
packet->txsize = CHECKMAC_COUNT;
atCalcCrc(packet);
return ATCA_SUCCESS;
}
/** \brief ATCACommand Counter method
* \param[in] ca_cmd instance
* \param[in] packet pointer to the packet containing the command being built
* \return ATCA_SUCCESS on success, otherwise an error code.
*/
ATCA_STATUS atCounter(ATCACommand ca_cmd, ATCAPacket *packet)
{
// Set the opcode & parameters
packet->opcode = ATCA_COUNTER;
packet->txsize = COUNTER_COUNT;
atCalcCrc(packet);
return ATCA_SUCCESS;
}
/** \brief ATCACommand DeriveKey method
* \param[in] ca_cmd instance
* \param[in] packet pointer to the packet containing the command being built
* \param[in] has_mac hasMAC determines if MAC data is present in the packet input
* \return ATCA_SUCCESS
*/
ATCA_STATUS atDeriveKey(ATCACommand ca_cmd, ATCAPacket *packet, bool has_mac)
{
// Set the opcode & parameters
packet->opcode = ATCA_DERIVE_KEY;
// hasMAC must be given since the packet does not have any implicit information to
// know if it has a mac or not unless the size is preset
if (has_mac)
{
packet->txsize = DERIVE_KEY_COUNT_LARGE;
}
else
{
packet->txsize = DERIVE_KEY_COUNT_SMALL;
}
atCalcCrc(packet);
return ATCA_SUCCESS;
}
/** \brief ATCACommand ECDH method
* \param[in] ca_cmd instance
* \param[in] packet pointer to the packet containing the command being built
* \return ATCA_SUCCESS
*/
ATCA_STATUS atECDH(ATCACommand ca_cmd, ATCAPacket *packet)
{
// Set the opcode & parameters
packet->opcode = ATCA_ECDH;
packet->txsize = ECDH_COUNT;
atCalcCrc(packet);
return ATCA_SUCCESS;
}
/** \brief ATCACommand Generate Digest method
* \param[in] ca_cmd instance
* \param[in] packet pointer to the packet containing the command being built
* \param[in] is_no_mac_key Should be true if GenDig is being run on a slot that has its SlotConfig.NoMac bit set
* \return ATCA_SUCCESS
*/
ATCA_STATUS atGenDig(ATCACommand ca_cmd, ATCAPacket *packet, bool is_no_mac_key)
{
// Set the opcode & parameters
packet->opcode = ATCA_GENDIG;
if (packet->param1 == GENDIG_ZONE_SHARED_NONCE) // shared nonce mode
{
packet->txsize = GENDIG_COUNT + 32;
}
else if (is_no_mac_key)
{
packet->txsize = GENDIG_COUNT + 4; // noMac keys use 4 bytes of OtherData in calculation
}
else
{
packet->txsize = GENDIG_COUNT;
}
atCalcCrc(packet);
return ATCA_SUCCESS;
}
/** \brief ATCACommand Generate Key method
* \param[in] ca_cmd instance
* \param[in] packet pointer to the packet containing the command being built
* \return ATCA_SUCCESS
*/
ATCA_STATUS atGenKey(ATCACommand ca_cmd, ATCAPacket *packet)
{
// Set the opcode & parameters
packet->opcode = ATCA_GENKEY;
if (packet->param1 & GENKEY_MODE_PUBKEY_DIGEST)
{
packet->txsize = GENKEY_COUNT_DATA;
}
else
{
packet->txsize = GENKEY_COUNT;
}
atCalcCrc(packet);
return ATCA_SUCCESS;
}
/** \brief ATCACommand HMAC method
* \param[in] ca_cmd instance
* \param[in] packet pointer to the packet containing the command being built
* \return ATCA_SUCCESS
*/
ATCA_STATUS atHMAC(ATCACommand ca_cmd, ATCAPacket *packet)
{
// Set the opcode & parameters
packet->opcode = ATCA_HMAC;
packet->txsize = HMAC_COUNT;
atCalcCrc(packet);
return ATCA_SUCCESS;
}
/** \brief ATCACommand Info method
* \param[in] ca_cmd instance
* \param[in] packet pointer to the packet containing the command being built
* \return ATCA_SUCCESS
*/
ATCA_STATUS atInfo(ATCACommand ca_cmd, ATCAPacket *packet)
{
// Set the opcode & parameters
packet->opcode = ATCA_INFO;
packet->txsize = INFO_COUNT;
atCalcCrc(packet);
return ATCA_SUCCESS;
}
/** \brief ATCACommand Lock method
* \param[in] ca_cmd instance
* \param[in] packet pointer to the packet containing the command being built
* \return ATCA_SUCCESS
*/
ATCA_STATUS atLock(ATCACommand ca_cmd, ATCAPacket *packet)
{
// Set the opcode & parameters
packet->opcode = ATCA_LOCK;
packet->txsize = LOCK_COUNT;
atCalcCrc(packet);
return ATCA_SUCCESS;
}
/** \brief ATCACommand MAC method
* \param[in] ca_cmd instance
* \param[in] packet pointer to the packet containing the command being built
* \return ATCA_SUCCESS
*/
ATCA_STATUS atMAC(ATCACommand ca_cmd, ATCAPacket *packet)
{
// Set the opcode & parameters
// variable packet size
packet->opcode = ATCA_MAC;
if (!(packet->param1 & MAC_MODE_BLOCK2_TEMPKEY))
{
packet->txsize = MAC_COUNT_LONG;
}
else
{
packet->txsize = MAC_COUNT_SHORT;
}
atCalcCrc(packet);
return ATCA_SUCCESS;
}
/** \brief ATCACommand Nonce method
* \param[in] ca_cmd instance
* \param[in] packet pointer to the packet containing the command being built
* \return ATCA_SUCCESS on success, otherwise an error code.
*/
ATCA_STATUS atNonce(ATCACommand ca_cmd, ATCAPacket *packet)
{
// Set the opcode & parameters
// variable packet size
uint8_t calc_mode = packet->param1 & NONCE_MODE_MASK;
packet->opcode = ATCA_NONCE;
if ((calc_mode == NONCE_MODE_SEED_UPDATE || calc_mode == NONCE_MODE_NO_SEED_UPDATE))
{
// Calculated nonce mode, 20 byte NumInm
packet->txsize = NONCE_COUNT_SHORT;
}
else if (calc_mode == NONCE_MODE_PASSTHROUGH)
{
// PAss-through nonce mode
if ((packet->param1 & NONCE_MODE_INPUT_LEN_MASK) == NONCE_MODE_INPUT_LEN_64)
{
// 64 byte NumIn
packet->txsize = NONCE_COUNT_LONG_64;
}
else
{
// 32 byte NumIn
packet->txsize = NONCE_COUNT_LONG;
}
}
else
{
return ATCA_BAD_PARAM;
}
atCalcCrc(packet);
return ATCA_SUCCESS;
}
/** \brief ATCACommand Pause method
* \param[in] ca_cmd instance
* \param[in] packet pointer to the packet containing the command being built
* \return ATCA_SUCCESS
*/
ATCA_STATUS atPause(ATCACommand ca_cmd, ATCAPacket *packet)
{
// Set the opcode & parameters
packet->opcode = ATCA_PAUSE;
packet->txsize = PAUSE_COUNT;
atCalcCrc(packet);
return ATCA_SUCCESS;
}
/** \brief ATCACommand PrivWrite method
* \param[in] ca_cmd instance
* \param[in] packet pointer to the packet containing the command being built
* \return ATCA_SUCCESS
*/
ATCA_STATUS atPrivWrite(ATCACommand ca_cmd, ATCAPacket *packet)
{
// Set the opcode & parameters
packet->opcode = ATCA_PRIVWRITE;
packet->txsize = PRIVWRITE_COUNT;
atCalcCrc(packet);
return ATCA_SUCCESS;
}
/** \brief ATCACommand Random method
* \param[in] ca_cmd instance
* \param[in] packet pointer to the packet containing the command being built
* \return ATCA_SUCCESS
*/
ATCA_STATUS atRandom(ATCACommand ca_cmd, ATCAPacket *packet)
{
// Set the opcode & parameters
packet->opcode = ATCA_RANDOM;
packet->txsize = RANDOM_COUNT;
atCalcCrc(packet);
return ATCA_SUCCESS;
}
/** \brief ATCACommand Read method
* \param[in] ca_cmd instance
* \param[in] packet pointer to the packet containing the command being built
* \return ATCA_SUCCESS
*/
ATCA_STATUS atRead(ATCACommand ca_cmd, ATCAPacket *packet)
{
// Set the opcode & parameters
packet->opcode = ATCA_READ;
packet->txsize = READ_COUNT;
atCalcCrc(packet);
return ATCA_SUCCESS;
}
/** \brief ATCACommand SecureBoot method
* \param[in] ca_cmd instance
* \param[in] packet pointer to the packet containing the command being built
* \return ATCA_SUCCESS
*/
ATCA_STATUS atSecureBoot(ATCACommand ca_cmd, ATCAPacket *packet)
{
packet->opcode = ATCA_SECUREBOOT;
packet->txsize = ATCA_CMD_SIZE_MIN;
//variable transmit size based on mode encoding
switch (packet->param1 & SECUREBOOT_MODE_MASK)
{
case SECUREBOOT_MODE_FULL:
case SECUREBOOT_MODE_FULL_COPY:
packet->txsize += (SECUREBOOT_DIGEST_SIZE + SECUREBOOT_SIGNATURE_SIZE);
break;
case SECUREBOOT_MODE_FULL_STORE:
packet->txsize += SECUREBOOT_DIGEST_SIZE;
break;
default:
return ATCA_BAD_PARAM;
break;
}
atCalcCrc(packet);
return ATCA_SUCCESS;
}
/** \brief ATCACommand SHA method
* \param[in] ca_cmd instance
* \param[in] packet pointer to the packet containing the command being built
* \param[in] write_context_size the length of the sha write_context data
* \return ATCA_SUCCESS on success, otherwise an error code.
*/
ATCA_STATUS atSHA(ATCACommand ca_cmd, ATCAPacket *packet, uint16_t write_context_size)
{
// Set the opcode & parameters
packet->opcode = ATCA_SHA;
switch (packet->param1 & SHA_MODE_MASK)
{
case SHA_MODE_SHA256_START: // START
case SHA_MODE_HMAC_START:
case SHA_MODE_SHA256_PUBLIC:
packet->txsize = ATCA_CMD_SIZE_MIN;
break;
case SHA_MODE_SHA256_UPDATE: // UPDATE
packet->txsize = ATCA_CMD_SIZE_MIN + packet->param2;
break;
case SHA_MODE_SHA256_END: // END
case SHA_MODE_HMAC_END:
// check the given packet for a size variable in param2. If it is > 0, it should
// be 0-63, incorporate that size into the packet
packet->txsize = ATCA_CMD_SIZE_MIN + packet->param2;
break;
case SHA_MODE_READ_CONTEXT:
packet->txsize = ATCA_CMD_SIZE_MIN;
break;
case SHA_MODE_WRITE_CONTEXT:
packet->txsize = ATCA_CMD_SIZE_MIN + write_context_size;
break;
default:
return ATCA_BAD_PARAM;
}
atCalcCrc(packet);
return ATCA_SUCCESS;
}
/** \brief ATCACommand Sign method
* \param[in] ca_cmd instance
* \param[in] packet pointer to the packet containing the command being built
* \return ATCA_SUCCESS
*/
ATCA_STATUS atSign(ATCACommand ca_cmd, ATCAPacket *packet)
{
// Set the opcode & parameters
packet->opcode = ATCA_SIGN;
packet->txsize = SIGN_COUNT;
atCalcCrc(packet);
return ATCA_SUCCESS;
}
/** \brief ATCACommand UpdateExtra method
* \param[in] ca_cmd instance
* \param[in] packet pointer to the packet containing the command being built
* \return ATCA_SUCCESS
*/
ATCA_STATUS atUpdateExtra(ATCACommand ca_cmd, ATCAPacket *packet)
{
// Set the opcode & parameters
packet->opcode = ATCA_UPDATE_EXTRA;
packet->txsize = UPDATE_COUNT;
atCalcCrc(packet);
return ATCA_SUCCESS;
}
/** \brief ATCACommand ECDSA Verify method
* \param[in] ca_cmd instance
* \param[in] packet pointer to the packet containing the command being built
* \return ATCA_SUCCESS on success, otherwise an error code.
*/
ATCA_STATUS atVerify(ATCACommand ca_cmd, ATCAPacket *packet)
{
// Set the opcode & parameters
packet->opcode = ATCA_VERIFY;
// variable packet size based on mode
switch (packet->param1 & VERIFY_MODE_MASK)
{
case VERIFY_MODE_STORED:
packet->txsize = VERIFY_256_STORED_COUNT;
break;
case VERIFY_MODE_VALIDATE_EXTERNAL:
packet->txsize = VERIFY_256_EXTERNAL_COUNT;
break;
case VERIFY_MODE_EXTERNAL:
packet->txsize = VERIFY_256_EXTERNAL_COUNT;
break;
case VERIFY_MODE_VALIDATE:
case VERIFY_MODE_INVALIDATE:
packet->txsize = VERIFY_256_VALIDATE_COUNT;
break;
default:
return ATCA_BAD_PARAM;
}
atCalcCrc(packet);
return ATCA_SUCCESS;
}
/** \brief ATCACommand Write method
* \param[in] ca_cmd instance
* \param[in] packet pointer to the packet containing the command being built
* \param[in] has_mac Flag to indicate whether a mac is present or not
* \return ATCA_SUCCESS
*/
ATCA_STATUS atWrite(ATCACommand ca_cmd, ATCAPacket *packet, bool has_mac)
{
// Set the opcode & parameters
packet->opcode = ATCA_WRITE;
packet->txsize = 7;
if (packet->param1 & ATCA_ZONE_READWRITE_32)
{
packet->txsize += ATCA_BLOCK_SIZE;
}
else
{
packet->txsize += ATCA_WORD_SIZE;
}
if (has_mac)
{
packet->txsize += WRITE_MAC_SIZE;
}
atCalcCrc(packet);
return ATCA_SUCCESS;
}
/** \brief ATCACommand AES method
* \param[in] ca_cmd instance
* \param[in] packet pointer to the packet containing the command being built
* \return ATCA_SUCCESS
*/
ATCA_STATUS atAES(ATCACommand ca_cmd, ATCAPacket *packet)
{
// Set the opcode & parameters
packet->opcode = ATCA_AES;
packet->txsize = ATCA_CMD_SIZE_MIN;
if ((packet->param1 & AES_MODE_OP_MASK) == AES_MODE_GFM)
{
packet->txsize += ATCA_AES_GFM_SIZE;
}
else
{
packet->txsize += AES_DATA_SIZE;
}
atCalcCrc(packet);
return ATCA_SUCCESS;
}
/** \brief ATCACommand AES method
* \param[in] ca_cmd instance
* \param[in] packet pointer to the packet containing the command being built
* \return ATCA_SUCCESS
*/
ATCA_STATUS atSelfTest(ATCACommand ca_cmd, ATCAPacket *packet)
{
// Set the opcode & parameters
packet->opcode = ATCA_SELFTEST;
packet->txsize = ATCA_CMD_SIZE_MIN;
atCalcCrc(packet);
return ATCA_SUCCESS;
}
/** \brief ATCACommand KDF method
* \param[in] ca_cmd Instance
* \param[in] packet Pointer to the packet containing the command being
* built.
* \return ATCA_SUCCESS
*/
ATCA_STATUS atKDF(ATCACommand ca_cmd, ATCAPacket *packet)
{
// Set the opcode & parameters
packet->opcode = ATCA_KDF;
// Set TX size
if ((packet->param1 & KDF_MODE_ALG_MASK) == KDF_MODE_ALG_AES)
{
// AES algorithm has a fixed message size
packet->txsize = ATCA_CMD_SIZE_MIN + KDF_DETAILS_SIZE + AES_DATA_SIZE;
}
else
{
// All other algorithms encode message size in the last byte of details
packet->txsize = ATCA_CMD_SIZE_MIN + KDF_DETAILS_SIZE + packet->data[3];
}
atCalcCrc(packet);
return ATCA_SUCCESS;
}
/** \brief Initializer for ATCACommand
* \param[in] device_type Specifies which set of commands and execution times
* should be associated with this command object.
* \param[in] ca_cmd Pre-allocated command structure to initialize.
* \return ATCA_SUCCESS on success, otherwise an error code.
*/
ATCA_STATUS initATCACommand(ATCADeviceType device_type, ATCACommand ca_cmd)
{
if (ca_cmd == NULL)
{
return ATCA_BAD_PARAM;
}
ca_cmd->dt = device_type;
ca_cmd->clock_divider = 0;
return ATCA_SUCCESS;
}
#ifndef ATCA_NO_HEAP
/** \brief constructor for ATCACommand
* \param[in] device_type Specifies which set of commands and execution times
* should be associated with this command object.
* \return Initialized object on success. NULL on failure.
*/
ATCACommand newATCACommand(ATCADeviceType device_type)
{
ATCACommand ca_cmd;
ATCA_STATUS status;
ca_cmd = (ATCACommand)malloc(sizeof(*ca_cmd));
status = initATCACommand(device_type, ca_cmd);
if (status != ATCA_SUCCESS)
{
free(ca_cmd);
ca_cmd = NULL;
return NULL;
}
return ca_cmd;
}
#endif
#ifndef ATCA_NO_HEAP
/** \brief ATCACommand destructor
* \param[in] ca_cmd instance of a command object
*/
void deleteATCACommand(ATCACommand *ca_cmd)
{
if (ca_cmd == NULL)
{
return;
}
free(*ca_cmd);
*ca_cmd = NULL;
}
#endif
/** \brief Calculates CRC over the given raw data and returns the CRC in
* little-endian byte order.
*
* \param[in] length Size of data not including the CRC byte positions
* \param[in] data Pointer to the data over which to compute the CRC
* \param[out] crc_le Pointer to the place where the two-bytes of CRC will be
* returned in little-endian byte order.
*/
void atCRC(size_t length, const uint8_t *data, uint8_t *crc_le)
{
size_t counter;
uint16_t crc_register = 0;
uint16_t polynom = 0x8005;
uint8_t shift_register;
uint8_t data_bit, crc_bit;
for (counter = 0; counter < length; counter++)
{
for (shift_register = 0x01; shift_register > 0x00; shift_register <<= 1)
{
data_bit = (data[counter] & shift_register) ? 1 : 0;
crc_bit = crc_register >> 15;
crc_register <<= 1;
if (data_bit != crc_bit)
{
crc_register ^= polynom;
}
}
}
crc_le[0] = (uint8_t)(crc_register & 0x00FF);
crc_le[1] = (uint8_t)(crc_register >> 8);
}
/** \brief This function calculates CRC and adds it to the correct offset in the packet data
* \param[in] packet Packet to calculate CRC data for
*/
void atCalcCrc(ATCAPacket *packet)
{
uint8_t length, *crc;
length = packet->txsize - ATCA_CRC_SIZE;
// computer pointer to CRC in the packet
crc = &(packet->txsize) + length;
// stuff CRC into packet
atCRC(length, &(packet->txsize), crc);
}
/** \brief This function checks the consistency of a response.
* \param[in] response pointer to response
* \return ATCA_SUCCESS on success, otherwise ATCA_RX_CRC_ERROR
*/
ATCA_STATUS atCheckCrc(const uint8_t *response)
{
uint8_t crc[ATCA_CRC_SIZE];
uint8_t count = response[ATCA_COUNT_IDX];
count -= ATCA_CRC_SIZE;
atCRC(count, response, crc);
return (crc[0] == response[count] && crc[1] == response[count + 1]) ? ATCA_SUCCESS : ATCA_RX_CRC_ERROR;
}
/** \brief determines if a given device type is a SHA device or a superset of a SHA device
* \param[in] device_type Type of device to check for family type
* \return boolean indicating whether the given device is a SHA family device.
*/
bool atIsSHAFamily(ATCADeviceType device_type)
{
switch (device_type)
{
case ATSHA204A:
case ATECC108A:
case ATECC508A:
case ATECC608A:
return true;
break;
default:
return false;
break;
}
}
/** \brief determines if a given device type is an ECC device or a superset of a ECC device
* \param[in] device_type Type of device to check for family type
* \return boolean indicating whether the given device is an ECC family device.
*/
bool atIsECCFamily(ATCADeviceType device_type)
{
switch (device_type)
{
case ATECC108A:
case ATECC508A:
case ATECC608A:
return true;
break;
default:
return false;
break;
}
}
/** \brief checks for basic error frame in data
* \param[in] data pointer to received data - expected to be in the form of a CA device response frame
* \return ATCA_SUCCESS on success, otherwise an error code.
*/
ATCA_STATUS isATCAError(uint8_t *data)
{
if (data[0] == 0x04) // error packets are always 4 bytes long
{
switch (data[1])
{
case 0x00: //No Error
return ATCA_SUCCESS;
case 0x01: // checkmac or verify failed
return ATCA_CHECKMAC_VERIFY_FAILED;
break;
case 0x03: // command received byte length, opcode or parameter was illegal
return ATCA_PARSE_ERROR;
break;
case 0x05: // computation error during ECC processing causing invalid results
return ATCA_STATUS_ECC;
break;
case 0x07: // chip is in self test failure mode
return ATCA_STATUS_SELFTEST_ERROR;
break;
case 0x08: //random number generator health test error
return ATCA_HEALTH_TEST_ERROR;
case 0x0f: // chip can't execute the command
return ATCA_EXECUTION_ERROR;
break;
case 0x11: // chip was successfully woken up
return ATCA_WAKE_SUCCESS;
break;
case 0xff: // bad crc found (command not properly received by device) or other comm error
return ATCA_STATUS_CRC;
break;
default:
return ATCA_GEN_FAIL;
break;
}
}
else
{
return ATCA_SUCCESS;
}
}
/** @} */
|
503163.c | /* Copyright (C) 1995, 1997-2000, 2001, 2002 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C 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.
The GNU C 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 the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.
As a special exception, if you link the code in this file with
files compiled with a GNU compiler to produce an executable,
that does not cause the resulting executable to be covered by
the GNU Lesser General Public License. This exception does not
however invalidate any other reasons why the executable file
might be covered by the GNU Lesser General Public License.
This exception applies to code released by its copyright holders
in files containing the exception. */
#include "libioP.h"
#include <stdio_ext.h>
int
_IO_vdprintf (d, format, arg)
int d;
const char *format;
_IO_va_list arg;
{
struct _IO_FILE_plus tmpfil;
struct _IO_wide_data wd;
int done;
#ifdef _IO_MTSAFE_IO
tmpfil.file._lock = NULL;
#endif
_IO_no_init (&tmpfil.file, _IO_USER_LOCK, 0, &wd, &INTUSE(_IO_wfile_jumps));
_IO_JUMPS (&tmpfil) = &INTUSE(_IO_file_jumps);
INTUSE(_IO_file_init) (&tmpfil);
#if !_IO_UNIFIED_JUMPTABLES
tmpfil.vtable = NULL;
#endif
if (INTUSE(_IO_file_attach) (&tmpfil.file, d) == NULL)
{
INTUSE(_IO_un_link) (&tmpfil);
return EOF;
}
tmpfil.file._IO_file_flags =
(_IO_mask_flags (&tmpfil.file, _IO_NO_READS,
_IO_NO_READS+_IO_NO_WRITES+_IO_IS_APPENDING)
| _IO_DELETE_DONT_CLOSE);
done = INTUSE(_IO_vfprintf) (&tmpfil.file, format, arg);
_IO_FINISH (&tmpfil.file);
return done;
}
#ifdef weak_alias
weak_alias (_IO_vdprintf, vdprintf)
#endif
|
524625.c | /*
* arch/powerpc/kernel/mpic.c
*
* Driver for interrupt controllers following the OpenPIC standard, the
* common implementation being IBM's MPIC. This driver also can deal
* with various broken implementations of this HW.
*
* Copyright (C) 2004 Benjamin Herrenschmidt, IBM Corp.
* Copyright 2010-2012 Freescale Semiconductor, Inc.
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive
* for more details.
*/
#undef DEBUG
#undef DEBUG_IPI
#undef DEBUG_IRQ
#undef DEBUG_LOW
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/irq.h>
#include <linux/smp.h>
#include <linux/interrupt.h>
#include <linux/spinlock.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/syscore_ops.h>
#include <linux/ratelimit.h>
#include <linux/pgtable.h>
#include <asm/ptrace.h>
#include <asm/signal.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/machdep.h>
#include <asm/mpic.h>
#include <asm/smp.h>
#include "mpic.h"
#ifdef DEBUG
#define DBG(fmt...) printk(fmt)
#else
#define DBG(fmt...)
#endif
struct bus_type mpic_subsys = {
.name = "mpic",
.dev_name = "mpic",
};
EXPORT_SYMBOL_GPL(mpic_subsys);
static struct mpic *mpics;
static struct mpic *mpic_primary;
static DEFINE_RAW_SPINLOCK(mpic_lock);
#ifdef CONFIG_PPC32 /* XXX for now */
#ifdef CONFIG_IRQ_ALL_CPUS
#define distribute_irqs (1)
#else
#define distribute_irqs (0)
#endif
#endif
#ifdef CONFIG_MPIC_WEIRD
static u32 mpic_infos[][MPIC_IDX_END] = {
[0] = { /* Original OpenPIC compatible MPIC */
MPIC_GREG_BASE,
MPIC_GREG_FEATURE_0,
MPIC_GREG_GLOBAL_CONF_0,
MPIC_GREG_VENDOR_ID,
MPIC_GREG_IPI_VECTOR_PRI_0,
MPIC_GREG_IPI_STRIDE,
MPIC_GREG_SPURIOUS,
MPIC_GREG_TIMER_FREQ,
MPIC_TIMER_BASE,
MPIC_TIMER_STRIDE,
MPIC_TIMER_CURRENT_CNT,
MPIC_TIMER_BASE_CNT,
MPIC_TIMER_VECTOR_PRI,
MPIC_TIMER_DESTINATION,
MPIC_CPU_BASE,
MPIC_CPU_STRIDE,
MPIC_CPU_IPI_DISPATCH_0,
MPIC_CPU_IPI_DISPATCH_STRIDE,
MPIC_CPU_CURRENT_TASK_PRI,
MPIC_CPU_WHOAMI,
MPIC_CPU_INTACK,
MPIC_CPU_EOI,
MPIC_CPU_MCACK,
MPIC_IRQ_BASE,
MPIC_IRQ_STRIDE,
MPIC_IRQ_VECTOR_PRI,
MPIC_VECPRI_VECTOR_MASK,
MPIC_VECPRI_POLARITY_POSITIVE,
MPIC_VECPRI_POLARITY_NEGATIVE,
MPIC_VECPRI_SENSE_LEVEL,
MPIC_VECPRI_SENSE_EDGE,
MPIC_VECPRI_POLARITY_MASK,
MPIC_VECPRI_SENSE_MASK,
MPIC_IRQ_DESTINATION
},
[1] = { /* Tsi108/109 PIC */
TSI108_GREG_BASE,
TSI108_GREG_FEATURE_0,
TSI108_GREG_GLOBAL_CONF_0,
TSI108_GREG_VENDOR_ID,
TSI108_GREG_IPI_VECTOR_PRI_0,
TSI108_GREG_IPI_STRIDE,
TSI108_GREG_SPURIOUS,
TSI108_GREG_TIMER_FREQ,
TSI108_TIMER_BASE,
TSI108_TIMER_STRIDE,
TSI108_TIMER_CURRENT_CNT,
TSI108_TIMER_BASE_CNT,
TSI108_TIMER_VECTOR_PRI,
TSI108_TIMER_DESTINATION,
TSI108_CPU_BASE,
TSI108_CPU_STRIDE,
TSI108_CPU_IPI_DISPATCH_0,
TSI108_CPU_IPI_DISPATCH_STRIDE,
TSI108_CPU_CURRENT_TASK_PRI,
TSI108_CPU_WHOAMI,
TSI108_CPU_INTACK,
TSI108_CPU_EOI,
TSI108_CPU_MCACK,
TSI108_IRQ_BASE,
TSI108_IRQ_STRIDE,
TSI108_IRQ_VECTOR_PRI,
TSI108_VECPRI_VECTOR_MASK,
TSI108_VECPRI_POLARITY_POSITIVE,
TSI108_VECPRI_POLARITY_NEGATIVE,
TSI108_VECPRI_SENSE_LEVEL,
TSI108_VECPRI_SENSE_EDGE,
TSI108_VECPRI_POLARITY_MASK,
TSI108_VECPRI_SENSE_MASK,
TSI108_IRQ_DESTINATION
},
};
#define MPIC_INFO(name) mpic->hw_set[MPIC_IDX_##name]
#else /* CONFIG_MPIC_WEIRD */
#define MPIC_INFO(name) MPIC_##name
#endif /* CONFIG_MPIC_WEIRD */
static inline unsigned int mpic_processor_id(struct mpic *mpic)
{
unsigned int cpu = 0;
if (!(mpic->flags & MPIC_SECONDARY))
cpu = hard_smp_processor_id();
return cpu;
}
/*
* Register accessor functions
*/
static inline u32 _mpic_read(enum mpic_reg_type type,
struct mpic_reg_bank *rb,
unsigned int reg)
{
switch(type) {
#ifdef CONFIG_PPC_DCR
case mpic_access_dcr:
return dcr_read(rb->dhost, reg);
#endif
case mpic_access_mmio_be:
return in_be32(rb->base + (reg >> 2));
case mpic_access_mmio_le:
default:
return in_le32(rb->base + (reg >> 2));
}
}
static inline void _mpic_write(enum mpic_reg_type type,
struct mpic_reg_bank *rb,
unsigned int reg, u32 value)
{
switch(type) {
#ifdef CONFIG_PPC_DCR
case mpic_access_dcr:
dcr_write(rb->dhost, reg, value);
break;
#endif
case mpic_access_mmio_be:
out_be32(rb->base + (reg >> 2), value);
break;
case mpic_access_mmio_le:
default:
out_le32(rb->base + (reg >> 2), value);
break;
}
}
static inline u32 _mpic_ipi_read(struct mpic *mpic, unsigned int ipi)
{
enum mpic_reg_type type = mpic->reg_type;
unsigned int offset = MPIC_INFO(GREG_IPI_VECTOR_PRI_0) +
(ipi * MPIC_INFO(GREG_IPI_STRIDE));
if ((mpic->flags & MPIC_BROKEN_IPI) && type == mpic_access_mmio_le)
type = mpic_access_mmio_be;
return _mpic_read(type, &mpic->gregs, offset);
}
static inline void _mpic_ipi_write(struct mpic *mpic, unsigned int ipi, u32 value)
{
unsigned int offset = MPIC_INFO(GREG_IPI_VECTOR_PRI_0) +
(ipi * MPIC_INFO(GREG_IPI_STRIDE));
_mpic_write(mpic->reg_type, &mpic->gregs, offset, value);
}
static inline unsigned int mpic_tm_offset(struct mpic *mpic, unsigned int tm)
{
return (tm >> 2) * MPIC_TIMER_GROUP_STRIDE +
(tm & 3) * MPIC_INFO(TIMER_STRIDE);
}
static inline u32 _mpic_tm_read(struct mpic *mpic, unsigned int tm)
{
unsigned int offset = mpic_tm_offset(mpic, tm) +
MPIC_INFO(TIMER_VECTOR_PRI);
return _mpic_read(mpic->reg_type, &mpic->tmregs, offset);
}
static inline void _mpic_tm_write(struct mpic *mpic, unsigned int tm, u32 value)
{
unsigned int offset = mpic_tm_offset(mpic, tm) +
MPIC_INFO(TIMER_VECTOR_PRI);
_mpic_write(mpic->reg_type, &mpic->tmregs, offset, value);
}
static inline u32 _mpic_cpu_read(struct mpic *mpic, unsigned int reg)
{
unsigned int cpu = mpic_processor_id(mpic);
return _mpic_read(mpic->reg_type, &mpic->cpuregs[cpu], reg);
}
static inline void _mpic_cpu_write(struct mpic *mpic, unsigned int reg, u32 value)
{
unsigned int cpu = mpic_processor_id(mpic);
_mpic_write(mpic->reg_type, &mpic->cpuregs[cpu], reg, value);
}
static inline u32 _mpic_irq_read(struct mpic *mpic, unsigned int src_no, unsigned int reg)
{
unsigned int isu = src_no >> mpic->isu_shift;
unsigned int idx = src_no & mpic->isu_mask;
unsigned int val;
val = _mpic_read(mpic->reg_type, &mpic->isus[isu],
reg + (idx * MPIC_INFO(IRQ_STRIDE)));
#ifdef CONFIG_MPIC_BROKEN_REGREAD
if (reg == 0)
val = (val & (MPIC_VECPRI_MASK | MPIC_VECPRI_ACTIVITY)) |
mpic->isu_reg0_shadow[src_no];
#endif
return val;
}
static inline void _mpic_irq_write(struct mpic *mpic, unsigned int src_no,
unsigned int reg, u32 value)
{
unsigned int isu = src_no >> mpic->isu_shift;
unsigned int idx = src_no & mpic->isu_mask;
_mpic_write(mpic->reg_type, &mpic->isus[isu],
reg + (idx * MPIC_INFO(IRQ_STRIDE)), value);
#ifdef CONFIG_MPIC_BROKEN_REGREAD
if (reg == 0)
mpic->isu_reg0_shadow[src_no] =
value & ~(MPIC_VECPRI_MASK | MPIC_VECPRI_ACTIVITY);
#endif
}
#define mpic_read(b,r) _mpic_read(mpic->reg_type,&(b),(r))
#define mpic_write(b,r,v) _mpic_write(mpic->reg_type,&(b),(r),(v))
#define mpic_ipi_read(i) _mpic_ipi_read(mpic,(i))
#define mpic_ipi_write(i,v) _mpic_ipi_write(mpic,(i),(v))
#define mpic_tm_read(i) _mpic_tm_read(mpic,(i))
#define mpic_tm_write(i,v) _mpic_tm_write(mpic,(i),(v))
#define mpic_cpu_read(i) _mpic_cpu_read(mpic,(i))
#define mpic_cpu_write(i,v) _mpic_cpu_write(mpic,(i),(v))
#define mpic_irq_read(s,r) _mpic_irq_read(mpic,(s),(r))
#define mpic_irq_write(s,r,v) _mpic_irq_write(mpic,(s),(r),(v))
/*
* Low level utility functions
*/
static void _mpic_map_mmio(struct mpic *mpic, phys_addr_t phys_addr,
struct mpic_reg_bank *rb, unsigned int offset,
unsigned int size)
{
rb->base = ioremap(phys_addr + offset, size);
BUG_ON(rb->base == NULL);
}
#ifdef CONFIG_PPC_DCR
static void _mpic_map_dcr(struct mpic *mpic, struct mpic_reg_bank *rb,
unsigned int offset, unsigned int size)
{
phys_addr_t phys_addr = dcr_resource_start(mpic->node, 0);
rb->dhost = dcr_map(mpic->node, phys_addr + offset, size);
BUG_ON(!DCR_MAP_OK(rb->dhost));
}
static inline void mpic_map(struct mpic *mpic,
phys_addr_t phys_addr, struct mpic_reg_bank *rb,
unsigned int offset, unsigned int size)
{
if (mpic->flags & MPIC_USES_DCR)
_mpic_map_dcr(mpic, rb, offset, size);
else
_mpic_map_mmio(mpic, phys_addr, rb, offset, size);
}
#else /* CONFIG_PPC_DCR */
#define mpic_map(m,p,b,o,s) _mpic_map_mmio(m,p,b,o,s)
#endif /* !CONFIG_PPC_DCR */
/* Check if we have one of those nice broken MPICs with a flipped endian on
* reads from IPI registers
*/
static void __init mpic_test_broken_ipi(struct mpic *mpic)
{
u32 r;
mpic_write(mpic->gregs, MPIC_INFO(GREG_IPI_VECTOR_PRI_0), MPIC_VECPRI_MASK);
r = mpic_read(mpic->gregs, MPIC_INFO(GREG_IPI_VECTOR_PRI_0));
if (r == le32_to_cpu(MPIC_VECPRI_MASK)) {
printk(KERN_INFO "mpic: Detected reversed IPI registers\n");
mpic->flags |= MPIC_BROKEN_IPI;
}
}
#ifdef CONFIG_MPIC_U3_HT_IRQS
/* Test if an interrupt is sourced from HyperTransport (used on broken U3s)
* to force the edge setting on the MPIC and do the ack workaround.
*/
static inline int mpic_is_ht_interrupt(struct mpic *mpic, unsigned int source)
{
if (source >= 128 || !mpic->fixups)
return 0;
return mpic->fixups[source].base != NULL;
}
static inline void mpic_ht_end_irq(struct mpic *mpic, unsigned int source)
{
struct mpic_irq_fixup *fixup = &mpic->fixups[source];
if (fixup->applebase) {
unsigned int soff = (fixup->index >> 3) & ~3;
unsigned int mask = 1U << (fixup->index & 0x1f);
writel(mask, fixup->applebase + soff);
} else {
raw_spin_lock(&mpic->fixup_lock);
writeb(0x11 + 2 * fixup->index, fixup->base + 2);
writel(fixup->data, fixup->base + 4);
raw_spin_unlock(&mpic->fixup_lock);
}
}
static void mpic_startup_ht_interrupt(struct mpic *mpic, unsigned int source,
bool level)
{
struct mpic_irq_fixup *fixup = &mpic->fixups[source];
unsigned long flags;
u32 tmp;
if (fixup->base == NULL)
return;
DBG("startup_ht_interrupt(0x%x) index: %d\n",
source, fixup->index);
raw_spin_lock_irqsave(&mpic->fixup_lock, flags);
/* Enable and configure */
writeb(0x10 + 2 * fixup->index, fixup->base + 2);
tmp = readl(fixup->base + 4);
tmp &= ~(0x23U);
if (level)
tmp |= 0x22;
writel(tmp, fixup->base + 4);
raw_spin_unlock_irqrestore(&mpic->fixup_lock, flags);
#ifdef CONFIG_PM
/* use the lowest bit inverted to the actual HW,
* set if this fixup was enabled, clear otherwise */
mpic->save_data[source].fixup_data = tmp | 1;
#endif
}
static void mpic_shutdown_ht_interrupt(struct mpic *mpic, unsigned int source)
{
struct mpic_irq_fixup *fixup = &mpic->fixups[source];
unsigned long flags;
u32 tmp;
if (fixup->base == NULL)
return;
DBG("shutdown_ht_interrupt(0x%x)\n", source);
/* Disable */
raw_spin_lock_irqsave(&mpic->fixup_lock, flags);
writeb(0x10 + 2 * fixup->index, fixup->base + 2);
tmp = readl(fixup->base + 4);
tmp |= 1;
writel(tmp, fixup->base + 4);
raw_spin_unlock_irqrestore(&mpic->fixup_lock, flags);
#ifdef CONFIG_PM
/* use the lowest bit inverted to the actual HW,
* set if this fixup was enabled, clear otherwise */
mpic->save_data[source].fixup_data = tmp & ~1;
#endif
}
#ifdef CONFIG_PCI_MSI
static void __init mpic_scan_ht_msi(struct mpic *mpic, u8 __iomem *devbase,
unsigned int devfn)
{
u8 __iomem *base;
u8 pos, flags;
u64 addr = 0;
for (pos = readb(devbase + PCI_CAPABILITY_LIST); pos != 0;
pos = readb(devbase + pos + PCI_CAP_LIST_NEXT)) {
u8 id = readb(devbase + pos + PCI_CAP_LIST_ID);
if (id == PCI_CAP_ID_HT) {
id = readb(devbase + pos + 3);
if ((id & HT_5BIT_CAP_MASK) == HT_CAPTYPE_MSI_MAPPING)
break;
}
}
if (pos == 0)
return;
base = devbase + pos;
flags = readb(base + HT_MSI_FLAGS);
if (!(flags & HT_MSI_FLAGS_FIXED)) {
addr = readl(base + HT_MSI_ADDR_LO) & HT_MSI_ADDR_LO_MASK;
addr = addr | ((u64)readl(base + HT_MSI_ADDR_HI) << 32);
}
printk(KERN_DEBUG "mpic: - HT:%02x.%x %s MSI mapping found @ 0x%llx\n",
PCI_SLOT(devfn), PCI_FUNC(devfn),
flags & HT_MSI_FLAGS_ENABLE ? "enabled" : "disabled", addr);
if (!(flags & HT_MSI_FLAGS_ENABLE))
writeb(flags | HT_MSI_FLAGS_ENABLE, base + HT_MSI_FLAGS);
}
#else
static void __init mpic_scan_ht_msi(struct mpic *mpic, u8 __iomem *devbase,
unsigned int devfn)
{
return;
}
#endif
static void __init mpic_scan_ht_pic(struct mpic *mpic, u8 __iomem *devbase,
unsigned int devfn, u32 vdid)
{
int i, irq, n;
u8 __iomem *base;
u32 tmp;
u8 pos;
for (pos = readb(devbase + PCI_CAPABILITY_LIST); pos != 0;
pos = readb(devbase + pos + PCI_CAP_LIST_NEXT)) {
u8 id = readb(devbase + pos + PCI_CAP_LIST_ID);
if (id == PCI_CAP_ID_HT) {
id = readb(devbase + pos + 3);
if ((id & HT_5BIT_CAP_MASK) == HT_CAPTYPE_IRQ)
break;
}
}
if (pos == 0)
return;
base = devbase + pos;
writeb(0x01, base + 2);
n = (readl(base + 4) >> 16) & 0xff;
printk(KERN_INFO "mpic: - HT:%02x.%x [0x%02x] vendor %04x device %04x"
" has %d irqs\n",
devfn >> 3, devfn & 0x7, pos, vdid & 0xffff, vdid >> 16, n + 1);
for (i = 0; i <= n; i++) {
writeb(0x10 + 2 * i, base + 2);
tmp = readl(base + 4);
irq = (tmp >> 16) & 0xff;
DBG("HT PIC index 0x%x, irq 0x%x, tmp: %08x\n", i, irq, tmp);
/* mask it , will be unmasked later */
tmp |= 0x1;
writel(tmp, base + 4);
mpic->fixups[irq].index = i;
mpic->fixups[irq].base = base;
/* Apple HT PIC has a non-standard way of doing EOIs */
if ((vdid & 0xffff) == 0x106b)
mpic->fixups[irq].applebase = devbase + 0x60;
else
mpic->fixups[irq].applebase = NULL;
writeb(0x11 + 2 * i, base + 2);
mpic->fixups[irq].data = readl(base + 4) | 0x80000000;
}
}
static void __init mpic_scan_ht_pics(struct mpic *mpic)
{
unsigned int devfn;
u8 __iomem *cfgspace;
printk(KERN_INFO "mpic: Setting up HT PICs workarounds for U3/U4\n");
/* Allocate fixups array */
mpic->fixups = kcalloc(128, sizeof(*mpic->fixups), GFP_KERNEL);
BUG_ON(mpic->fixups == NULL);
/* Init spinlock */
raw_spin_lock_init(&mpic->fixup_lock);
/* Map U3 config space. We assume all IO-APICs are on the primary bus
* so we only need to map 64kB.
*/
cfgspace = ioremap(0xf2000000, 0x10000);
BUG_ON(cfgspace == NULL);
/* Now we scan all slots. We do a very quick scan, we read the header
* type, vendor ID and device ID only, that's plenty enough
*/
for (devfn = 0; devfn < 0x100; devfn++) {
u8 __iomem *devbase = cfgspace + (devfn << 8);
u8 hdr_type = readb(devbase + PCI_HEADER_TYPE);
u32 l = readl(devbase + PCI_VENDOR_ID);
u16 s;
DBG("devfn %x, l: %x\n", devfn, l);
/* If no device, skip */
if (l == 0xffffffff || l == 0x00000000 ||
l == 0x0000ffff || l == 0xffff0000)
goto next;
/* Check if is supports capability lists */
s = readw(devbase + PCI_STATUS);
if (!(s & PCI_STATUS_CAP_LIST))
goto next;
mpic_scan_ht_pic(mpic, devbase, devfn, l);
mpic_scan_ht_msi(mpic, devbase, devfn);
next:
/* next device, if function 0 */
if (PCI_FUNC(devfn) == 0 && (hdr_type & 0x80) == 0)
devfn += 7;
}
}
#else /* CONFIG_MPIC_U3_HT_IRQS */
static inline int mpic_is_ht_interrupt(struct mpic *mpic, unsigned int source)
{
return 0;
}
static void __init mpic_scan_ht_pics(struct mpic *mpic)
{
}
#endif /* CONFIG_MPIC_U3_HT_IRQS */
/* Find an mpic associated with a given linux interrupt */
static struct mpic *mpic_find(unsigned int irq)
{
if (irq < NR_IRQS_LEGACY)
return NULL;
return irq_get_chip_data(irq);
}
/* Determine if the linux irq is an IPI */
static unsigned int mpic_is_ipi(struct mpic *mpic, unsigned int src)
{
return (src >= mpic->ipi_vecs[0] && src <= mpic->ipi_vecs[3]);
}
/* Determine if the linux irq is a timer */
static unsigned int mpic_is_tm(struct mpic *mpic, unsigned int src)
{
return (src >= mpic->timer_vecs[0] && src <= mpic->timer_vecs[7]);
}
/* Convert a cpu mask from logical to physical cpu numbers. */
static inline u32 mpic_physmask(u32 cpumask)
{
int i;
u32 mask = 0;
for (i = 0; i < min(32, NR_CPUS) && cpu_possible(i); ++i, cpumask >>= 1)
mask |= (cpumask & 1) << get_hard_smp_processor_id(i);
return mask;
}
#ifdef CONFIG_SMP
/* Get the mpic structure from the IPI number */
static inline struct mpic * mpic_from_ipi(struct irq_data *d)
{
return irq_data_get_irq_chip_data(d);
}
#endif
/* Get the mpic structure from the irq number */
static inline struct mpic * mpic_from_irq(unsigned int irq)
{
return irq_get_chip_data(irq);
}
/* Get the mpic structure from the irq data */
static inline struct mpic * mpic_from_irq_data(struct irq_data *d)
{
return irq_data_get_irq_chip_data(d);
}
/* Send an EOI */
static inline void mpic_eoi(struct mpic *mpic)
{
mpic_cpu_write(MPIC_INFO(CPU_EOI), 0);
}
/*
* Linux descriptor level callbacks
*/
void mpic_unmask_irq(struct irq_data *d)
{
unsigned int loops = 100000;
struct mpic *mpic = mpic_from_irq_data(d);
unsigned int src = irqd_to_hwirq(d);
DBG("%p: %s: enable_irq: %d (src %d)\n", mpic, mpic->name, d->irq, src);
mpic_irq_write(src, MPIC_INFO(IRQ_VECTOR_PRI),
mpic_irq_read(src, MPIC_INFO(IRQ_VECTOR_PRI)) &
~MPIC_VECPRI_MASK);
/* make sure mask gets to controller before we return to user */
do {
if (!loops--) {
printk(KERN_ERR "%s: timeout on hwirq %u\n",
__func__, src);
break;
}
} while(mpic_irq_read(src, MPIC_INFO(IRQ_VECTOR_PRI)) & MPIC_VECPRI_MASK);
}
void mpic_mask_irq(struct irq_data *d)
{
unsigned int loops = 100000;
struct mpic *mpic = mpic_from_irq_data(d);
unsigned int src = irqd_to_hwirq(d);
DBG("%s: disable_irq: %d (src %d)\n", mpic->name, d->irq, src);
mpic_irq_write(src, MPIC_INFO(IRQ_VECTOR_PRI),
mpic_irq_read(src, MPIC_INFO(IRQ_VECTOR_PRI)) |
MPIC_VECPRI_MASK);
/* make sure mask gets to controller before we return to user */
do {
if (!loops--) {
printk(KERN_ERR "%s: timeout on hwirq %u\n",
__func__, src);
break;
}
} while(!(mpic_irq_read(src, MPIC_INFO(IRQ_VECTOR_PRI)) & MPIC_VECPRI_MASK));
}
void mpic_end_irq(struct irq_data *d)
{
struct mpic *mpic = mpic_from_irq_data(d);
#ifdef DEBUG_IRQ
DBG("%s: end_irq: %d\n", mpic->name, d->irq);
#endif
/* We always EOI on end_irq() even for edge interrupts since that
* should only lower the priority, the MPIC should have properly
* latched another edge interrupt coming in anyway
*/
mpic_eoi(mpic);
}
#ifdef CONFIG_MPIC_U3_HT_IRQS
static void mpic_unmask_ht_irq(struct irq_data *d)
{
struct mpic *mpic = mpic_from_irq_data(d);
unsigned int src = irqd_to_hwirq(d);
mpic_unmask_irq(d);
if (irqd_is_level_type(d))
mpic_ht_end_irq(mpic, src);
}
static unsigned int mpic_startup_ht_irq(struct irq_data *d)
{
struct mpic *mpic = mpic_from_irq_data(d);
unsigned int src = irqd_to_hwirq(d);
mpic_unmask_irq(d);
mpic_startup_ht_interrupt(mpic, src, irqd_is_level_type(d));
return 0;
}
static void mpic_shutdown_ht_irq(struct irq_data *d)
{
struct mpic *mpic = mpic_from_irq_data(d);
unsigned int src = irqd_to_hwirq(d);
mpic_shutdown_ht_interrupt(mpic, src);
mpic_mask_irq(d);
}
static void mpic_end_ht_irq(struct irq_data *d)
{
struct mpic *mpic = mpic_from_irq_data(d);
unsigned int src = irqd_to_hwirq(d);
#ifdef DEBUG_IRQ
DBG("%s: end_irq: %d\n", mpic->name, d->irq);
#endif
/* We always EOI on end_irq() even for edge interrupts since that
* should only lower the priority, the MPIC should have properly
* latched another edge interrupt coming in anyway
*/
if (irqd_is_level_type(d))
mpic_ht_end_irq(mpic, src);
mpic_eoi(mpic);
}
#endif /* !CONFIG_MPIC_U3_HT_IRQS */
#ifdef CONFIG_SMP
static void mpic_unmask_ipi(struct irq_data *d)
{
struct mpic *mpic = mpic_from_ipi(d);
unsigned int src = virq_to_hw(d->irq) - mpic->ipi_vecs[0];
DBG("%s: enable_ipi: %d (ipi %d)\n", mpic->name, d->irq, src);
mpic_ipi_write(src, mpic_ipi_read(src) & ~MPIC_VECPRI_MASK);
}
static void mpic_mask_ipi(struct irq_data *d)
{
/* NEVER disable an IPI... that's just plain wrong! */
}
static void mpic_end_ipi(struct irq_data *d)
{
struct mpic *mpic = mpic_from_ipi(d);
/*
* IPIs are marked IRQ_PER_CPU. This has the side effect of
* preventing the IRQ_PENDING/IRQ_INPROGRESS logic from
* applying to them. We EOI them late to avoid re-entering.
*/
mpic_eoi(mpic);
}
#endif /* CONFIG_SMP */
static void mpic_unmask_tm(struct irq_data *d)
{
struct mpic *mpic = mpic_from_irq_data(d);
unsigned int src = virq_to_hw(d->irq) - mpic->timer_vecs[0];
DBG("%s: enable_tm: %d (tm %d)\n", mpic->name, d->irq, src);
mpic_tm_write(src, mpic_tm_read(src) & ~MPIC_VECPRI_MASK);
mpic_tm_read(src);
}
static void mpic_mask_tm(struct irq_data *d)
{
struct mpic *mpic = mpic_from_irq_data(d);
unsigned int src = virq_to_hw(d->irq) - mpic->timer_vecs[0];
mpic_tm_write(src, mpic_tm_read(src) | MPIC_VECPRI_MASK);
mpic_tm_read(src);
}
int mpic_set_affinity(struct irq_data *d, const struct cpumask *cpumask,
bool force)
{
struct mpic *mpic = mpic_from_irq_data(d);
unsigned int src = irqd_to_hwirq(d);
if (mpic->flags & MPIC_SINGLE_DEST_CPU) {
int cpuid = irq_choose_cpu(cpumask);
mpic_irq_write(src, MPIC_INFO(IRQ_DESTINATION), 1 << cpuid);
} else {
u32 mask = cpumask_bits(cpumask)[0];
mask &= cpumask_bits(cpu_online_mask)[0];
mpic_irq_write(src, MPIC_INFO(IRQ_DESTINATION),
mpic_physmask(mask));
}
return IRQ_SET_MASK_OK;
}
static unsigned int mpic_type_to_vecpri(struct mpic *mpic, unsigned int type)
{
/* Now convert sense value */
switch(type & IRQ_TYPE_SENSE_MASK) {
case IRQ_TYPE_EDGE_RISING:
return MPIC_INFO(VECPRI_SENSE_EDGE) |
MPIC_INFO(VECPRI_POLARITY_POSITIVE);
case IRQ_TYPE_EDGE_FALLING:
case IRQ_TYPE_EDGE_BOTH:
return MPIC_INFO(VECPRI_SENSE_EDGE) |
MPIC_INFO(VECPRI_POLARITY_NEGATIVE);
case IRQ_TYPE_LEVEL_HIGH:
return MPIC_INFO(VECPRI_SENSE_LEVEL) |
MPIC_INFO(VECPRI_POLARITY_POSITIVE);
case IRQ_TYPE_LEVEL_LOW:
default:
return MPIC_INFO(VECPRI_SENSE_LEVEL) |
MPIC_INFO(VECPRI_POLARITY_NEGATIVE);
}
}
int mpic_set_irq_type(struct irq_data *d, unsigned int flow_type)
{
struct mpic *mpic = mpic_from_irq_data(d);
unsigned int src = irqd_to_hwirq(d);
unsigned int vecpri, vold, vnew;
DBG("mpic: set_irq_type(mpic:@%p,virq:%d,src:0x%x,type:0x%x)\n",
mpic, d->irq, src, flow_type);
if (src >= mpic->num_sources)
return -EINVAL;
vold = mpic_irq_read(src, MPIC_INFO(IRQ_VECTOR_PRI));
/* We don't support "none" type */
if (flow_type == IRQ_TYPE_NONE)
flow_type = IRQ_TYPE_DEFAULT;
/* Default: read HW settings */
if (flow_type == IRQ_TYPE_DEFAULT) {
int vold_ps;
vold_ps = vold & (MPIC_INFO(VECPRI_POLARITY_MASK) |
MPIC_INFO(VECPRI_SENSE_MASK));
if (vold_ps == (MPIC_INFO(VECPRI_SENSE_EDGE) |
MPIC_INFO(VECPRI_POLARITY_POSITIVE)))
flow_type = IRQ_TYPE_EDGE_RISING;
else if (vold_ps == (MPIC_INFO(VECPRI_SENSE_EDGE) |
MPIC_INFO(VECPRI_POLARITY_NEGATIVE)))
flow_type = IRQ_TYPE_EDGE_FALLING;
else if (vold_ps == (MPIC_INFO(VECPRI_SENSE_LEVEL) |
MPIC_INFO(VECPRI_POLARITY_POSITIVE)))
flow_type = IRQ_TYPE_LEVEL_HIGH;
else if (vold_ps == (MPIC_INFO(VECPRI_SENSE_LEVEL) |
MPIC_INFO(VECPRI_POLARITY_NEGATIVE)))
flow_type = IRQ_TYPE_LEVEL_LOW;
else
WARN_ONCE(1, "mpic: unknown IRQ type %d\n", vold);
}
/* Apply to irq desc */
irqd_set_trigger_type(d, flow_type);
/* Apply to HW */
if (mpic_is_ht_interrupt(mpic, src))
vecpri = MPIC_VECPRI_POLARITY_POSITIVE |
MPIC_VECPRI_SENSE_EDGE;
else
vecpri = mpic_type_to_vecpri(mpic, flow_type);
vnew = vold & ~(MPIC_INFO(VECPRI_POLARITY_MASK) |
MPIC_INFO(VECPRI_SENSE_MASK));
vnew |= vecpri;
if (vold != vnew)
mpic_irq_write(src, MPIC_INFO(IRQ_VECTOR_PRI), vnew);
return IRQ_SET_MASK_OK_NOCOPY;
}
void mpic_set_vector(unsigned int virq, unsigned int vector)
{
struct mpic *mpic = mpic_from_irq(virq);
unsigned int src = virq_to_hw(virq);
unsigned int vecpri;
DBG("mpic: set_vector(mpic:@%p,virq:%d,src:%d,vector:0x%x)\n",
mpic, virq, src, vector);
if (src >= mpic->num_sources)
return;
vecpri = mpic_irq_read(src, MPIC_INFO(IRQ_VECTOR_PRI));
vecpri = vecpri & ~MPIC_INFO(VECPRI_VECTOR_MASK);
vecpri |= vector;
mpic_irq_write(src, MPIC_INFO(IRQ_VECTOR_PRI), vecpri);
}
static void mpic_set_destination(unsigned int virq, unsigned int cpuid)
{
struct mpic *mpic = mpic_from_irq(virq);
unsigned int src = virq_to_hw(virq);
DBG("mpic: set_destination(mpic:@%p,virq:%d,src:%d,cpuid:0x%x)\n",
mpic, virq, src, cpuid);
if (src >= mpic->num_sources)
return;
mpic_irq_write(src, MPIC_INFO(IRQ_DESTINATION), 1 << cpuid);
}
static struct irq_chip mpic_irq_chip = {
.irq_mask = mpic_mask_irq,
.irq_unmask = mpic_unmask_irq,
.irq_eoi = mpic_end_irq,
.irq_set_type = mpic_set_irq_type,
};
#ifdef CONFIG_SMP
static const struct irq_chip mpic_ipi_chip = {
.irq_mask = mpic_mask_ipi,
.irq_unmask = mpic_unmask_ipi,
.irq_eoi = mpic_end_ipi,
};
#endif /* CONFIG_SMP */
static struct irq_chip mpic_tm_chip = {
.irq_mask = mpic_mask_tm,
.irq_unmask = mpic_unmask_tm,
.irq_eoi = mpic_end_irq,
};
#ifdef CONFIG_MPIC_U3_HT_IRQS
static const struct irq_chip mpic_irq_ht_chip = {
.irq_startup = mpic_startup_ht_irq,
.irq_shutdown = mpic_shutdown_ht_irq,
.irq_mask = mpic_mask_irq,
.irq_unmask = mpic_unmask_ht_irq,
.irq_eoi = mpic_end_ht_irq,
.irq_set_type = mpic_set_irq_type,
};
#endif /* CONFIG_MPIC_U3_HT_IRQS */
static int mpic_host_match(struct irq_domain *h, struct device_node *node,
enum irq_domain_bus_token bus_token)
{
/* Exact match, unless mpic node is NULL */
struct device_node *of_node = irq_domain_get_of_node(h);
return of_node == NULL || of_node == node;
}
static int mpic_host_map(struct irq_domain *h, unsigned int virq,
irq_hw_number_t hw)
{
struct mpic *mpic = h->host_data;
struct irq_chip *chip;
DBG("mpic: map virq %d, hwirq 0x%lx\n", virq, hw);
if (hw == mpic->spurious_vec)
return -EINVAL;
if (mpic->protected && test_bit(hw, mpic->protected)) {
pr_warn("mpic: Mapping of source 0x%x failed, source protected by firmware !\n",
(unsigned int)hw);
return -EPERM;
}
#ifdef CONFIG_SMP
else if (hw >= mpic->ipi_vecs[0]) {
WARN_ON(mpic->flags & MPIC_SECONDARY);
DBG("mpic: mapping as IPI\n");
irq_set_chip_data(virq, mpic);
irq_set_chip_and_handler(virq, &mpic->hc_ipi,
handle_percpu_irq);
return 0;
}
#endif /* CONFIG_SMP */
if (hw >= mpic->timer_vecs[0] && hw <= mpic->timer_vecs[7]) {
WARN_ON(mpic->flags & MPIC_SECONDARY);
DBG("mpic: mapping as timer\n");
irq_set_chip_data(virq, mpic);
irq_set_chip_and_handler(virq, &mpic->hc_tm,
handle_fasteoi_irq);
return 0;
}
if (mpic_map_error_int(mpic, virq, hw))
return 0;
if (hw >= mpic->num_sources) {
pr_warn("mpic: Mapping of source 0x%x failed, source out of range !\n",
(unsigned int)hw);
return -EINVAL;
}
mpic_msi_reserve_hwirq(mpic, hw);
/* Default chip */
chip = &mpic->hc_irq;
#ifdef CONFIG_MPIC_U3_HT_IRQS
/* Check for HT interrupts, override vecpri */
if (mpic_is_ht_interrupt(mpic, hw))
chip = &mpic->hc_ht_irq;
#endif /* CONFIG_MPIC_U3_HT_IRQS */
DBG("mpic: mapping to irq chip @%p\n", chip);
irq_set_chip_data(virq, mpic);
irq_set_chip_and_handler(virq, chip, handle_fasteoi_irq);
/* Set default irq type */
irq_set_irq_type(virq, IRQ_TYPE_DEFAULT);
/* If the MPIC was reset, then all vectors have already been
* initialized. Otherwise, a per source lazy initialization
* is done here.
*/
if (!mpic_is_ipi(mpic, hw) && (mpic->flags & MPIC_NO_RESET)) {
int cpu;
preempt_disable();
cpu = mpic_processor_id(mpic);
preempt_enable();
mpic_set_vector(virq, hw);
mpic_set_destination(virq, cpu);
mpic_irq_set_priority(virq, 8);
}
return 0;
}
static int mpic_host_xlate(struct irq_domain *h, struct device_node *ct,
const u32 *intspec, unsigned int intsize,
irq_hw_number_t *out_hwirq, unsigned int *out_flags)
{
struct mpic *mpic = h->host_data;
static unsigned char map_mpic_senses[4] = {
IRQ_TYPE_EDGE_RISING,
IRQ_TYPE_LEVEL_LOW,
IRQ_TYPE_LEVEL_HIGH,
IRQ_TYPE_EDGE_FALLING,
};
*out_hwirq = intspec[0];
if (intsize >= 4 && (mpic->flags & MPIC_FSL)) {
/*
* Freescale MPIC with extended intspec:
* First two cells are as usual. Third specifies
* an "interrupt type". Fourth is type-specific data.
*
* See Documentation/devicetree/bindings/powerpc/fsl/mpic.txt
*/
switch (intspec[2]) {
case 0:
break;
case 1:
if (!(mpic->flags & MPIC_FSL_HAS_EIMR))
break;
if (intspec[3] >= ARRAY_SIZE(mpic->err_int_vecs))
return -EINVAL;
*out_hwirq = mpic->err_int_vecs[intspec[3]];
break;
case 2:
if (intspec[0] >= ARRAY_SIZE(mpic->ipi_vecs))
return -EINVAL;
*out_hwirq = mpic->ipi_vecs[intspec[0]];
break;
case 3:
if (intspec[0] >= ARRAY_SIZE(mpic->timer_vecs))
return -EINVAL;
*out_hwirq = mpic->timer_vecs[intspec[0]];
break;
default:
pr_debug("%s: unknown irq type %u\n",
__func__, intspec[2]);
return -EINVAL;
}
*out_flags = map_mpic_senses[intspec[1] & 3];
} else if (intsize > 1) {
u32 mask = 0x3;
/* Apple invented a new race of encoding on machines with
* an HT APIC. They encode, among others, the index within
* the HT APIC. We don't care about it here since thankfully,
* it appears that they have the APIC already properly
* configured, and thus our current fixup code that reads the
* APIC config works fine. However, we still need to mask out
* bits in the specifier to make sure we only get bit 0 which
* is the level/edge bit (the only sense bit exposed by Apple),
* as their bit 1 means something else.
*/
if (machine_is(powermac))
mask = 0x1;
*out_flags = map_mpic_senses[intspec[1] & mask];
} else
*out_flags = IRQ_TYPE_NONE;
DBG("mpic: xlate (%d cells: 0x%08x 0x%08x) to line 0x%lx sense 0x%x\n",
intsize, intspec[0], intspec[1], *out_hwirq, *out_flags);
return 0;
}
/* IRQ handler for a secondary MPIC cascaded from another IRQ controller */
static void mpic_cascade(struct irq_desc *desc)
{
struct irq_chip *chip = irq_desc_get_chip(desc);
struct mpic *mpic = irq_desc_get_handler_data(desc);
unsigned int virq;
BUG_ON(!(mpic->flags & MPIC_SECONDARY));
virq = mpic_get_one_irq(mpic);
if (virq)
generic_handle_irq(virq);
chip->irq_eoi(&desc->irq_data);
}
static const struct irq_domain_ops mpic_host_ops = {
.match = mpic_host_match,
.map = mpic_host_map,
.xlate = mpic_host_xlate,
};
static u32 fsl_mpic_get_version(struct mpic *mpic)
{
u32 brr1;
if (!(mpic->flags & MPIC_FSL))
return 0;
brr1 = _mpic_read(mpic->reg_type, &mpic->thiscpuregs,
MPIC_FSL_BRR1);
return brr1 & MPIC_FSL_BRR1_VER;
}
/*
* Exported functions
*/
u32 fsl_mpic_primary_get_version(void)
{
struct mpic *mpic = mpic_primary;
if (mpic)
return fsl_mpic_get_version(mpic);
return 0;
}
struct mpic * __init mpic_alloc(struct device_node *node,
phys_addr_t phys_addr,
unsigned int flags,
unsigned int isu_size,
unsigned int irq_count,
const char *name)
{
int i, psize, intvec_top;
struct mpic *mpic;
u32 greg_feature;
const char *vers;
const u32 *psrc;
u32 last_irq;
u32 fsl_version = 0;
/* Default MPIC search parameters */
static const struct of_device_id __initconst mpic_device_id[] = {
{ .type = "open-pic", },
{ .compatible = "open-pic", },
{},
};
/*
* If we were not passed a device-tree node, then perform the default
* search for standardized a standardized OpenPIC.
*/
if (node) {
node = of_node_get(node);
} else {
node = of_find_matching_node(NULL, mpic_device_id);
if (!node)
return NULL;
}
/* Pick the physical address from the device tree if unspecified */
if (!phys_addr) {
/* Check if it is DCR-based */
if (of_property_read_bool(node, "dcr-reg")) {
flags |= MPIC_USES_DCR;
} else {
struct resource r;
if (of_address_to_resource(node, 0, &r))
goto err_of_node_put;
phys_addr = r.start;
}
}
/* Read extra device-tree properties into the flags variable */
if (of_get_property(node, "big-endian", NULL))
flags |= MPIC_BIG_ENDIAN;
if (of_get_property(node, "pic-no-reset", NULL))
flags |= MPIC_NO_RESET;
if (of_get_property(node, "single-cpu-affinity", NULL))
flags |= MPIC_SINGLE_DEST_CPU;
if (of_device_is_compatible(node, "fsl,mpic")) {
flags |= MPIC_FSL | MPIC_LARGE_VECTORS;
mpic_irq_chip.flags |= IRQCHIP_SKIP_SET_WAKE;
mpic_tm_chip.flags |= IRQCHIP_SKIP_SET_WAKE;
}
mpic = kzalloc(sizeof(struct mpic), GFP_KERNEL);
if (mpic == NULL)
goto err_of_node_put;
mpic->name = name;
mpic->node = node;
mpic->paddr = phys_addr;
mpic->flags = flags;
mpic->hc_irq = mpic_irq_chip;
mpic->hc_irq.name = name;
if (!(mpic->flags & MPIC_SECONDARY))
mpic->hc_irq.irq_set_affinity = mpic_set_affinity;
#ifdef CONFIG_MPIC_U3_HT_IRQS
mpic->hc_ht_irq = mpic_irq_ht_chip;
mpic->hc_ht_irq.name = name;
if (!(mpic->flags & MPIC_SECONDARY))
mpic->hc_ht_irq.irq_set_affinity = mpic_set_affinity;
#endif /* CONFIG_MPIC_U3_HT_IRQS */
#ifdef CONFIG_SMP
mpic->hc_ipi = mpic_ipi_chip;
mpic->hc_ipi.name = name;
#endif /* CONFIG_SMP */
mpic->hc_tm = mpic_tm_chip;
mpic->hc_tm.name = name;
mpic->num_sources = 0; /* so far */
if (mpic->flags & MPIC_LARGE_VECTORS)
intvec_top = 2047;
else
intvec_top = 255;
mpic->timer_vecs[0] = intvec_top - 12;
mpic->timer_vecs[1] = intvec_top - 11;
mpic->timer_vecs[2] = intvec_top - 10;
mpic->timer_vecs[3] = intvec_top - 9;
mpic->timer_vecs[4] = intvec_top - 8;
mpic->timer_vecs[5] = intvec_top - 7;
mpic->timer_vecs[6] = intvec_top - 6;
mpic->timer_vecs[7] = intvec_top - 5;
mpic->ipi_vecs[0] = intvec_top - 4;
mpic->ipi_vecs[1] = intvec_top - 3;
mpic->ipi_vecs[2] = intvec_top - 2;
mpic->ipi_vecs[3] = intvec_top - 1;
mpic->spurious_vec = intvec_top;
/* Look for protected sources */
psrc = of_get_property(mpic->node, "protected-sources", &psize);
if (psrc) {
/* Allocate a bitmap with one bit per interrupt */
mpic->protected = bitmap_zalloc(intvec_top + 1, GFP_KERNEL);
BUG_ON(mpic->protected == NULL);
for (i = 0; i < psize/sizeof(u32); i++) {
if (psrc[i] > intvec_top)
continue;
__set_bit(psrc[i], mpic->protected);
}
}
#ifdef CONFIG_MPIC_WEIRD
mpic->hw_set = mpic_infos[MPIC_GET_REGSET(mpic->flags)];
#endif
/* default register type */
if (mpic->flags & MPIC_BIG_ENDIAN)
mpic->reg_type = mpic_access_mmio_be;
else
mpic->reg_type = mpic_access_mmio_le;
/*
* An MPIC with a "dcr-reg" property must be accessed that way, but
* only if the kernel includes DCR support.
*/
#ifdef CONFIG_PPC_DCR
if (mpic->flags & MPIC_USES_DCR)
mpic->reg_type = mpic_access_dcr;
#else
BUG_ON(mpic->flags & MPIC_USES_DCR);
#endif
/* Map the global registers */
mpic_map(mpic, mpic->paddr, &mpic->gregs, MPIC_INFO(GREG_BASE), 0x1000);
mpic_map(mpic, mpic->paddr, &mpic->tmregs, MPIC_INFO(TIMER_BASE), 0x1000);
if (mpic->flags & MPIC_FSL) {
int ret;
/*
* Yes, Freescale really did put global registers in the
* magic per-cpu area -- and they don't even show up in the
* non-magic per-cpu copies that this driver normally uses.
*/
mpic_map(mpic, mpic->paddr, &mpic->thiscpuregs,
MPIC_CPU_THISBASE, 0x1000);
fsl_version = fsl_mpic_get_version(mpic);
/* Error interrupt mask register (EIMR) is required for
* handling individual device error interrupts. EIMR
* was added in MPIC version 4.1.
*
* Over here we reserve vector number space for error
* interrupt vectors. This space is stolen from the
* global vector number space, as in case of ipis
* and timer interrupts.
*
* Available vector space = intvec_top - 13, where 13
* is the number of vectors which have been consumed by
* ipis, timer interrupts and spurious.
*/
if (fsl_version >= 0x401) {
ret = mpic_setup_error_int(mpic, intvec_top - 13);
if (ret)
return NULL;
}
}
/*
* EPR is only available starting with v4.0. To support
* platforms that don't know the MPIC version at compile-time,
* such as qemu-e500, turn off coreint if this MPIC doesn't
* support it. Note that we never enable it if it wasn't
* requested in the first place.
*
* This is done outside the MPIC_FSL check, so that we
* also disable coreint if the MPIC node doesn't have
* an "fsl,mpic" compatible at all. This will be the case
* with device trees generated by older versions of QEMU.
* fsl_version will be zero if MPIC_FSL is not set.
*/
if (fsl_version < 0x400 && (flags & MPIC_ENABLE_COREINT)) {
WARN_ON(ppc_md.get_irq != mpic_get_coreint_irq);
ppc_md.get_irq = mpic_get_irq;
}
/* Reset */
/* When using a device-node, reset requests are only honored if the MPIC
* is allowed to reset.
*/
if (!(mpic->flags & MPIC_NO_RESET)) {
printk(KERN_DEBUG "mpic: Resetting\n");
mpic_write(mpic->gregs, MPIC_INFO(GREG_GLOBAL_CONF_0),
mpic_read(mpic->gregs, MPIC_INFO(GREG_GLOBAL_CONF_0))
| MPIC_GREG_GCONF_RESET);
while( mpic_read(mpic->gregs, MPIC_INFO(GREG_GLOBAL_CONF_0))
& MPIC_GREG_GCONF_RESET)
mb();
}
/* CoreInt */
if (mpic->flags & MPIC_ENABLE_COREINT)
mpic_write(mpic->gregs, MPIC_INFO(GREG_GLOBAL_CONF_0),
mpic_read(mpic->gregs, MPIC_INFO(GREG_GLOBAL_CONF_0))
| MPIC_GREG_GCONF_COREINT);
if (mpic->flags & MPIC_ENABLE_MCK)
mpic_write(mpic->gregs, MPIC_INFO(GREG_GLOBAL_CONF_0),
mpic_read(mpic->gregs, MPIC_INFO(GREG_GLOBAL_CONF_0))
| MPIC_GREG_GCONF_MCK);
/*
* The MPIC driver will crash if there are more cores than we
* can initialize, so we may as well catch that problem here.
*/
BUG_ON(num_possible_cpus() > MPIC_MAX_CPUS);
/* Map the per-CPU registers */
for_each_possible_cpu(i) {
unsigned int cpu = get_hard_smp_processor_id(i);
mpic_map(mpic, mpic->paddr, &mpic->cpuregs[cpu],
MPIC_INFO(CPU_BASE) + cpu * MPIC_INFO(CPU_STRIDE),
0x1000);
}
/*
* Read feature register. For non-ISU MPICs, num sources as well. On
* ISU MPICs, sources are counted as ISUs are added
*/
greg_feature = mpic_read(mpic->gregs, MPIC_INFO(GREG_FEATURE_0));
/*
* By default, the last source number comes from the MPIC, but the
* device-tree and board support code can override it on buggy hw.
* If we get passed an isu_size (multi-isu MPIC) then we use that
* as a default instead of the value read from the HW.
*/
last_irq = (greg_feature & MPIC_GREG_FEATURE_LAST_SRC_MASK)
>> MPIC_GREG_FEATURE_LAST_SRC_SHIFT;
if (isu_size)
last_irq = isu_size * MPIC_MAX_ISU - 1;
of_property_read_u32(mpic->node, "last-interrupt-source", &last_irq);
if (irq_count)
last_irq = irq_count - 1;
/* Initialize main ISU if none provided */
if (!isu_size) {
isu_size = last_irq + 1;
mpic->num_sources = isu_size;
mpic_map(mpic, mpic->paddr, &mpic->isus[0],
MPIC_INFO(IRQ_BASE),
MPIC_INFO(IRQ_STRIDE) * isu_size);
}
mpic->isu_size = isu_size;
mpic->isu_shift = 1 + __ilog2(mpic->isu_size - 1);
mpic->isu_mask = (1 << mpic->isu_shift) - 1;
mpic->irqhost = irq_domain_add_linear(mpic->node,
intvec_top,
&mpic_host_ops, mpic);
/*
* FIXME: The code leaks the MPIC object and mappings here; this
* is very unlikely to fail but it ought to be fixed anyways.
*/
if (mpic->irqhost == NULL)
return NULL;
/* Display version */
switch (greg_feature & MPIC_GREG_FEATURE_VERSION_MASK) {
case 1:
vers = "1.0";
break;
case 2:
vers = "1.2";
break;
case 3:
vers = "1.3";
break;
default:
vers = "<unknown>";
break;
}
printk(KERN_INFO "mpic: Setting up MPIC \"%s\" version %s at %llx,"
" max %d CPUs\n",
name, vers, (unsigned long long)mpic->paddr, num_possible_cpus());
printk(KERN_INFO "mpic: ISU size: %d, shift: %d, mask: %x\n",
mpic->isu_size, mpic->isu_shift, mpic->isu_mask);
mpic->next = mpics;
mpics = mpic;
if (!(mpic->flags & MPIC_SECONDARY)) {
mpic_primary = mpic;
irq_set_default_host(mpic->irqhost);
}
return mpic;
err_of_node_put:
of_node_put(node);
return NULL;
}
void __init mpic_assign_isu(struct mpic *mpic, unsigned int isu_num,
phys_addr_t paddr)
{
unsigned int isu_first = isu_num * mpic->isu_size;
BUG_ON(isu_num >= MPIC_MAX_ISU);
mpic_map(mpic,
paddr, &mpic->isus[isu_num], 0,
MPIC_INFO(IRQ_STRIDE) * mpic->isu_size);
if ((isu_first + mpic->isu_size) > mpic->num_sources)
mpic->num_sources = isu_first + mpic->isu_size;
}
void __init mpic_init(struct mpic *mpic)
{
int i, cpu;
int num_timers = 4;
BUG_ON(mpic->num_sources == 0);
printk(KERN_INFO "mpic: Initializing for %d sources\n", mpic->num_sources);
/* Set current processor priority to max */
mpic_cpu_write(MPIC_INFO(CPU_CURRENT_TASK_PRI), 0xf);
if (mpic->flags & MPIC_FSL) {
u32 version = fsl_mpic_get_version(mpic);
/*
* Timer group B is present at the latest in MPIC 3.1 (e.g.
* mpc8536). It is not present in MPIC 2.0 (e.g. mpc8544).
* I don't know about the status of intermediate versions (or
* whether they even exist).
*/
if (version >= 0x0301)
num_timers = 8;
}
/* Initialize timers to our reserved vectors and mask them for now */
for (i = 0; i < num_timers; i++) {
unsigned int offset = mpic_tm_offset(mpic, i);
mpic_write(mpic->tmregs,
offset + MPIC_INFO(TIMER_DESTINATION),
1 << hard_smp_processor_id());
mpic_write(mpic->tmregs,
offset + MPIC_INFO(TIMER_VECTOR_PRI),
MPIC_VECPRI_MASK |
(9 << MPIC_VECPRI_PRIORITY_SHIFT) |
(mpic->timer_vecs[0] + i));
}
/* Initialize IPIs to our reserved vectors and mark them disabled for now */
mpic_test_broken_ipi(mpic);
for (i = 0; i < 4; i++) {
mpic_ipi_write(i,
MPIC_VECPRI_MASK |
(10 << MPIC_VECPRI_PRIORITY_SHIFT) |
(mpic->ipi_vecs[0] + i));
}
/* Do the HT PIC fixups on U3 broken mpic */
DBG("MPIC flags: %x\n", mpic->flags);
if ((mpic->flags & MPIC_U3_HT_IRQS) && !(mpic->flags & MPIC_SECONDARY)) {
mpic_scan_ht_pics(mpic);
mpic_u3msi_init(mpic);
}
mpic_pasemi_msi_init(mpic);
cpu = mpic_processor_id(mpic);
if (!(mpic->flags & MPIC_NO_RESET)) {
for (i = 0; i < mpic->num_sources; i++) {
/* start with vector = source number, and masked */
u32 vecpri = MPIC_VECPRI_MASK | i |
(8 << MPIC_VECPRI_PRIORITY_SHIFT);
/* check if protected */
if (mpic->protected && test_bit(i, mpic->protected))
continue;
/* init hw */
mpic_irq_write(i, MPIC_INFO(IRQ_VECTOR_PRI), vecpri);
mpic_irq_write(i, MPIC_INFO(IRQ_DESTINATION), 1 << cpu);
}
}
/* Init spurious vector */
mpic_write(mpic->gregs, MPIC_INFO(GREG_SPURIOUS), mpic->spurious_vec);
/* Disable 8259 passthrough, if supported */
if (!(mpic->flags & MPIC_NO_PTHROU_DIS))
mpic_write(mpic->gregs, MPIC_INFO(GREG_GLOBAL_CONF_0),
mpic_read(mpic->gregs, MPIC_INFO(GREG_GLOBAL_CONF_0))
| MPIC_GREG_GCONF_8259_PTHROU_DIS);
if (mpic->flags & MPIC_NO_BIAS)
mpic_write(mpic->gregs, MPIC_INFO(GREG_GLOBAL_CONF_0),
mpic_read(mpic->gregs, MPIC_INFO(GREG_GLOBAL_CONF_0))
| MPIC_GREG_GCONF_NO_BIAS);
/* Set current processor priority to 0 */
mpic_cpu_write(MPIC_INFO(CPU_CURRENT_TASK_PRI), 0);
#ifdef CONFIG_PM
/* allocate memory to save mpic state */
mpic->save_data = kmalloc_array(mpic->num_sources,
sizeof(*mpic->save_data),
GFP_KERNEL);
BUG_ON(mpic->save_data == NULL);
#endif
/* Check if this MPIC is chained from a parent interrupt controller */
if (mpic->flags & MPIC_SECONDARY) {
int virq = irq_of_parse_and_map(mpic->node, 0);
if (virq) {
printk(KERN_INFO "%pOF: hooking up to IRQ %d\n",
mpic->node, virq);
irq_set_handler_data(virq, mpic);
irq_set_chained_handler(virq, &mpic_cascade);
}
}
/* FSL mpic error interrupt initialization */
if (mpic->flags & MPIC_FSL_HAS_EIMR)
mpic_err_int_init(mpic, MPIC_FSL_ERR_INT);
}
void mpic_irq_set_priority(unsigned int irq, unsigned int pri)
{
struct mpic *mpic = mpic_find(irq);
unsigned int src = virq_to_hw(irq);
unsigned long flags;
u32 reg;
if (!mpic)
return;
raw_spin_lock_irqsave(&mpic_lock, flags);
if (mpic_is_ipi(mpic, src)) {
reg = mpic_ipi_read(src - mpic->ipi_vecs[0]) &
~MPIC_VECPRI_PRIORITY_MASK;
mpic_ipi_write(src - mpic->ipi_vecs[0],
reg | (pri << MPIC_VECPRI_PRIORITY_SHIFT));
} else if (mpic_is_tm(mpic, src)) {
reg = mpic_tm_read(src - mpic->timer_vecs[0]) &
~MPIC_VECPRI_PRIORITY_MASK;
mpic_tm_write(src - mpic->timer_vecs[0],
reg | (pri << MPIC_VECPRI_PRIORITY_SHIFT));
} else {
reg = mpic_irq_read(src, MPIC_INFO(IRQ_VECTOR_PRI))
& ~MPIC_VECPRI_PRIORITY_MASK;
mpic_irq_write(src, MPIC_INFO(IRQ_VECTOR_PRI),
reg | (pri << MPIC_VECPRI_PRIORITY_SHIFT));
}
raw_spin_unlock_irqrestore(&mpic_lock, flags);
}
void mpic_setup_this_cpu(void)
{
#ifdef CONFIG_SMP
struct mpic *mpic = mpic_primary;
unsigned long flags;
u32 msk = 1 << hard_smp_processor_id();
unsigned int i;
BUG_ON(mpic == NULL);
DBG("%s: setup_this_cpu(%d)\n", mpic->name, hard_smp_processor_id());
raw_spin_lock_irqsave(&mpic_lock, flags);
/* let the mpic know we want intrs. default affinity is 0xffffffff
* until changed via /proc. That's how it's done on x86. If we want
* it differently, then we should make sure we also change the default
* values of irq_desc[].affinity in irq.c.
*/
if (distribute_irqs && !(mpic->flags & MPIC_SINGLE_DEST_CPU)) {
for (i = 0; i < mpic->num_sources ; i++)
mpic_irq_write(i, MPIC_INFO(IRQ_DESTINATION),
mpic_irq_read(i, MPIC_INFO(IRQ_DESTINATION)) | msk);
}
/* Set current processor priority to 0 */
mpic_cpu_write(MPIC_INFO(CPU_CURRENT_TASK_PRI), 0);
raw_spin_unlock_irqrestore(&mpic_lock, flags);
#endif /* CONFIG_SMP */
}
int mpic_cpu_get_priority(void)
{
struct mpic *mpic = mpic_primary;
return mpic_cpu_read(MPIC_INFO(CPU_CURRENT_TASK_PRI));
}
void mpic_cpu_set_priority(int prio)
{
struct mpic *mpic = mpic_primary;
prio &= MPIC_CPU_TASKPRI_MASK;
mpic_cpu_write(MPIC_INFO(CPU_CURRENT_TASK_PRI), prio);
}
void mpic_teardown_this_cpu(int secondary)
{
struct mpic *mpic = mpic_primary;
unsigned long flags;
u32 msk = 1 << hard_smp_processor_id();
unsigned int i;
BUG_ON(mpic == NULL);
DBG("%s: teardown_this_cpu(%d)\n", mpic->name, hard_smp_processor_id());
raw_spin_lock_irqsave(&mpic_lock, flags);
/* let the mpic know we don't want intrs. */
for (i = 0; i < mpic->num_sources ; i++)
mpic_irq_write(i, MPIC_INFO(IRQ_DESTINATION),
mpic_irq_read(i, MPIC_INFO(IRQ_DESTINATION)) & ~msk);
/* Set current processor priority to max */
mpic_cpu_write(MPIC_INFO(CPU_CURRENT_TASK_PRI), 0xf);
/* We need to EOI the IPI since not all platforms reset the MPIC
* on boot and new interrupts wouldn't get delivered otherwise.
*/
mpic_eoi(mpic);
raw_spin_unlock_irqrestore(&mpic_lock, flags);
}
static unsigned int _mpic_get_one_irq(struct mpic *mpic, int reg)
{
u32 src;
src = mpic_cpu_read(reg) & MPIC_INFO(VECPRI_VECTOR_MASK);
#ifdef DEBUG_LOW
DBG("%s: get_one_irq(reg 0x%x): %d\n", mpic->name, reg, src);
#endif
if (unlikely(src == mpic->spurious_vec)) {
if (mpic->flags & MPIC_SPV_EOI)
mpic_eoi(mpic);
return 0;
}
if (unlikely(mpic->protected && test_bit(src, mpic->protected))) {
printk_ratelimited(KERN_WARNING "%s: Got protected source %d !\n",
mpic->name, (int)src);
mpic_eoi(mpic);
return 0;
}
return irq_linear_revmap(mpic->irqhost, src);
}
unsigned int mpic_get_one_irq(struct mpic *mpic)
{
return _mpic_get_one_irq(mpic, MPIC_INFO(CPU_INTACK));
}
unsigned int mpic_get_irq(void)
{
struct mpic *mpic = mpic_primary;
BUG_ON(mpic == NULL);
return mpic_get_one_irq(mpic);
}
unsigned int mpic_get_coreint_irq(void)
{
#ifdef CONFIG_BOOKE
struct mpic *mpic = mpic_primary;
u32 src;
BUG_ON(mpic == NULL);
src = mfspr(SPRN_EPR);
if (unlikely(src == mpic->spurious_vec)) {
if (mpic->flags & MPIC_SPV_EOI)
mpic_eoi(mpic);
return 0;
}
if (unlikely(mpic->protected && test_bit(src, mpic->protected))) {
printk_ratelimited(KERN_WARNING "%s: Got protected source %d !\n",
mpic->name, (int)src);
return 0;
}
return irq_linear_revmap(mpic->irqhost, src);
#else
return 0;
#endif
}
unsigned int mpic_get_mcirq(void)
{
struct mpic *mpic = mpic_primary;
BUG_ON(mpic == NULL);
return _mpic_get_one_irq(mpic, MPIC_INFO(CPU_MCACK));
}
#ifdef CONFIG_SMP
void __init mpic_request_ipis(void)
{
struct mpic *mpic = mpic_primary;
int i;
BUG_ON(mpic == NULL);
printk(KERN_INFO "mpic: requesting IPIs...\n");
for (i = 0; i < 4; i++) {
unsigned int vipi = irq_create_mapping(mpic->irqhost,
mpic->ipi_vecs[0] + i);
if (!vipi) {
printk(KERN_ERR "Failed to map %s\n", smp_ipi_name[i]);
continue;
}
smp_request_message_ipi(vipi, i);
}
}
void smp_mpic_message_pass(int cpu, int msg)
{
struct mpic *mpic = mpic_primary;
u32 physmask;
BUG_ON(mpic == NULL);
/* make sure we're sending something that translates to an IPI */
if ((unsigned int)msg > 3) {
printk("SMP %d: smp_message_pass: unknown msg %d\n",
smp_processor_id(), msg);
return;
}
#ifdef DEBUG_IPI
DBG("%s: send_ipi(ipi_no: %d)\n", mpic->name, msg);
#endif
physmask = 1 << get_hard_smp_processor_id(cpu);
mpic_cpu_write(MPIC_INFO(CPU_IPI_DISPATCH_0) +
msg * MPIC_INFO(CPU_IPI_DISPATCH_STRIDE), physmask);
}
void __init smp_mpic_probe(void)
{
int nr_cpus;
DBG("smp_mpic_probe()...\n");
nr_cpus = num_possible_cpus();
DBG("nr_cpus: %d\n", nr_cpus);
if (nr_cpus > 1)
mpic_request_ipis();
}
void smp_mpic_setup_cpu(int cpu)
{
mpic_setup_this_cpu();
}
void mpic_reset_core(int cpu)
{
struct mpic *mpic = mpic_primary;
u32 pir;
int cpuid = get_hard_smp_processor_id(cpu);
int i;
/* Set target bit for core reset */
pir = mpic_read(mpic->gregs, MPIC_INFO(GREG_PROCESSOR_INIT));
pir |= (1 << cpuid);
mpic_write(mpic->gregs, MPIC_INFO(GREG_PROCESSOR_INIT), pir);
mpic_read(mpic->gregs, MPIC_INFO(GREG_PROCESSOR_INIT));
/* Restore target bit after reset complete */
pir &= ~(1 << cpuid);
mpic_write(mpic->gregs, MPIC_INFO(GREG_PROCESSOR_INIT), pir);
mpic_read(mpic->gregs, MPIC_INFO(GREG_PROCESSOR_INIT));
/* Perform 15 EOI on each reset core to clear pending interrupts.
* This is required for FSL CoreNet based devices */
if (mpic->flags & MPIC_FSL) {
for (i = 0; i < 15; i++) {
_mpic_write(mpic->reg_type, &mpic->cpuregs[cpuid],
MPIC_CPU_EOI, 0);
}
}
}
#endif /* CONFIG_SMP */
#ifdef CONFIG_PM
static void mpic_suspend_one(struct mpic *mpic)
{
int i;
for (i = 0; i < mpic->num_sources; i++) {
mpic->save_data[i].vecprio =
mpic_irq_read(i, MPIC_INFO(IRQ_VECTOR_PRI));
mpic->save_data[i].dest =
mpic_irq_read(i, MPIC_INFO(IRQ_DESTINATION));
}
}
static int mpic_suspend(void)
{
struct mpic *mpic = mpics;
while (mpic) {
mpic_suspend_one(mpic);
mpic = mpic->next;
}
return 0;
}
static void mpic_resume_one(struct mpic *mpic)
{
int i;
for (i = 0; i < mpic->num_sources; i++) {
mpic_irq_write(i, MPIC_INFO(IRQ_VECTOR_PRI),
mpic->save_data[i].vecprio);
mpic_irq_write(i, MPIC_INFO(IRQ_DESTINATION),
mpic->save_data[i].dest);
#ifdef CONFIG_MPIC_U3_HT_IRQS
if (mpic->fixups) {
struct mpic_irq_fixup *fixup = &mpic->fixups[i];
if (fixup->base) {
/* we use the lowest bit in an inverted meaning */
if ((mpic->save_data[i].fixup_data & 1) == 0)
continue;
/* Enable and configure */
writeb(0x10 + 2 * fixup->index, fixup->base + 2);
writel(mpic->save_data[i].fixup_data & ~1,
fixup->base + 4);
}
}
#endif
} /* end for loop */
}
static void mpic_resume(void)
{
struct mpic *mpic = mpics;
while (mpic) {
mpic_resume_one(mpic);
mpic = mpic->next;
}
}
static struct syscore_ops mpic_syscore_ops = {
.resume = mpic_resume,
.suspend = mpic_suspend,
};
static int mpic_init_sys(void)
{
int rc;
register_syscore_ops(&mpic_syscore_ops);
rc = subsys_system_register(&mpic_subsys, NULL);
if (rc) {
unregister_syscore_ops(&mpic_syscore_ops);
pr_err("mpic: Failed to register subsystem!\n");
return rc;
}
return 0;
}
device_initcall(mpic_init_sys);
#endif
|
53655.c | /* mpn_div_qr_2u_pi1
Contributed to the GNU project by Niels Möller
THIS FILE CONTAINS INTERNAL FUNCTIONS WITH MUTABLE INTERFACES. IT IS ONLY
SAFE TO REACH THEM THROUGH DOCUMENTED INTERFACES. IN FACT, IT IS ALMOST
GUARANTEED THAT THEY'LL CHANGE OR DISAPPEAR IN A FUTURE GNU MP RELEASE.
Copyright 2011 Free Software Foundation, Inc.
This file is part of the GNU MP Library.
The GNU MP Library is free software; you can redistribute it and/or modify
it under the terms of either:
* the GNU Lesser General Public License as published by the Free
Software Foundation; either version 3 of the License, or (at your
option) any later version.
or
* the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any
later version.
or both in parallel, as here.
The GNU MP 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 General Public License
for more details.
You should have received copies of the GNU General Public License and the
GNU Lesser General Public License along with the GNU MP Library. If not,
see https://www.gnu.org/licenses/. */
#include "gmp.h"
#include "gmp-impl.h"
#include "longlong.h"
/* 3/2 loop, for unnormalized divisor. Caller must pass shifted d1 and
d0, while {np,nn} is shifted on the fly. */
mp_limb_t
mpn_div_qr_2u_pi1 (mp_ptr qp, mp_ptr rp, mp_srcptr np, mp_size_t nn,
mp_limb_t d1, mp_limb_t d0, int shift, mp_limb_t di)
{
mp_limb_t qh;
mp_limb_t r2, r1, r0;
mp_size_t i;
ASSERT (nn >= 2);
ASSERT (d1 & GMP_NUMB_HIGHBIT);
ASSERT (shift > 0);
r2 = np[nn-1] >> (GMP_LIMB_BITS - shift);
r1 = (np[nn-1] << shift) | (np[nn-2] >> (GMP_LIMB_BITS - shift));
r0 = np[nn-2] << shift;
udiv_qr_3by2 (qh, r2, r1, r2, r1, r0, d1, d0, di);
for (i = nn - 2 - 1; i >= 0; i--)
{
mp_limb_t q;
r0 = np[i];
r1 |= r0 >> (GMP_LIMB_BITS - shift);
r0 <<= shift;
udiv_qr_3by2 (q, r2, r1, r2, r1, r0, d1, d0, di);
qp[i] = q;
}
rp[0] = (r1 >> shift) | (r2 << (GMP_LIMB_BITS - shift));
rp[1] = r2 >> shift;
return qh;
}
|
850493.c | /*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
*/
/*
* SCSI Enclosure Services Log Transport Module
*
* This transport module is responsible for accessing the ses devices seen
* from this host, reading their logs, generating ereports for targeted
* entries, and then writing the log contents to a well known location in
* the filesystem.
*
*/
#include <ctype.h>
#include <fm/fmd_api.h>
#include <fm/libtopo.h>
#include <fm/topo_hc.h>
#include <fm/topo_mod.h>
#include <limits.h>
#include <string.h>
#include <sys/fm/io/scsi.h>
#include <sys/fm/protocol.h>
#include <stdio.h>
#include <time.h>
#include <fm/libseslog.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
/*
* This struct contains the default property values. These may
* be overridden by entries in a ses_log_transport.conf file.
* The severity is set to -1 here so that the _fmd_init routine will
* determine the default severity based on the constants in libseslog.h.
*/
static const fmd_prop_t fmd_props[] = {
{ "interval", FMD_TYPE_TIME, "60s"},
{ "severity", FMD_TYPE_INT32, "-1"},
{ "path", FMD_TYPE_STRING, "/var/fm/fmd/ses_logs/"},
{ "logcount", FMD_TYPE_UINT32, "5"},
{ "maxlogsize", FMD_TYPE_UINT32, "1000000"},
{ NULL, 0, NULL}
};
/* Maintains statistics on dropped ereports. */
static struct slt_stat
{
fmd_stat_t dropped;
} slt_stats = {
{ "dropped", FMD_TYPE_UINT64, "number of dropped ereports"}
};
/*
* This structure maintains a reference to the input values, transport, and
* other data which is held by FMD and retrieved whenever an entry point
* is called.
*/
typedef struct ses_log_monitor
{
fmd_hdl_t *slt_hdl; /* opaque handle for this transport */
fmd_xprt_t *slt_xprt; /* ereport transport */
id_t slt_timer; /* Timer for FMD polling use */
hrtime_t slt_interval; /* Polling interval */
int32_t slt_severity; /* Min severity for logging ereports */
char *slt_path; /* Output path for log files */
int32_t slt_log_count; /* Max rolled logs to keep */
int32_t slt_max_log_size; /* Max log size before rolling */
nvlist_t *slt_expanders; /* List of expander log entries */
} ses_log_monitor_t;
/* Contains expander log data retrieved from a topology node */
typedef struct expander
{
char slt_label[MAXNAMELEN]; /* The expander name */
char slt_pid[MAXNAMELEN]; /* The system product id */
char slt_key[MAXNAMELEN]; /* The expander key (sas address) */
char slt_path[MAXPATHLEN]; /* The ses path to the expander */
nvlist_t *fmri; /* The fmri for this target */
} expander_t;
#define DATA_FIELD "data" /* Label for the expander details */
#define DEFAULT_DATA "0" /* Default expander details value */
#define MIN_LOG_SIZE 100000 /* The minimum log file size. */
#define MIN_LOG_COUNT 1 /* Num of rolled files to keep */
#define EXAMINE_FMRI_VALUE 0 /* Extract fmri val */
#define INVERT_FMRI_INSTANCE 1 /* Invert an FMRI instance value */
#define FATAL_ERROR "fatal" /* ereport val for fatal errors */
#define NON_FATAL_ERROR "non-fatal" /* val for non fatal errors */
#define INVALID_OPERATION 0x01 /* Invalid access_fmri operation */
#define NULL_LOG_DATA 0x02 /* Lib returned NULL log ref */
#define INVALID_SEVERITY 0x03 /* Invalid severity value */
#define DATE_STRING_SIZE 16 /* Size of date string prefix. */
/* Prototype needed for use in declaring and populating tables */
static int invert_fmri(ses_log_monitor_t *, nvlist_t *);
/* Holds a code-operation pair. Contains a log code an a function ptr */
typedef struct code_operation {
int code;
int (*func_ptr)(ses_log_monitor_t *, nvlist_t *);
} code_operation_t;
/* Holds a platform type and a list of code-operation structures */
typedef struct platform {
const char *pid;
int count;
code_operation_t *codes;
} platform_t;
/* Holds a reference to all of the platforms */
typedef struct platforms {
int pcount;
platform_t *plist;
} platforms_t;
/* This is the genesis list of codes and functions. */
static code_operation_t genesis_codes[] = {
{ 684002, invert_fmri }, /* Alternate expander is down */
{ 685002, invert_fmri } /* Alternate expander is down */
};
/* This is the list of all platforms and their associated code op pairs. */
static platform_t platform_list[] = {
{ "SUN-GENESIS",
sizeof (genesis_codes) / sizeof (code_operation_t),
genesis_codes }
};
/* This structure holds a reference to the platform list. */
static const platforms_t platforms = {
sizeof (platform_list) / sizeof (platform_t),
platform_list
};
/*
* Post ereports using this method.
*/
static void
slt_post_ereport(fmd_hdl_t *hdl, fmd_xprt_t *xprt, const char *ereport_class,
uint64_t ena, nvlist_t *detector, nvlist_t *payload)
{
nvlist_t *nvl;
int e = 0;
char fullclass[PATH_MAX];
(void) snprintf(fullclass, sizeof (fullclass), "%s.io.sas.log.%s",
FM_EREPORT_CLASS, ereport_class);
if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) == 0) {
e |= nvlist_add_string(nvl, FM_CLASS, fullclass);
e |= nvlist_add_uint8(nvl, FM_VERSION, FM_EREPORT_VERSION);
e |= nvlist_add_uint64(nvl, FM_EREPORT_ENA, ena);
e |= nvlist_add_nvlist(nvl, FM_EREPORT_DETECTOR, detector);
e |= nvlist_merge(nvl, payload, 0);
if (e == 0) {
fmd_xprt_post(hdl, xprt, nvl, 0);
} else {
nvlist_free(nvl);
fmd_hdl_debug(hdl, "Error adding fields to ereport");
slt_stats.dropped.fmds_value.ui64++;
}
} else {
fmd_hdl_debug(hdl, "Could not allocate space for ereport");
slt_stats.dropped.fmds_value.ui64++;
}
}
/*
* Create a directory if it doesn't exist.
* Parameters:
* path: The directory path to create.
* mode: The mode used when creating the directory.
*/
static int
do_mkdir(const char *path, mode_t mode)
{
struct stat st;
int status = 0;
if (stat(path, &st) != 0) {
/* Directory does not exist */
if (mkdir(path, mode) != 0)
status = -1;
} else if (!S_ISDIR(st.st_mode)) {
errno = ENOTDIR;
status = -1;
}
return (status);
}
/*
* Validates that all directories in path exist
* path: The directory path to create.
* mode: The mode used when creating the directory.
*/
static int
mkpath(char *path, mode_t mode)
{
char *pp;
char *sp;
int status = 0;
pp = path;
while (status == 0 && (sp = strchr(pp, '/')) != 0) {
if (sp != pp) {
/* Neither root nor double slash in path */
*sp = '\0';
status = do_mkdir(path, mode);
*sp = '/';
}
pp = sp + 1;
}
return (status);
}
/*
* Rotate the file from base.max-1->base.max, ... base.1->base.2, base->base.1
* Parameter:
* file: The name of the current log file.
*/
void
check_file_size(ses_log_monitor_t *slmp, char *file, int byte_count)
{
int i;
char newFile[MAXPATHLEN];
char oldName[MAXPATHLEN];
struct stat st;
int size;
stat(file, &st);
size = st.st_size;
/*
* If current file size plus what will be added is larger
* than max file size, rotate the logs
* For check to see if larger than configured max size.
*/
if (size + byte_count < slmp->slt_max_log_size) {
/* next log entries can fit */
return;
}
/* next log entries could make log entries too large */
for (i = slmp->slt_log_count; i > 1; i--) {
(void) snprintf(newFile, MAXPATHLEN, "%s.%x", file, i);
(void) snprintf(oldName, MAXPATHLEN, "%s.%x", file, i - 1);
(void) rename(oldName, newFile);
}
/* Finally move base to base.1 */
(void) rename(file, oldName);
}
/*
* This method exists to give access into the fmri. One purpose is to flip the
* instance number on the FMRI for a given hc-list entry. It is also
* used to pull the value of an hc-list entry. In all cases, the function
* returns the value of the hc-list entry found, NULL if no value was found.
*/
static char *
access_fmri(ses_log_monitor_t *slmp, nvlist_t *fmri, char *target,
int operation, int *err)
{
int i;
nvpair_t *nvp;
nvpair_t *nvp2;
uint_t nelem;
nvlist_t **nvl_array;
char *name;
int ival;
char ivs[25];
char *target_val = NULL;
if ((*err = nvlist_lookup_nvpair(fmri, "hc-list", &nvp)) != 0) {
fmd_hdl_debug(slmp->slt_hdl, "No hc-list in the fmri");
return (NULL);
}
/* hc-list is an array of nvlists */
(void) nvpair_value_nvlist_array(nvp, &nvl_array, &nelem);
/*
* Loop until you find the list that has hc-name that equals the
* passed in "target" value (such as controller) in it.
*/
for (i = 0; i < nelem; i++) {
/* Skip this pair if it is not labeled hc-name */
if ((nvlist_lookup_nvpair(nvl_array[i], "hc-name", &nvp2))
!= 0) {
continue;
}
/*
* Extract the value of the name. Continue on an error because
* we want to check all of the hc-name entries.
*/
if (nvpair_value_string(nvp2, &name) != 0) {
continue;
}
/* If this isn't the target, go to the next pair. */
if (strcmp(name, target) != 0) {
continue;
}
if ((*err = nvlist_lookup_nvpair(nvl_array[i], "hc-id", &nvp2))
!= 0) {
fmd_hdl_debug(slmp->slt_hdl,
"Could not find hc-id in the fmri for %s", target);
return (NULL);
}
/*
* This is the target pair. If we can't get the value then
* exit out and log an error.
*/
if ((*err = nvpair_value_string(nvp2, &target_val)) != 0) {
fmd_hdl_debug(slmp->slt_hdl,
"Target value not returned.");
return (NULL);
}
switch (operation) {
case INVERT_FMRI_INSTANCE:
ival = atoi(target_val);
ival = (ival + 1) % 2;
(void) snprintf(ivs, sizeof (ivs), "%d", ival);
if ((*err = nvlist_remove_nvpair(nvl_array[i], nvp2))
== 0) {
if ((*err = nvlist_add_string(nvl_array[i],
"hc-id", ivs)) != 0) {
fmd_hdl_debug(slmp->slt_hdl,
"Error setting ivalue.");
}
} else {
fmd_hdl_debug(slmp->slt_hdl,
"Error removing original ivalue.");
}
break;
case EXAMINE_FMRI_VALUE:
/*
* target_val is already set. Return without modifying
* its value.
*/
break;
/* Can return target_val as is (NULL) */
default:
*err = INVALID_OPERATION;
break;
} /* End switch on operation */
/* Exit the loop. You have found the target */
break;
}
return (target_val);
}
/*
* Generate a filename based on the target path
* Parameters:
* filename: The space for the generated output log file name.
* expander: An expander_t struct containing path, pid etc info from the node.
* slmp: A pointer to the transport data structure which contains the
* configurable file parameters.
* byte_count: The number of bytes that will be added to the target file for
* this expander.
*/
static int
create_filename(char *fileName, expander_t *expander, ses_log_monitor_t *slmp,
int byte_count)
{
char *ses_node;
int i;
int label_length;
int status = 0;
char *subchassis_val = NULL;
/*
* Add the file name with the path root
* and append a forward slash if one is not there.
*/
(void) snprintf(fileName, MAXPATHLEN, "%s", slmp->slt_path);
ses_node = strrchr(fileName, '/');
if ((ses_node != NULL) && (ses_node[0] != '\0')) {
(void) strlcat(fileName, "/", MAXPATHLEN);
}
ses_node = strrchr(expander->slt_path, '/');
(void) strlcat(fileName, ses_node + 1, MAXPATHLEN);
/*
* If a subchassis is defined, include it in the file name.
* Errors are logged in the function. There may legitimately be no
* subchassis, so simply continue if none is found.
*/
subchassis_val = access_fmri(slmp, expander->fmri, SUBCHASSIS,
EXAMINE_FMRI_VALUE, &status);
if (subchassis_val != NULL) {
(void) strlcat(fileName, "_", MAXPATHLEN);
(void) strlcat(fileName, SUBCHASSIS, MAXPATHLEN);
(void) strlcat(fileName, subchassis_val, MAXPATHLEN);
}
(void) strlcat(fileName, "_", MAXPATHLEN);
/* remove spaces and forward slashes from name */
label_length = strlen(expander->slt_label);
for (i = 0; i < label_length; i++) {
if ((!isspace(expander->slt_label[i])) &&
('/' != expander->slt_label[i])) {
(void) strncat(fileName, &expander->slt_label[i], 1);
}
}
(void) strlcat(fileName, "/log", MAXPATHLEN);
/*
* Ensure directory structure exists for log file.
*/
status = mkpath(fileName, 0744);
/*
* Check size of file and rotate if necessary.
*/
check_file_size(slmp, fileName, byte_count);
return (status);
}
/*
* Determines the error class type based on the severity of the entry.
* Parameter
* severity: A severity level from a log entry.
*/
static char *
error_type(int severity)
{
char *rval;
switch (severity) {
case SES_LOG_LEVEL_FATAL:
rval = FATAL_ERROR;
break;
case SES_LOG_LEVEL_ERROR:
rval = NON_FATAL_ERROR;
break;
default:
rval = NULL;
break;
}
return (rval);
}
/*
* Allocates and adds an entry for a given expander to the expander list.
* Parameters
* slmp: A pointer to the ses_log_monitor_t struct for this transport.
* key: A unique identifier for this expander.
*/
static int
add_expander_record(ses_log_monitor_t *slmp, char *key)
{
nvlist_t *expanderDetails;
int status = 0;
if ((status = nvlist_alloc(&expanderDetails, NV_UNIQUE_NAME, 0)) != 0) {
fmd_hdl_debug(slmp->slt_hdl,
"Error allocating expander detail space (%d)", status);
return (status);
}
if ((status = nvlist_add_string(expanderDetails, DATA_FIELD,
DEFAULT_DATA)) != 0) {
fmd_hdl_debug(slmp->slt_hdl,
"Error adding default data to expander details (%d)",
status);
} else {
if ((status = nvlist_add_nvlist(slmp->slt_expanders, key,
expanderDetails)) != 0) {
fmd_hdl_debug(slmp->slt_hdl,
"Error storing the default expander details (%d)",
status);
}
}
nvlist_free(expanderDetails);
return (status);
}
/*
* Retrieves the expander record nvlist that is associated with the
* expander identified by the given key. If no match is found, an
* entry is created with default values.
* Parameters
* slmp: A pointer to the ses_log_monitor_t struct for this transport.
* key: A pointer to the key for an expander.
* expdata: A pointer to a pointer for the last log entry data for this
* expander.
*/
static int
get_last_entry(ses_log_monitor_t *slmp, char *key, char **expdata)
{
nvlist_t *expanderRecord;
int err = 0;
/*
* Retrieve the expander record that matches this expander. A default
* entry will be returned if no matching entry is found.
*/
if ((err = nvlist_lookup_nvlist(slmp->slt_expanders, key,
&expanderRecord)) != 0) {
if ((err = add_expander_record(slmp, key)) != 0) {
fmd_hdl_debug(slmp->slt_hdl,
"Expander add failed for %s", key);
return (err);
}
if ((err = nvlist_lookup_nvlist(slmp->slt_expanders, key,
&expanderRecord)) != 0) {
fmd_hdl_debug(slmp->slt_hdl,
"Could not retrieve the data after adding it", key);
return (err);
}
}
if ((err = nvlist_lookup_string(expanderRecord, DATA_FIELD, expdata))
!= 0) {
fmd_hdl_debug(slmp->slt_hdl,
"Could not retrieve the expander data field (%d)", err);
return (err);
}
return (err);
}
/*
* Searches the platform lists for target codes. If a match is found then
* it calls then indicated function.
*/
static int
check_code(ses_log_monitor_t *slmp, nvlist_t *fmri, char *pid, int code)
{
int status = 0;
int i, x;
for (i = 0; i < platforms.pcount; i++) {
if (strcmp(platforms.plist[i].pid, pid) == 0) {
for (x = 0; x < platforms.plist[i].count; x++) {
if (code == platforms.plist[i].codes[x].code) {
status = platforms.plist[i].codes[x].
func_ptr(slmp, fmri);
break;
}
}
break;
}
}
if (status != 0) {
fmd_hdl_debug(slmp->slt_hdl,
"Error checking for a code action (%d)", status);
}
return (status);
}
/*
* Searches the platform lists for for a match on the supplied product id.
* Returns non zero if supported, zero otherwise.
*/
static int
platform_supported(char *pid)
{
int supported = 0;
int i;
for (i = 0; i < platforms.pcount; i++) {
if (strcmp(platforms.plist[i].pid, pid) == 0) {
supported = 1;
break;
}
}
return (supported);
}
/*
* Inverts the controller instance and the expander instance in the
* specified FMRI.
*/
static int
invert_fmri(ses_log_monitor_t *slmp, nvlist_t *fmri)
{
int err = 0;
(void) access_fmri(slmp, fmri, CONTROLLER, INVERT_FMRI_INSTANCE, &err);
if (err != 0) {
fmd_hdl_debug(slmp->slt_hdl,
"error inverting the controller instance: %d", err);
return (err);
}
(void) access_fmri(slmp, fmri, SASEXPANDER, INVERT_FMRI_INSTANCE, &err);
if (err != 0) {
fmd_hdl_debug(slmp->slt_hdl,
"error inverting sas-expander instance: %d", err);
}
return (err);
}
/*
* Checks the severity of the log entry against the configured boundary,
* generates and ereport, and writes the data out to the log file.
* Parameters
* slmp: A pointer to the ses_log_monitor_t struct for this transport.
* entry: The log entry
* ena: the ena for this transport.
* expander: Contains derived information for this expander.
* format_time: The formatted time to append to this entry.
* fp: A file pointer for the data to be written out to.
*/
static int
handle_log_entry(ses_log_monitor_t *slmp, nvpair_t *entry,
expander_t *expander, char *format_time, FILE *fp)
{
nvlist_t *entry_data;
char *log_entry;
char *severity;
int severityValue = 0;
char *code;
char *class_sev = NULL;
uint64_t ena;
int rval = 0;
if ((rval = nvpair_value_nvlist(entry, &entry_data)) != 0) {
fmd_hdl_debug(slmp->slt_hdl, "Unable to retrieve entry");
return (rval);
}
if ((rval = nvlist_lookup_string(entry_data, ENTRY_SEVERITY, &severity))
== 0) {
severityValue = atoi(severity);
if (severityValue >= slmp->slt_severity) {
/*
* Pull the code and check to see if there are any
* special operations to perform for it on the given
* platform.
*/
if ((rval = nvlist_lookup_string(entry_data, ENTRY_CODE,
&code)) != 0) {
fmd_hdl_debug(slmp->slt_hdl,
"Error retrieving code: %d", rval);
return (rval);
}
/*
* Check this code for any actions specific
* to this platform.
*/
(void) check_code(slmp, expander->fmri,
expander->slt_pid, atoi(code));
class_sev = error_type(severityValue);
if (class_sev == NULL) {
fmd_hdl_debug(slmp->slt_hdl,
"log severity %d mapped to NULL", severity);
return (INVALID_SEVERITY);
}
/* Create the ENA for this ereport */
ena = fmd_event_ena_create(slmp->slt_hdl);
slt_post_ereport(slmp->slt_hdl, slmp->slt_xprt,
class_sev, ena, expander->fmri, entry_data);
}
} else {
fmd_hdl_debug(slmp->slt_hdl,
"Unable to pull severity from the entry.");
return (rval);
}
/*
* Append the log entry to the log file.
*/
if (fp) {
if ((rval = nvlist_lookup_string(entry_data, ENTRY_LOG,
&log_entry)) == 0) {
(void) fprintf(fp, "%s %s\n", format_time,
log_entry);
} else {
fmd_hdl_debug(slmp->slt_hdl,
"Unable to pull log from the entry.");
}
}
return (rval);
}
/*
* The function performs the work of deallocating the space used for an
* expander_t structure.
* Parameters:
* slmp: A pointer to t ses_log_monitor_t struct for this transport.
* exp: A pointer to an expander_t structure that identifies an expander.
*/
static void
free_expander(ses_log_monitor_t *slmp, expander_t *exp)
{
if (exp != NULL) {
if (exp->fmri != NULL) {
nvlist_free(exp->fmri);
}
fmd_hdl_free(slmp->slt_hdl, exp, sizeof (expander_t));
}
}
/*
* This function performs the log read on a target
*
* Parameters:
* slmp: A pointer to the ses log monitor structure.
* expander: A pointer to an expander object that contains info required
* for a call to the libseslog library.
* lib_param: The structure used to pass data to and from the library. This
* contains the target's information as well as a ponter to returned data.
*/
static int
get_log(ses_log_monitor_t *slmp, expander_t *expander,
struct ses_log_call_struct *lib_param)
{
char *expdata;
int err;
nvlist_t *expanderRecord;
/* Retrieve the last entry for this expander for the lib call */
if ((err = get_last_entry(slmp, expander->slt_key, &expdata)) != 0) {
fmd_hdl_debug(slmp->slt_hdl, "Error collecting expander entry");
return (err);
}
(void) strncpy(lib_param->target_path, expander->slt_path, MAXPATHLEN);
(void) strncpy(lib_param->product_id, expander->slt_pid, MAXNAMELEN);
(void) strncpy(lib_param->last_log_entry, expdata, MAXNAMELEN);
lib_param->poll_time = slmp->slt_interval;
/*
* If the library call returned non zero, log it, however, the call
* may still have returned valid log data. Check the log data. If it
* is NULL, return an error. Otherwise continue processing.
*/
if ((err = access_ses_log(lib_param)) != 0) {
fmd_hdl_debug(slmp->slt_hdl, "Library access error: %d", err);
}
/* Double check that log data actually exists. */
if (lib_param->log_data == NULL) {
if (err != 0) {
return (err);
}
return (NULL_LOG_DATA);
}
/*
* If we can retrieve the expander details for this expander then store
* the last log entry returned from the library. Otherwise log it
* and continue processing.
*/
if ((err = nvlist_lookup_nvlist(slmp->slt_expanders, expander->slt_key,
&expanderRecord)) == 0) {
if (nvlist_add_string(expanderRecord, DATA_FIELD,
lib_param->last_log_entry) != 0) {
fmd_hdl_debug(slmp->slt_hdl,
"Error saving buffer data in expander details");
}
} else {
fmd_hdl_debug(slmp->slt_hdl,
"Could not retrieve expander to store last entry: %d", err);
}
return (err);
}
/*
* This function processes the log data from a target. This includes
* writing the data to the filesystem and initiating generation of ereports
* as needed by calling slt_post_ereport.
*
*
* Parameters:
* slmp: A pointer to the ses log monitor structure.
* expander: A pointer to an expander object that contains info about the
* expander.
* lib_param: The structure used to pass data to and from the library. This
* contains the target's information as well as a ponter to returned data.
*/
static int
process_log(ses_log_monitor_t *slmp, expander_t *expander,
struct ses_log_call_struct *lib_param)
{
nvlist_t *result;
int err;
char *pairName;
nvpair_t *entry = NULL;
FILE *fp = NULL;
char fileName[MAXPATHLEN];
time_t now;
char format_time[30];
struct tm tim;
int output_count;
/*
* Determine how many bytes will be written out with this response,
* pass this count to a function that will determine whether or not
* to roll the logs, and will return the name of the file path to use.
*/
output_count = lib_param->number_log_entries * DATE_STRING_SIZE +
lib_param->size_of_log_entries;
err = create_filename(fileName, expander, slmp, output_count);
if (err == 0) {
fp = fopen(fileName, "a");
if (fp == NULL) {
fmd_hdl_debug(slmp->slt_hdl, "File open failed");
}
}
/* Format the time to prepend to the log entry */
now = time(NULL);
tim = *(localtime(&now));
(void) strftime(format_time, 30, "%b %d %H:%M:%S ", &tim);
/*
* For each entry returned, generate an ereport if the severity
* is at or above the target level, then append all entries to
* the appropriate log file.
*/
result = lib_param->log_data;
while ((entry = nvlist_next_nvpair(result, entry)) != NULL) {
pairName = nvpair_name(entry);
/*
* Process each entry in the result data returned from
* the library call. These are log entries and may
* warrant an ereport.
*/
if (strncmp(ENTRY_PREFIX, pairName, 5) == 0) {
err = handle_log_entry(slmp, entry, expander,
format_time, fp);
}
}
/* Close the log file */
if (fp) {
(void) fclose(fp);
fp = NULL;
}
/* Free the space used for the result and the fmri. */
nvlist_free(result);
return (0);
}
/*
* This function performs the log read and processing of the logs for a target
* as well as writing the data to the filesystem. Ereports are generated
* as needed by calling slt_post_ereport.
*
* Access the log data for a specific ses.
* If a log entry should generate an ereport, call slt_post_ereport
* Format and store the data at the appropriate location.
*/
static int
slt_process_ses_log(topo_hdl_t *thp, tnode_t *node, void *arg)
{
ses_log_monitor_t *slmp = arg;
nvlist_t *fmri;
expander_t *expander;
struct ses_log_call_struct lib_param;
int err = 0;
char *label = NULL;
char *target_path = NULL;
char *product_id = NULL;
char *sas_address = NULL;
if (strcmp(SASEXPANDER, topo_node_name(node)) != 0) {
/* Not the type of node we are looking for */
return (TOPO_WALK_NEXT);
}
if (topo_prop_get_string(node, "authority", "product-id",
&product_id, &err) != 0) {
fmd_hdl_debug(slmp->slt_hdl,
"Error collecting product_id %d", err);
return (TOPO_WALK_NEXT);
}
/* If the current system type is unsupported stop processing the node */
if (platform_supported(product_id) == 0) {
fmd_hdl_debug(slmp->slt_hdl, "Unsupported platform %d",
product_id);
topo_hdl_strfree(thp, product_id);
return (TOPO_WALK_NEXT);
}
/* Allocate space for the holder structure */
expander = (expander_t *)fmd_hdl_zalloc(slmp->slt_hdl,
sizeof (expander_t), FMD_SLEEP);
(void) snprintf(expander->slt_pid, MAXNAMELEN, "%s", product_id);
topo_hdl_strfree(thp, product_id);
if (topo_prop_get_string(node, "protocol", "label", &label, &err)
!= 0) {
fmd_hdl_debug(slmp->slt_hdl, "Error collecting label %d", err);
free_expander(slmp, expander);
return (TOPO_WALK_NEXT);
}
(void) snprintf(expander->slt_label, MAXNAMELEN, "%s", label);
topo_hdl_strfree(thp, label);
if (topo_prop_get_string(node, TOPO_PGROUP_SES,
TOPO_PROP_SES_DEV_PATH, &target_path, &err) != 0) {
fmd_hdl_debug(slmp->slt_hdl,
"Error collecting ses-devfs-path for %s: %d",
expander->slt_label, err);
free_expander(slmp, expander);
return (TOPO_WALK_NEXT);
}
(void) snprintf(expander->slt_path, MAXPATHLEN, "%s", target_path);
topo_hdl_strfree(thp, target_path);
if (topo_prop_get_string(node, TOPO_PGROUP_STORAGE,
TOPO_PROP_SAS_ADDR, &sas_address, &err) != 0) {
fmd_hdl_debug(slmp->slt_hdl,
"Error collecting sas_address for %s: %d",
expander->slt_label, err);
free_expander(slmp, expander);
return (TOPO_WALK_NEXT);
}
if (strlen(sas_address) != 16) {
fmd_hdl_debug(slmp->slt_hdl,
"sas-address length is not 16: (%s)", sas_address);
free_expander(slmp, expander);
topo_hdl_strfree(thp, sas_address);
return (TOPO_WALK_NEXT);
}
(void) snprintf(expander->slt_key, MAXNAMELEN, "%s", sas_address);
topo_hdl_strfree(thp, sas_address);
/* Obtain the fmri for this node and save a reference to it. */
if (topo_node_resource(node, &fmri, &err) != 0) {
fmd_hdl_debug(slmp->slt_hdl, "failed to get fmri for %s: %s",
expander->slt_label, topo_strerror(err));
free_expander(slmp, expander);
return (TOPO_WALK_NEXT);
} else {
expander->fmri = fmri;
}
if ((err = get_log(slmp, expander, &lib_param)) != 0) {
/*
* NULL_LOG_DATA means that no data was returned from the
* library. (i.e. There were no log entries.) Just free memory
* and return.
*/
if (err != NULL_LOG_DATA) {
fmd_hdl_debug(slmp->slt_hdl,
"Error retrieving logs from %s: %d",
expander->slt_label, err);
}
free_expander(slmp, expander);
return (TOPO_WALK_NEXT);
}
if ((err = process_log(slmp, expander, &lib_param)) != 0) {
fmd_hdl_debug(slmp->slt_hdl,
"Error processing logs from %s: %d",
expander->slt_label, err);
}
/* Free the expander structure before exiting. */
free_expander(slmp, expander);
return (TOPO_WALK_NEXT);
}
/*
* Called by the FMD after the specified timeout has expired.
* This initiates the processing of the SES device logs.
* slt_process_ses_log() performs the actual log retrieval and analysis.
*
* The last action is to reset the timer so that this method is called again.
*/
/*ARGSUSED*/
static void
slt_timeout(fmd_hdl_t *hdl, id_t id, void *data)
{
topo_hdl_t *thp;
topo_walk_t *twp;
int err;
/* Retrieve the SES log monitor structure. */
ses_log_monitor_t *slmp = fmd_hdl_getspecific(hdl);
if (slmp == NULL) {
fmd_hdl_abort(hdl, "Unable to retrieve log monitor structure.");
return;
}
slmp->slt_hdl = hdl;
thp = fmd_hdl_topo_hold(hdl, TOPO_VERSION);
/*
* This initializes a topology walk structure for stepping through
* the snapshot associated with thp. Note that a callback function
* is supplied (slt_process_ses_log in this case).
*/
if ((twp = topo_walk_init(thp, FM_FMRI_SCHEME_HC, slt_process_ses_log,
slmp, &err)) == NULL) {
fmd_hdl_topo_rele(hdl, thp);
fmd_hdl_abort(hdl, "failed to get topology: %s\n",
topo_strerror(err));
return;
}
/*
* This function walks through the snapshot and invokes the callback
* function supplied when it was set up above.
*/
if (topo_walk_step(twp, TOPO_WALK_CHILD) == TOPO_WALK_ERR) {
topo_walk_fini(twp);
fmd_hdl_topo_rele(hdl, thp);
fmd_hdl_abort(hdl, "failed to walk topology\n");
return;
}
/* This releases the walk structure. */
topo_walk_fini(twp);
fmd_hdl_topo_rele(hdl, thp);
/* Reset the timer for the next iteration. */
slmp->slt_timer = fmd_timer_install(hdl, NULL, NULL,
slmp->slt_interval);
}
/*
* Entry points for the FMD to access this transport.
*/
static const fmd_hdl_ops_t fmd_ops = {
NULL, /* fmdo_recv */
slt_timeout, /* fmdo_timeout */
NULL, /* fmdo_close */
NULL, /* fmdo_stats */
NULL, /* fmdo_gc */
NULL, /* fmdo_send */
NULL, /* fmdo_topo_change */
};
static const fmd_hdl_info_t fmd_info = {
"SES Log Transport Agent", "1.0", &fmd_ops, fmd_props
};
/*
* Initialize the transport.
*/
void
_fmd_init(fmd_hdl_t *hdl)
{
ses_log_monitor_t *slmp;
int error;
nvlist_t *expanderList;
if (fmd_hdl_register(hdl, FMD_API_VERSION, &fmd_info) != 0)
return;
(void) fmd_stat_create(hdl, FMD_STAT_NOALLOC,
sizeof (slt_stats) / sizeof (fmd_stat_t),
(fmd_stat_t *)&slt_stats);
slmp = fmd_hdl_zalloc(hdl, sizeof (ses_log_monitor_t), FMD_SLEEP);
fmd_hdl_setspecific(hdl, slmp);
slmp->slt_xprt = fmd_xprt_open(hdl, FMD_XPRT_RDONLY, NULL, NULL);
if (slmp->slt_xprt == NULL) {
fmd_hdl_error(hdl,
"Unable to obtain a reference to the transport");
fmd_hdl_free(hdl, slmp, sizeof (*slmp));
fmd_hdl_unregister(hdl);
return;
}
/*
* interval is validity checked by the framework since it is of type
* FMD_TYPE_TIME.
*/
slmp->slt_interval = fmd_prop_get_int64(hdl, "interval");
/*
* Use default the severity if it is out of range.
* Setting the severity too high is allowed as this has the effect
* of preventing any ereports from being generated.
*/
slmp->slt_severity = fmd_prop_get_int32(hdl, "severity");
if (slmp->slt_severity < SES_LOG_LEVEL_NOTICE) {
slmp->slt_severity = SES_LOG_LEVEL_ERROR;
}
slmp->slt_log_count = fmd_prop_get_int32(hdl, "logcount");
if (slmp->slt_log_count < MIN_LOG_COUNT) {
slmp->slt_log_count = MIN_LOG_COUNT;
}
slmp->slt_max_log_size = fmd_prop_get_int32(hdl, "maxlogsize");
if (slmp->slt_max_log_size < MIN_LOG_SIZE) {
slmp->slt_max_log_size = MIN_LOG_SIZE;
}
/* Invalid paths will be handled by logging and skipping log creation */
slmp->slt_path = fmd_prop_get_string(hdl, "path");
/* Allocate space for the expander id holder */
if ((error = nvlist_alloc(&expanderList, NV_UNIQUE_NAME, 0)) != 0) {
fmd_xprt_close(hdl, slmp->slt_xprt);
fmd_hdl_strfree(hdl, slmp->slt_path);
fmd_hdl_free(hdl, slmp, sizeof (*slmp));
fmd_hdl_error(hdl,
"Error allocating space for the expander list: %d", error);
fmd_hdl_unregister(hdl);
return;
}
slmp->slt_expanders = expanderList;
/*
* Call our initial timer routine, starting the periodic timeout.
*/
slmp->slt_timer = fmd_timer_install(hdl, NULL, NULL, 0);
}
/*
* Shut down the transport. The primary responsibility is to release any
* allocated memory.
*/
void
_fmd_fini(fmd_hdl_t *hdl)
{
ses_log_monitor_t *slmp;
slmp = fmd_hdl_getspecific(hdl);
if (slmp) {
fmd_timer_remove(hdl, slmp->slt_timer);
fmd_xprt_close(hdl, slmp->slt_xprt);
fmd_prop_free_string(hdl, slmp->slt_path);
nvlist_free(slmp->slt_expanders);
fmd_hdl_free(hdl, slmp, sizeof (*slmp));
}
}
|
764477.c | /**
******************************************************************************
* @file stm32f10x_dac.c
* @author MCD Application Team
* @version V3.6.1
* @date 05-March-2012
* @brief This file provides all the DAC firmware functions.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT 2012 STMicroelectronics</center></h2>
*
* Licensed under MCD-ST Liberty SW License Agreement V2, (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.st.com/software_license_agreement_liberty_v2
*
* 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.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f10x_dac.h"
#include "stm32f10x_rcc.h"
/** @addtogroup STM32F10x_StdPeriph_Driver
* @{
*/
/** @defgroup DAC
* @brief DAC driver modules
* @{
*/
/** @defgroup DAC_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @defgroup DAC_Private_Defines
* @{
*/
/* CR register Mask */
#define CR_CLEAR_MASK ((uint32_t)0x00000FFE)
/* DAC Dual Channels SWTRIG masks */
#define DUAL_SWTRIG_SET ((uint32_t)0x00000003)
#define DUAL_SWTRIG_RESET ((uint32_t)0xFFFFFFFC)
/* DHR registers offsets */
#define DHR12R1_OFFSET ((uint32_t)0x00000008)
#define DHR12R2_OFFSET ((uint32_t)0x00000014)
#define DHR12RD_OFFSET ((uint32_t)0x00000020)
/* DOR register offset */
#define DOR_OFFSET ((uint32_t)0x0000002C)
/**
* @}
*/
/** @defgroup DAC_Private_Macros
* @{
*/
/**
* @}
*/
/** @defgroup DAC_Private_Variables
* @{
*/
/**
* @}
*/
/** @defgroup DAC_Private_FunctionPrototypes
* @{
*/
/**
* @}
*/
/** @defgroup DAC_Private_Functions
* @{
*/
/**
* @brief Deinitializes the DAC peripheral registers to their default reset values.
* @param None
* @retval None
*/
void DAC_DeInit(void)
{
/* Enable DAC reset state */
RCC_APB1PeriphResetCmd(RCC_APB1Periph_DAC, ENABLE);
/* Release DAC from reset state */
RCC_APB1PeriphResetCmd(RCC_APB1Periph_DAC, DISABLE);
}
/**
* @brief Initializes the DAC peripheral according to the specified
* parameters in the DAC_InitStruct.
* @param DAC_Channel: the selected DAC channel.
* This parameter can be one of the following values:
* @arg DAC_Channel_1: DAC Channel1 selected
* @arg DAC_Channel_2: DAC Channel2 selected
* @param DAC_InitStruct: pointer to a DAC_InitTypeDef structure that
* contains the configuration information for the specified DAC channel.
* @retval None
*/
void DAC_Init(uint32_t DAC_Channel, DAC_InitTypeDef* DAC_InitStruct)
{
uint32_t tmpreg1 = 0, tmpreg2 = 0;
/* Check the DAC parameters */
assert_param(IS_DAC_TRIGGER(DAC_InitStruct->DAC_Trigger));
assert_param(IS_DAC_GENERATE_WAVE(DAC_InitStruct->DAC_WaveGeneration));
assert_param(IS_DAC_LFSR_UNMASK_TRIANGLE_AMPLITUDE(DAC_InitStruct->DAC_LFSRUnmask_TriangleAmplitude));
assert_param(IS_DAC_OUTPUT_BUFFER_STATE(DAC_InitStruct->DAC_OutputBuffer));
/*---------------------------- DAC CR Configuration --------------------------*/
/* Get the DAC CR value */
tmpreg1 = DAC->CR;
/* Clear BOFFx, TENx, TSELx, WAVEx and MAMPx bits */
tmpreg1 &= ~(CR_CLEAR_MASK << DAC_Channel);
/* Configure for the selected DAC channel: buffer output, trigger, wave generation,
mask/amplitude for wave generation */
/* Set TSELx and TENx bits according to DAC_Trigger value */
/* Set WAVEx bits according to DAC_WaveGeneration value */
/* Set MAMPx bits according to DAC_LFSRUnmask_TriangleAmplitude value */
/* Set BOFFx bit according to DAC_OutputBuffer value */
tmpreg2 = (DAC_InitStruct->DAC_Trigger | DAC_InitStruct->DAC_WaveGeneration |
DAC_InitStruct->DAC_LFSRUnmask_TriangleAmplitude | DAC_InitStruct->DAC_OutputBuffer);
/* Calculate CR register value depending on DAC_Channel */
tmpreg1 |= tmpreg2 << DAC_Channel;
/* Write to DAC CR */
DAC->CR = tmpreg1;
}
/**
* @brief Fills each DAC_InitStruct member with its default value.
* @param DAC_InitStruct : pointer to a DAC_InitTypeDef structure which will
* be initialized.
* @retval None
*/
void DAC_StructInit(DAC_InitTypeDef* DAC_InitStruct)
{
/*--------------- Reset DAC init structure parameters values -----------------*/
/* Initialize the DAC_Trigger member */
DAC_InitStruct->DAC_Trigger = DAC_Trigger_None;
/* Initialize the DAC_WaveGeneration member */
DAC_InitStruct->DAC_WaveGeneration = DAC_WaveGeneration_None;
/* Initialize the DAC_LFSRUnmask_TriangleAmplitude member */
DAC_InitStruct->DAC_LFSRUnmask_TriangleAmplitude = DAC_LFSRUnmask_Bit0;
/* Initialize the DAC_OutputBuffer member */
DAC_InitStruct->DAC_OutputBuffer = DAC_OutputBuffer_Enable;
}
/**
* @brief Enables or disables the specified DAC channel.
* @param DAC_Channel: the selected DAC channel.
* This parameter can be one of the following values:
* @arg DAC_Channel_1: DAC Channel1 selected
* @arg DAC_Channel_2: DAC Channel2 selected
* @param NewState: new state of the DAC channel.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void DAC_Cmd(uint32_t DAC_Channel, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_DAC_CHANNEL(DAC_Channel));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Enable the selected DAC channel */
DAC->CR |= (DAC_CR_EN1 << DAC_Channel);
}
else
{
/* Disable the selected DAC channel */
DAC->CR &= ~(DAC_CR_EN1 << DAC_Channel);
}
}
#if defined (STM32F10X_LD_VL) || defined (STM32F10X_MD_VL) || defined (STM32F10X_HD_VL)
/**
* @brief Enables or disables the specified DAC interrupts.
* @param DAC_Channel: the selected DAC channel.
* This parameter can be one of the following values:
* @arg DAC_Channel_1: DAC Channel1 selected
* @arg DAC_Channel_2: DAC Channel2 selected
* @param DAC_IT: specifies the DAC interrupt sources to be enabled or disabled.
* This parameter can be the following values:
* @arg DAC_IT_DMAUDR: DMA underrun interrupt mask
* @param NewState: new state of the specified DAC interrupts.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void DAC_ITConfig(uint32_t DAC_Channel, uint32_t DAC_IT, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_DAC_CHANNEL(DAC_Channel));
assert_param(IS_FUNCTIONAL_STATE(NewState));
assert_param(IS_DAC_IT(DAC_IT));
if (NewState != DISABLE)
{
/* Enable the selected DAC interrupts */
DAC->CR |= (DAC_IT << DAC_Channel);
}
else
{
/* Disable the selected DAC interrupts */
DAC->CR &= (~(uint32_t)(DAC_IT << DAC_Channel));
}
}
#endif
/**
* @brief Enables or disables the specified DAC channel DMA request.
* @param DAC_Channel: the selected DAC channel.
* This parameter can be one of the following values:
* @arg DAC_Channel_1: DAC Channel1 selected
* @arg DAC_Channel_2: DAC Channel2 selected
* @param NewState: new state of the selected DAC channel DMA request.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void DAC_DMACmd(uint32_t DAC_Channel, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_DAC_CHANNEL(DAC_Channel));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Enable the selected DAC channel DMA request */
DAC->CR |= (DAC_CR_DMAEN1 << DAC_Channel);
}
else
{
/* Disable the selected DAC channel DMA request */
DAC->CR &= ~(DAC_CR_DMAEN1 << DAC_Channel);
}
}
/**
* @brief Enables or disables the selected DAC channel software trigger.
* @param DAC_Channel: the selected DAC channel.
* This parameter can be one of the following values:
* @arg DAC_Channel_1: DAC Channel1 selected
* @arg DAC_Channel_2: DAC Channel2 selected
* @param NewState: new state of the selected DAC channel software trigger.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void DAC_SoftwareTriggerCmd(uint32_t DAC_Channel, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_DAC_CHANNEL(DAC_Channel));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Enable software trigger for the selected DAC channel */
DAC->SWTRIGR |= (uint32_t)DAC_SWTRIGR_SWTRIG1 << (DAC_Channel >> 4);
}
else
{
/* Disable software trigger for the selected DAC channel */
DAC->SWTRIGR &= ~((uint32_t)DAC_SWTRIGR_SWTRIG1 << (DAC_Channel >> 4));
}
}
/**
* @brief Enables or disables simultaneously the two DAC channels software
* triggers.
* @param NewState: new state of the DAC channels software triggers.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void DAC_DualSoftwareTriggerCmd(FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Enable software trigger for both DAC channels */
DAC->SWTRIGR |= DUAL_SWTRIG_SET ;
}
else
{
/* Disable software trigger for both DAC channels */
DAC->SWTRIGR &= DUAL_SWTRIG_RESET;
}
}
/**
* @brief Enables or disables the selected DAC channel wave generation.
* @param DAC_Channel: the selected DAC channel.
* This parameter can be one of the following values:
* @arg DAC_Channel_1: DAC Channel1 selected
* @arg DAC_Channel_2: DAC Channel2 selected
* @param DAC_Wave: Specifies the wave type to enable or disable.
* This parameter can be one of the following values:
* @arg DAC_Wave_Noise: noise wave generation
* @arg DAC_Wave_Triangle: triangle wave generation
* @param NewState: new state of the selected DAC channel wave generation.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void DAC_WaveGenerationCmd(uint32_t DAC_Channel, uint32_t DAC_Wave, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_DAC_CHANNEL(DAC_Channel));
assert_param(IS_DAC_WAVE(DAC_Wave));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Enable the selected wave generation for the selected DAC channel */
DAC->CR |= DAC_Wave << DAC_Channel;
}
else
{
/* Disable the selected wave generation for the selected DAC channel */
DAC->CR &= ~(DAC_Wave << DAC_Channel);
}
}
/**
* @brief Set the specified data holding register value for DAC channel1.
* @param DAC_Align: Specifies the data alignment for DAC channel1.
* This parameter can be one of the following values:
* @arg DAC_Align_8b_R: 8bit right data alignment selected
* @arg DAC_Align_12b_L: 12bit left data alignment selected
* @arg DAC_Align_12b_R: 12bit right data alignment selected
* @param Data : Data to be loaded in the selected data holding register.
* @retval None
*/
void DAC_SetChannel1Data(uint32_t DAC_Align, uint16_t Data)
{
__IO uint32_t tmp = 0;
/* Check the parameters */
assert_param(IS_DAC_ALIGN(DAC_Align));
assert_param(IS_DAC_DATA(Data));
tmp = (uint32_t)DAC_BASE;
tmp += DHR12R1_OFFSET + DAC_Align;
/* Set the DAC channel1 selected data holding register */
*(__IO uint32_t *) tmp = Data;
}
/**
* @brief Set the specified data holding register value for DAC channel2.
* @param DAC_Align: Specifies the data alignment for DAC channel2.
* This parameter can be one of the following values:
* @arg DAC_Align_8b_R: 8bit right data alignment selected
* @arg DAC_Align_12b_L: 12bit left data alignment selected
* @arg DAC_Align_12b_R: 12bit right data alignment selected
* @param Data : Data to be loaded in the selected data holding register.
* @retval None
*/
void DAC_SetChannel2Data(uint32_t DAC_Align, uint16_t Data)
{
__IO uint32_t tmp = 0;
/* Check the parameters */
assert_param(IS_DAC_ALIGN(DAC_Align));
assert_param(IS_DAC_DATA(Data));
tmp = (uint32_t)DAC_BASE;
tmp += DHR12R2_OFFSET + DAC_Align;
/* Set the DAC channel2 selected data holding register */
*(__IO uint32_t *)tmp = Data;
}
/**
* @brief Set the specified data holding register value for dual channel
* DAC.
* @param DAC_Align: Specifies the data alignment for dual channel DAC.
* This parameter can be one of the following values:
* @arg DAC_Align_8b_R: 8bit right data alignment selected
* @arg DAC_Align_12b_L: 12bit left data alignment selected
* @arg DAC_Align_12b_R: 12bit right data alignment selected
* @param Data2: Data for DAC Channel2 to be loaded in the selected data
* holding register.
* @param Data1: Data for DAC Channel1 to be loaded in the selected data
* holding register.
* @retval None
*/
void DAC_SetDualChannelData(uint32_t DAC_Align, uint16_t Data2, uint16_t Data1)
{
uint32_t data = 0, tmp = 0;
/* Check the parameters */
assert_param(IS_DAC_ALIGN(DAC_Align));
assert_param(IS_DAC_DATA(Data1));
assert_param(IS_DAC_DATA(Data2));
/* Calculate and set dual DAC data holding register value */
if (DAC_Align == DAC_Align_8b_R)
{
data = ((uint32_t)Data2 << 8) | Data1;
}
else
{
data = ((uint32_t)Data2 << 16) | Data1;
}
tmp = (uint32_t)DAC_BASE;
tmp += DHR12RD_OFFSET + DAC_Align;
/* Set the dual DAC selected data holding register */
*(__IO uint32_t *)tmp = data;
}
/**
* @brief Returns the last data output value of the selected DAC channel.
* @param DAC_Channel: the selected DAC channel.
* This parameter can be one of the following values:
* @arg DAC_Channel_1: DAC Channel1 selected
* @arg DAC_Channel_2: DAC Channel2 selected
* @retval The selected DAC channel data output value.
*/
uint16_t DAC_GetDataOutputValue(uint32_t DAC_Channel)
{
__IO uint32_t tmp = 0;
/* Check the parameters */
assert_param(IS_DAC_CHANNEL(DAC_Channel));
tmp = (uint32_t) DAC_BASE ;
tmp += DOR_OFFSET + ((uint32_t)DAC_Channel >> 2);
/* Returns the DAC channel data output register value */
return (uint16_t) (*(__IO uint32_t*) tmp);
}
#if defined (STM32F10X_LD_VL) || defined (STM32F10X_MD_VL) || defined (STM32F10X_HD_VL)
/**
* @brief Checks whether the specified DAC flag is set or not.
* @param DAC_Channel: thee selected DAC channel.
* This parameter can be one of the following values:
* @arg DAC_Channel_1: DAC Channel1 selected
* @arg DAC_Channel_2: DAC Channel2 selected
* @param DAC_FLAG: specifies the flag to check.
* This parameter can be only of the following value:
* @arg DAC_FLAG_DMAUDR: DMA underrun flag
* @retval The new state of DAC_FLAG (SET or RESET).
*/
FlagStatus DAC_GetFlagStatus(uint32_t DAC_Channel, uint32_t DAC_FLAG)
{
FlagStatus bitstatus = RESET;
/* Check the parameters */
assert_param(IS_DAC_CHANNEL(DAC_Channel));
assert_param(IS_DAC_FLAG(DAC_FLAG));
/* Check the status of the specified DAC flag */
if ((DAC->SR & (DAC_FLAG << DAC_Channel)) != (uint8_t)RESET)
{
/* DAC_FLAG is set */
bitstatus = SET;
}
else
{
/* DAC_FLAG is reset */
bitstatus = RESET;
}
/* Return the DAC_FLAG status */
return bitstatus;
}
/**
* @brief Clears the DAC channelx's pending flags.
* @param DAC_Channel: the selected DAC channel.
* This parameter can be one of the following values:
* @arg DAC_Channel_1: DAC Channel1 selected
* @arg DAC_Channel_2: DAC Channel2 selected
* @param DAC_FLAG: specifies the flag to clear.
* This parameter can be of the following value:
* @arg DAC_FLAG_DMAUDR: DMA underrun flag
* @retval None
*/
void DAC_ClearFlag(uint32_t DAC_Channel, uint32_t DAC_FLAG)
{
/* Check the parameters */
assert_param(IS_DAC_CHANNEL(DAC_Channel));
assert_param(IS_DAC_FLAG(DAC_FLAG));
/* Clear the selected DAC flags */
DAC->SR = (DAC_FLAG << DAC_Channel);
}
/**
* @brief Checks whether the specified DAC interrupt has occurred or not.
* @param DAC_Channel: the selected DAC channel.
* This parameter can be one of the following values:
* @arg DAC_Channel_1: DAC Channel1 selected
* @arg DAC_Channel_2: DAC Channel2 selected
* @param DAC_IT: specifies the DAC interrupt source to check.
* This parameter can be the following values:
* @arg DAC_IT_DMAUDR: DMA underrun interrupt mask
* @retval The new state of DAC_IT (SET or RESET).
*/
ITStatus DAC_GetITStatus(uint32_t DAC_Channel, uint32_t DAC_IT)
{
ITStatus bitstatus = RESET;
uint32_t enablestatus = 0;
/* Check the parameters */
assert_param(IS_DAC_CHANNEL(DAC_Channel));
assert_param(IS_DAC_IT(DAC_IT));
/* Get the DAC_IT enable bit status */
enablestatus = (DAC->CR & (DAC_IT << DAC_Channel)) ;
/* Check the status of the specified DAC interrupt */
if (((DAC->SR & (DAC_IT << DAC_Channel)) != (uint32_t)RESET) && enablestatus)
{
/* DAC_IT is set */
bitstatus = SET;
}
else
{
/* DAC_IT is reset */
bitstatus = RESET;
}
/* Return the DAC_IT status */
return bitstatus;
}
/**
* @brief Clears the DAC channelx's interrupt pending bits.
* @param DAC_Channel: the selected DAC channel.
* This parameter can be one of the following values:
* @arg DAC_Channel_1: DAC Channel1 selected
* @arg DAC_Channel_2: DAC Channel2 selected
* @param DAC_IT: specifies the DAC interrupt pending bit to clear.
* This parameter can be the following values:
* @arg DAC_IT_DMAUDR: DMA underrun interrupt mask
* @retval None
*/
void DAC_ClearITPendingBit(uint32_t DAC_Channel, uint32_t DAC_IT)
{
/* Check the parameters */
assert_param(IS_DAC_CHANNEL(DAC_Channel));
assert_param(IS_DAC_IT(DAC_IT));
/* Clear the selected DAC interrupt pending bits */
DAC->SR = (DAC_IT << DAC_Channel);
}
#endif
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
743331.c | #include <stdio.h>
#include <unistd.h>
#include "neoviki_semaphore_lock.h"
#define SEMAPHORE_NAME "/tmp/test.txt"
int main()
{
int i;
neoviki_sem_t *sem = SEM_CREATE(SEMAPHORE_NAME);
SEM_LOCK(sem);
printf("writer\n");
return 0;
}
|
162309.c | /*
* Copyright (c) 2017, NVIDIA CORPORATION. All rights reserved.
*
* 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.
*/
#include <float.h>
#include <stdio.h>
#include <string.h>
#include "libavutil/avstring.h"
#include "libavutil/common.h"
#include "libavutil/hwcontext.h"
#include "libavutil/hwcontext_cuda_internal.h"
#include "libavutil/cuda_check.h"
#include "libavutil/internal.h"
#include "libavutil/opt.h"
#include "libavutil/pixdesc.h"
#include "avfilter.h"
#include "formats.h"
#include "internal.h"
#include "scale_eval.h"
#include "video.h"
#include "cuda/load_helper.h"
#include "vf_scale_cuda.h"
static const enum AVPixelFormat supported_formats[] = {
AV_PIX_FMT_YUV420P,
AV_PIX_FMT_NV12,
AV_PIX_FMT_YUV444P,
AV_PIX_FMT_P010,
AV_PIX_FMT_P016,
AV_PIX_FMT_YUV444P16,
AV_PIX_FMT_0RGB32,
AV_PIX_FMT_0BGR32,
};
#define DIV_UP(a, b) ( ((a) + (b) - 1) / (b) )
#define BLOCKX 32
#define BLOCKY 16
#define CHECK_CU(x) FF_CUDA_CHECK_DL(ctx, s->hwctx->internal->cuda_dl, x)
enum {
INTERP_ALGO_DEFAULT,
INTERP_ALGO_NEAREST,
INTERP_ALGO_BILINEAR,
INTERP_ALGO_BICUBIC,
INTERP_ALGO_LANCZOS,
INTERP_ALGO_COUNT
};
typedef struct CUDAScaleContext {
const AVClass *class;
AVCUDADeviceContext *hwctx;
enum AVPixelFormat in_fmt, out_fmt;
const AVPixFmtDescriptor *in_desc, *out_desc;
int in_planes, out_planes;
int in_plane_depths[4];
int in_plane_channels[4];
AVBufferRef *frames_ctx;
AVFrame *frame;
AVFrame *tmp_frame;
int passthrough;
/**
* Output sw format. AV_PIX_FMT_NONE for no conversion.
*/
enum AVPixelFormat format;
char *w_expr; ///< width expression string
char *h_expr; ///< height expression string
int force_original_aspect_ratio;
int force_divisible_by;
CUcontext cu_ctx;
CUmodule cu_module;
CUfunction cu_func;
CUfunction cu_func_uv;
CUstream cu_stream;
int interp_algo;
int interp_use_linear;
int interp_as_integer;
float param;
} CUDAScaleContext;
static av_cold int cudascale_init(AVFilterContext *ctx)
{
CUDAScaleContext *s = ctx->priv;
s->frame = av_frame_alloc();
if (!s->frame)
return AVERROR(ENOMEM);
s->tmp_frame = av_frame_alloc();
if (!s->tmp_frame)
return AVERROR(ENOMEM);
return 0;
}
static av_cold void cudascale_uninit(AVFilterContext *ctx)
{
CUDAScaleContext *s = ctx->priv;
if (s->hwctx && s->cu_module) {
CudaFunctions *cu = s->hwctx->internal->cuda_dl;
CUcontext dummy;
CHECK_CU(cu->cuCtxPushCurrent(s->hwctx->cuda_ctx));
CHECK_CU(cu->cuModuleUnload(s->cu_module));
s->cu_module = NULL;
CHECK_CU(cu->cuCtxPopCurrent(&dummy));
}
av_frame_free(&s->frame);
av_buffer_unref(&s->frames_ctx);
av_frame_free(&s->tmp_frame);
}
static int cudascale_query_formats(AVFilterContext *ctx)
{
static const enum AVPixelFormat pixel_formats[] = {
AV_PIX_FMT_CUDA, AV_PIX_FMT_NONE,
};
return ff_set_common_formats_from_list(ctx, pixel_formats);
}
static av_cold int init_hwframe_ctx(CUDAScaleContext *s, AVBufferRef *device_ctx, int width, int height)
{
AVBufferRef *out_ref = NULL;
AVHWFramesContext *out_ctx;
int ret;
out_ref = av_hwframe_ctx_alloc(device_ctx);
if (!out_ref)
return AVERROR(ENOMEM);
out_ctx = (AVHWFramesContext*)out_ref->data;
out_ctx->format = AV_PIX_FMT_CUDA;
out_ctx->sw_format = s->out_fmt;
out_ctx->width = FFALIGN(width, 32);
out_ctx->height = FFALIGN(height, 32);
ret = av_hwframe_ctx_init(out_ref);
if (ret < 0)
goto fail;
av_frame_unref(s->frame);
ret = av_hwframe_get_buffer(out_ref, s->frame, 0);
if (ret < 0)
goto fail;
s->frame->width = width;
s->frame->height = height;
av_buffer_unref(&s->frames_ctx);
s->frames_ctx = out_ref;
return 0;
fail:
av_buffer_unref(&out_ref);
return ret;
}
static int format_is_supported(enum AVPixelFormat fmt)
{
int i;
for (i = 0; i < FF_ARRAY_ELEMS(supported_formats); i++)
if (supported_formats[i] == fmt)
return 1;
return 0;
}
static av_cold void set_format_info(AVFilterContext *ctx, enum AVPixelFormat in_format, enum AVPixelFormat out_format)
{
CUDAScaleContext *s = ctx->priv;
int i, p, d;
s->in_fmt = in_format;
s->out_fmt = out_format;
s->in_desc = av_pix_fmt_desc_get(s->in_fmt);
s->out_desc = av_pix_fmt_desc_get(s->out_fmt);
s->in_planes = av_pix_fmt_count_planes(s->in_fmt);
s->out_planes = av_pix_fmt_count_planes(s->out_fmt);
// find maximum step of each component of each plane
// For our subset of formats, this should accurately tell us how many channels CUDA needs
// i.e. 1 for Y plane, 2 for UV plane of NV12, 4 for single plane of RGB0 formats
for (i = 0; i < s->in_desc->nb_components; i++) {
d = (s->in_desc->comp[i].depth + 7) / 8;
p = s->in_desc->comp[i].plane;
s->in_plane_channels[p] = FFMAX(s->in_plane_channels[p], s->in_desc->comp[i].step / d);
s->in_plane_depths[p] = s->in_desc->comp[i].depth;
}
}
static av_cold int init_processing_chain(AVFilterContext *ctx, int in_width, int in_height,
int out_width, int out_height)
{
CUDAScaleContext *s = ctx->priv;
AVHWFramesContext *in_frames_ctx;
enum AVPixelFormat in_format;
enum AVPixelFormat out_format;
int ret;
/* check that we have a hw context */
if (!ctx->inputs[0]->hw_frames_ctx) {
av_log(ctx, AV_LOG_ERROR, "No hw context provided on input\n");
return AVERROR(EINVAL);
}
in_frames_ctx = (AVHWFramesContext*)ctx->inputs[0]->hw_frames_ctx->data;
in_format = in_frames_ctx->sw_format;
out_format = (s->format == AV_PIX_FMT_NONE) ? in_format : s->format;
if (!format_is_supported(in_format)) {
av_log(ctx, AV_LOG_ERROR, "Unsupported input format: %s\n",
av_get_pix_fmt_name(in_format));
return AVERROR(ENOSYS);
}
if (!format_is_supported(out_format)) {
av_log(ctx, AV_LOG_ERROR, "Unsupported output format: %s\n",
av_get_pix_fmt_name(out_format));
return AVERROR(ENOSYS);
}
set_format_info(ctx, in_format, out_format);
if (s->passthrough && in_width == out_width && in_height == out_height && in_format == out_format) {
s->frames_ctx = av_buffer_ref(ctx->inputs[0]->hw_frames_ctx);
if (!s->frames_ctx)
return AVERROR(ENOMEM);
} else {
s->passthrough = 0;
ret = init_hwframe_ctx(s, in_frames_ctx->device_ref, out_width, out_height);
if (ret < 0)
return ret;
if (in_width == out_width && in_height == out_height &&
in_format == out_format && s->interp_algo == INTERP_ALGO_DEFAULT)
s->interp_algo = INTERP_ALGO_NEAREST;
}
ctx->outputs[0]->hw_frames_ctx = av_buffer_ref(s->frames_ctx);
if (!ctx->outputs[0]->hw_frames_ctx)
return AVERROR(ENOMEM);
return 0;
}
static av_cold int cudascale_load_functions(AVFilterContext *ctx)
{
CUDAScaleContext *s = ctx->priv;
CUcontext dummy, cuda_ctx = s->hwctx->cuda_ctx;
CudaFunctions *cu = s->hwctx->internal->cuda_dl;
char buf[128];
int ret;
const char *in_fmt_name = av_get_pix_fmt_name(s->in_fmt);
const char *out_fmt_name = av_get_pix_fmt_name(s->out_fmt);
const char *function_infix = "";
extern const unsigned char ff_vf_scale_cuda_ptx_data[];
extern const unsigned int ff_vf_scale_cuda_ptx_len;
switch(s->interp_algo) {
case INTERP_ALGO_NEAREST:
function_infix = "Nearest";
s->interp_use_linear = 0;
s->interp_as_integer = 1;
break;
case INTERP_ALGO_BILINEAR:
function_infix = "Bilinear";
s->interp_use_linear = 1;
s->interp_as_integer = 1;
break;
case INTERP_ALGO_DEFAULT:
case INTERP_ALGO_BICUBIC:
function_infix = "Bicubic";
s->interp_use_linear = 0;
s->interp_as_integer = 0;
break;
case INTERP_ALGO_LANCZOS:
function_infix = "Lanczos";
s->interp_use_linear = 0;
s->interp_as_integer = 0;
break;
default:
av_log(ctx, AV_LOG_ERROR, "Unknown interpolation algorithm\n");
return AVERROR_BUG;
}
ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_ctx));
if (ret < 0)
return ret;
ret = ff_cuda_load_module(ctx, s->hwctx, &s->cu_module,
ff_vf_scale_cuda_ptx_data, ff_vf_scale_cuda_ptx_len);
if (ret < 0)
goto fail;
snprintf(buf, sizeof(buf), "Subsample_%s_%s_%s", function_infix, in_fmt_name, out_fmt_name);
ret = CHECK_CU(cu->cuModuleGetFunction(&s->cu_func, s->cu_module, buf));
if (ret < 0) {
av_log(ctx, AV_LOG_FATAL, "Unsupported conversion: %s -> %s\n", in_fmt_name, out_fmt_name);
ret = AVERROR(ENOSYS);
goto fail;
}
snprintf(buf, sizeof(buf), "Subsample_%s_%s_%s_uv", function_infix, in_fmt_name, out_fmt_name);
ret = CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_uv, s->cu_module, buf));
if (ret < 0)
goto fail;
fail:
CHECK_CU(cu->cuCtxPopCurrent(&dummy));
return ret;
}
static av_cold int cudascale_config_props(AVFilterLink *outlink)
{
AVFilterContext *ctx = outlink->src;
AVFilterLink *inlink = outlink->src->inputs[0];
CUDAScaleContext *s = ctx->priv;
AVHWFramesContext *frames_ctx = (AVHWFramesContext*)inlink->hw_frames_ctx->data;
AVCUDADeviceContext *device_hwctx = frames_ctx->device_ctx->hwctx;
int w, h;
int ret;
s->hwctx = device_hwctx;
s->cu_stream = s->hwctx->stream;
if ((ret = ff_scale_eval_dimensions(s,
s->w_expr, s->h_expr,
inlink, outlink,
&w, &h)) < 0)
goto fail;
ff_scale_adjust_dimensions(inlink, &w, &h,
s->force_original_aspect_ratio, s->force_divisible_by);
if (((int64_t)h * inlink->w) > INT_MAX ||
((int64_t)w * inlink->h) > INT_MAX)
av_log(ctx, AV_LOG_ERROR, "Rescaled value for width or height is too big.\n");
outlink->w = w;
outlink->h = h;
ret = init_processing_chain(ctx, inlink->w, inlink->h, w, h);
if (ret < 0)
return ret;
if (inlink->sample_aspect_ratio.num) {
outlink->sample_aspect_ratio = av_mul_q((AVRational){outlink->h*inlink->w,
outlink->w*inlink->h},
inlink->sample_aspect_ratio);
} else {
outlink->sample_aspect_ratio = inlink->sample_aspect_ratio;
}
av_log(ctx, AV_LOG_VERBOSE, "w:%d h:%d fmt:%s -> w:%d h:%d fmt:%s%s\n",
inlink->w, inlink->h, av_get_pix_fmt_name(s->in_fmt),
outlink->w, outlink->h, av_get_pix_fmt_name(s->out_fmt),
s->passthrough ? " (passthrough)" : "");
ret = cudascale_load_functions(ctx);
if (ret < 0)
return ret;
return 0;
fail:
return ret;
}
static int call_resize_kernel(AVFilterContext *ctx, CUfunction func,
CUtexObject src_tex[4], int src_width, int src_height,
AVFrame *out_frame, int dst_width, int dst_height, int dst_pitch)
{
CUDAScaleContext *s = ctx->priv;
CudaFunctions *cu = s->hwctx->internal->cuda_dl;
CUdeviceptr dst_devptr[4] = {
(CUdeviceptr)out_frame->data[0], (CUdeviceptr)out_frame->data[1],
(CUdeviceptr)out_frame->data[2], (CUdeviceptr)out_frame->data[3]
};
void *args_uchar[] = {
&src_tex[0], &src_tex[1], &src_tex[2], &src_tex[3],
&dst_devptr[0], &dst_devptr[1], &dst_devptr[2], &dst_devptr[3],
&dst_width, &dst_height, &dst_pitch,
&src_width, &src_height, &s->param
};
return CHECK_CU(cu->cuLaunchKernel(func,
DIV_UP(dst_width, BLOCKX), DIV_UP(dst_height, BLOCKY), 1,
BLOCKX, BLOCKY, 1, 0, s->cu_stream, args_uchar, NULL));
}
static int scalecuda_resize(AVFilterContext *ctx,
AVFrame *out, AVFrame *in)
{
CUDAScaleContext *s = ctx->priv;
CudaFunctions *cu = s->hwctx->internal->cuda_dl;
CUcontext dummy, cuda_ctx = s->hwctx->cuda_ctx;
int i, ret;
CUtexObject tex[4] = { 0, 0, 0, 0 };
ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_ctx));
if (ret < 0)
return ret;
for (i = 0; i < s->in_planes; i++) {
CUDA_TEXTURE_DESC tex_desc = {
.filterMode = s->interp_use_linear ?
CU_TR_FILTER_MODE_LINEAR :
CU_TR_FILTER_MODE_POINT,
.flags = s->interp_as_integer ? CU_TRSF_READ_AS_INTEGER : 0,
};
CUDA_RESOURCE_DESC res_desc = {
.resType = CU_RESOURCE_TYPE_PITCH2D,
.res.pitch2D.format = s->in_plane_depths[i] <= 8 ?
CU_AD_FORMAT_UNSIGNED_INT8 :
CU_AD_FORMAT_UNSIGNED_INT16,
.res.pitch2D.numChannels = s->in_plane_channels[i],
.res.pitch2D.pitchInBytes = in->linesize[i],
.res.pitch2D.devPtr = (CUdeviceptr)in->data[i],
};
if (i == 1 || i == 2) {
res_desc.res.pitch2D.width = AV_CEIL_RSHIFT(in->width, s->in_desc->log2_chroma_w);
res_desc.res.pitch2D.height = AV_CEIL_RSHIFT(in->height, s->in_desc->log2_chroma_h);
} else {
res_desc.res.pitch2D.width = in->width;
res_desc.res.pitch2D.height = in->height;
}
ret = CHECK_CU(cu->cuTexObjectCreate(&tex[i], &res_desc, &tex_desc, NULL));
if (ret < 0)
goto exit;
}
// scale primary plane(s). Usually Y (and A), or single plane of RGB frames.
ret = call_resize_kernel(ctx, s->cu_func,
tex, in->width, in->height,
out, out->width, out->height, out->linesize[0]);
if (ret < 0)
goto exit;
if (s->out_planes > 1) {
// scale UV plane. Scale function sets both U and V plane, or singular interleaved plane.
ret = call_resize_kernel(ctx, s->cu_func_uv, tex,
AV_CEIL_RSHIFT(in->width, s->in_desc->log2_chroma_w),
AV_CEIL_RSHIFT(in->height, s->in_desc->log2_chroma_h),
out,
AV_CEIL_RSHIFT(out->width, s->out_desc->log2_chroma_w),
AV_CEIL_RSHIFT(out->height, s->out_desc->log2_chroma_h),
out->linesize[1]);
if (ret < 0)
goto exit;
}
exit:
for (i = 0; i < s->in_planes; i++)
if (tex[i])
CHECK_CU(cu->cuTexObjectDestroy(tex[i]));
CHECK_CU(cu->cuCtxPopCurrent(&dummy));
return ret;
}
static int cudascale_scale(AVFilterContext *ctx, AVFrame *out, AVFrame *in)
{
CUDAScaleContext *s = ctx->priv;
AVFilterLink *outlink = ctx->outputs[0];
AVFrame *src = in;
int ret;
ret = scalecuda_resize(ctx, s->frame, src);
if (ret < 0)
return ret;
src = s->frame;
ret = av_hwframe_get_buffer(src->hw_frames_ctx, s->tmp_frame, 0);
if (ret < 0)
return ret;
av_frame_move_ref(out, s->frame);
av_frame_move_ref(s->frame, s->tmp_frame);
s->frame->width = outlink->w;
s->frame->height = outlink->h;
ret = av_frame_copy_props(out, in);
if (ret < 0)
return ret;
return 0;
}
static int cudascale_filter_frame(AVFilterLink *link, AVFrame *in)
{
AVFilterContext *ctx = link->dst;
CUDAScaleContext *s = ctx->priv;
AVFilterLink *outlink = ctx->outputs[0];
CudaFunctions *cu = s->hwctx->internal->cuda_dl;
AVFrame *out = NULL;
CUcontext dummy;
int ret = 0;
if (s->passthrough)
return ff_filter_frame(outlink, in);
out = av_frame_alloc();
if (!out) {
ret = AVERROR(ENOMEM);
goto fail;
}
ret = CHECK_CU(cu->cuCtxPushCurrent(s->hwctx->cuda_ctx));
if (ret < 0)
goto fail;
ret = cudascale_scale(ctx, out, in);
CHECK_CU(cu->cuCtxPopCurrent(&dummy));
if (ret < 0)
goto fail;
av_reduce(&out->sample_aspect_ratio.num, &out->sample_aspect_ratio.den,
(int64_t)in->sample_aspect_ratio.num * outlink->h * link->w,
(int64_t)in->sample_aspect_ratio.den * outlink->w * link->h,
INT_MAX);
av_frame_free(&in);
return ff_filter_frame(outlink, out);
fail:
av_frame_free(&in);
av_frame_free(&out);
return ret;
}
static AVFrame *cudascale_get_video_buffer(AVFilterLink *inlink, int w, int h)
{
CUDAScaleContext *s = inlink->dst->priv;
return s->passthrough ?
ff_null_get_video_buffer (inlink, w, h) :
ff_default_get_video_buffer(inlink, w, h);
}
#define OFFSET(x) offsetof(CUDAScaleContext, x)
#define FLAGS (AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM)
static const AVOption options[] = {
{ "w", "Output video width", OFFSET(w_expr), AV_OPT_TYPE_STRING, { .str = "iw" }, .flags = FLAGS },
{ "h", "Output video height", OFFSET(h_expr), AV_OPT_TYPE_STRING, { .str = "ih" }, .flags = FLAGS },
{ "interp_algo", "Interpolation algorithm used for resizing", OFFSET(interp_algo), AV_OPT_TYPE_INT, { .i64 = INTERP_ALGO_DEFAULT }, 0, INTERP_ALGO_COUNT - 1, FLAGS, "interp_algo" },
{ "nearest", "nearest neighbour", 0, AV_OPT_TYPE_CONST, { .i64 = INTERP_ALGO_NEAREST }, 0, 0, FLAGS, "interp_algo" },
{ "bilinear", "bilinear", 0, AV_OPT_TYPE_CONST, { .i64 = INTERP_ALGO_BILINEAR }, 0, 0, FLAGS, "interp_algo" },
{ "bicubic", "bicubic", 0, AV_OPT_TYPE_CONST, { .i64 = INTERP_ALGO_BICUBIC }, 0, 0, FLAGS, "interp_algo" },
{ "lanczos", "lanczos", 0, AV_OPT_TYPE_CONST, { .i64 = INTERP_ALGO_LANCZOS }, 0, 0, FLAGS, "interp_algo" },
{ "format", "Output video pixel format", OFFSET(format), AV_OPT_TYPE_PIXEL_FMT, { .i64 = AV_PIX_FMT_NONE }, INT_MIN, INT_MAX, .flags=FLAGS },
{ "passthrough", "Do not process frames at all if parameters match", OFFSET(passthrough), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, FLAGS },
{ "param", "Algorithm-Specific parameter", OFFSET(param), AV_OPT_TYPE_FLOAT, { .dbl = SCALE_CUDA_PARAM_DEFAULT }, -FLT_MAX, FLT_MAX, FLAGS },
{ "force_original_aspect_ratio", "decrease or increase w/h if necessary to keep the original AR", OFFSET(force_original_aspect_ratio), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, FLAGS, "force_oar" },
{ "disable", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 0 }, 0, 0, FLAGS, "force_oar" },
{ "decrease", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 1 }, 0, 0, FLAGS, "force_oar" },
{ "increase", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 2 }, 0, 0, FLAGS, "force_oar" },
{ "force_divisible_by", "enforce that the output resolution is divisible by a defined integer when force_original_aspect_ratio is used", OFFSET(force_divisible_by), AV_OPT_TYPE_INT, { .i64 = 1 }, 1, 256, FLAGS },
{ NULL },
};
static const AVClass cudascale_class = {
.class_name = "cudascale",
.item_name = av_default_item_name,
.option = options,
.version = LIBAVUTIL_VERSION_INT,
};
static const AVFilterPad cudascale_inputs[] = {
{
.name = "default",
.type = AVMEDIA_TYPE_VIDEO,
.filter_frame = cudascale_filter_frame,
.get_buffer.video = cudascale_get_video_buffer,
},
};
static const AVFilterPad cudascale_outputs[] = {
{
.name = "default",
.type = AVMEDIA_TYPE_VIDEO,
.config_props = cudascale_config_props,
},
};
const AVFilter ff_vf_scale_cuda = {
.name = "scale_cuda",
.description = NULL_IF_CONFIG_SMALL("GPU accelerated video resizer"),
.init = cudascale_init,
.uninit = cudascale_uninit,
.query_formats = cudascale_query_formats,
.priv_size = sizeof(CUDAScaleContext),
.priv_class = &cudascale_class,
FILTER_INPUTS(cudascale_inputs),
FILTER_OUTPUTS(cudascale_outputs),
.flags_internal = FF_FILTER_FLAG_HWFRAME_AWARE,
};
|
94455.c | // SPDX-License-Identifier: GPL-2.0-only
//
// GPIO Aggregator
//
// Copyright (C) 2019-2020 Glider bv
#define DRV_NAME "gpio-aggregator"
#define pr_fmt(fmt) DRV_NAME ": " fmt
#include <linux/bitmap.h>
#include <linux/bitops.h>
#include <linux/ctype.h>
#include <linux/gpio.h>
#include <linux/gpio/consumer.h>
#include <linux/gpio/driver.h>
#include <linux/gpio/machine.h>
#include <linux/idr.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/overflow.h>
#include <linux/platform_device.h>
#include <linux/spinlock.h>
#include <linux/string.h>
/*
* GPIO Aggregator sysfs interface
*/
struct gpio_aggregator {
struct gpiod_lookup_table *lookups;
struct platform_device *pdev;
char args[];
};
static DEFINE_MUTEX(gpio_aggregator_lock); /* protects idr */
static DEFINE_IDR(gpio_aggregator_idr);
static int aggr_add_gpio(struct gpio_aggregator *aggr, const char *key,
int hwnum, unsigned int *n)
{
struct gpiod_lookup_table *lookups;
lookups = krealloc(aggr->lookups, struct_size(lookups, table, *n + 2),
GFP_KERNEL);
if (!lookups)
return -ENOMEM;
lookups->table[*n] = GPIO_LOOKUP_IDX(key, hwnum, NULL, *n, 0);
(*n)++;
memset(&lookups->table[*n], 0, sizeof(lookups->table[*n]));
aggr->lookups = lookups;
return 0;
}
static int aggr_parse(struct gpio_aggregator *aggr)
{
char *args = skip_spaces(aggr->args);
char *name, *offsets, *p;
unsigned long *bitmap;
unsigned int i, n = 0;
int error = 0;
bitmap = bitmap_alloc(ARCH_NR_GPIOS, GFP_KERNEL);
if (!bitmap)
return -ENOMEM;
args = next_arg(args, &name, &p);
while (*args) {
args = next_arg(args, &offsets, &p);
p = get_options(offsets, 0, &error);
if (error == 0 || *p) {
/* Named GPIO line */
error = aggr_add_gpio(aggr, name, U16_MAX, &n);
if (error)
goto free_bitmap;
name = offsets;
continue;
}
/* GPIO chip + offset(s) */
error = bitmap_parselist(offsets, bitmap, ARCH_NR_GPIOS);
if (error) {
pr_err("Cannot parse %s: %d\n", offsets, error);
goto free_bitmap;
}
for_each_set_bit(i, bitmap, ARCH_NR_GPIOS) {
error = aggr_add_gpio(aggr, name, i, &n);
if (error)
goto free_bitmap;
}
args = next_arg(args, &name, &p);
}
if (!n) {
pr_err("No GPIOs specified\n");
error = -EINVAL;
}
free_bitmap:
bitmap_free(bitmap);
return error;
}
static ssize_t new_device_store(struct device_driver *driver, const char *buf,
size_t count)
{
struct gpio_aggregator *aggr;
struct platform_device *pdev;
int res, id;
/* kernfs guarantees string termination, so count + 1 is safe */
aggr = kzalloc(sizeof(*aggr) + count + 1, GFP_KERNEL);
if (!aggr)
return -ENOMEM;
memcpy(aggr->args, buf, count + 1);
aggr->lookups = kzalloc(struct_size(aggr->lookups, table, 1),
GFP_KERNEL);
if (!aggr->lookups) {
res = -ENOMEM;
goto free_ga;
}
mutex_lock(&gpio_aggregator_lock);
id = idr_alloc(&gpio_aggregator_idr, aggr, 0, 0, GFP_KERNEL);
mutex_unlock(&gpio_aggregator_lock);
if (id < 0) {
res = id;
goto free_table;
}
aggr->lookups->dev_id = kasprintf(GFP_KERNEL, "%s.%d", DRV_NAME, id);
if (!aggr->lookups->dev_id) {
res = -ENOMEM;
goto remove_idr;
}
res = aggr_parse(aggr);
if (res)
goto free_dev_id;
gpiod_add_lookup_table(aggr->lookups);
pdev = platform_device_register_simple(DRV_NAME, id, NULL, 0);
if (IS_ERR(pdev)) {
res = PTR_ERR(pdev);
goto remove_table;
}
aggr->pdev = pdev;
return count;
remove_table:
gpiod_remove_lookup_table(aggr->lookups);
free_dev_id:
kfree(aggr->lookups->dev_id);
remove_idr:
mutex_lock(&gpio_aggregator_lock);
idr_remove(&gpio_aggregator_idr, id);
mutex_unlock(&gpio_aggregator_lock);
free_table:
kfree(aggr->lookups);
free_ga:
kfree(aggr);
return res;
}
static DRIVER_ATTR_WO(new_device);
static void gpio_aggregator_free(struct gpio_aggregator *aggr)
{
platform_device_unregister(aggr->pdev);
gpiod_remove_lookup_table(aggr->lookups);
kfree(aggr->lookups->dev_id);
kfree(aggr->lookups);
kfree(aggr);
}
static ssize_t delete_device_store(struct device_driver *driver,
const char *buf, size_t count)
{
struct gpio_aggregator *aggr;
unsigned int id;
int error;
if (!str_has_prefix(buf, DRV_NAME "."))
return -EINVAL;
error = kstrtouint(buf + strlen(DRV_NAME "."), 10, &id);
if (error)
return error;
mutex_lock(&gpio_aggregator_lock);
aggr = idr_remove(&gpio_aggregator_idr, id);
mutex_unlock(&gpio_aggregator_lock);
if (!aggr)
return -ENOENT;
gpio_aggregator_free(aggr);
return count;
}
static DRIVER_ATTR_WO(delete_device);
static struct attribute *gpio_aggregator_attrs[] = {
&driver_attr_new_device.attr,
&driver_attr_delete_device.attr,
NULL
};
ATTRIBUTE_GROUPS(gpio_aggregator);
static int __exit gpio_aggregator_idr_remove(int id, void *p, void *data)
{
gpio_aggregator_free(p);
return 0;
}
static void __exit gpio_aggregator_remove_all(void)
{
mutex_lock(&gpio_aggregator_lock);
idr_for_each(&gpio_aggregator_idr, gpio_aggregator_idr_remove, NULL);
idr_destroy(&gpio_aggregator_idr);
mutex_unlock(&gpio_aggregator_lock);
}
/*
* GPIO Forwarder
*/
struct gpiochip_fwd {
struct gpio_chip chip;
struct gpio_desc **descs;
union {
struct mutex mlock; /* protects tmp[] if can_sleep */
spinlock_t slock; /* protects tmp[] if !can_sleep */
};
unsigned long tmp[]; /* values and descs for multiple ops */
};
static int gpio_fwd_get_direction(struct gpio_chip *chip, unsigned int offset)
{
struct gpiochip_fwd *fwd = gpiochip_get_data(chip);
return gpiod_get_direction(fwd->descs[offset]);
}
static int gpio_fwd_direction_input(struct gpio_chip *chip, unsigned int offset)
{
struct gpiochip_fwd *fwd = gpiochip_get_data(chip);
return gpiod_direction_input(fwd->descs[offset]);
}
static int gpio_fwd_direction_output(struct gpio_chip *chip,
unsigned int offset, int value)
{
struct gpiochip_fwd *fwd = gpiochip_get_data(chip);
return gpiod_direction_output(fwd->descs[offset], value);
}
static int gpio_fwd_get(struct gpio_chip *chip, unsigned int offset)
{
struct gpiochip_fwd *fwd = gpiochip_get_data(chip);
return gpiod_get_value(fwd->descs[offset]);
}
static int gpio_fwd_get_multiple(struct gpiochip_fwd *fwd, unsigned long *mask,
unsigned long *bits)
{
struct gpio_desc **descs;
unsigned long *values;
unsigned int i, j = 0;
int error;
/* Both values bitmap and desc pointers are stored in tmp[] */
values = &fwd->tmp[0];
descs = (void *)&fwd->tmp[BITS_TO_LONGS(fwd->chip.ngpio)];
bitmap_clear(values, 0, fwd->chip.ngpio);
for_each_set_bit(i, mask, fwd->chip.ngpio)
descs[j++] = fwd->descs[i];
error = gpiod_get_array_value(j, descs, NULL, values);
if (error)
return error;
j = 0;
for_each_set_bit(i, mask, fwd->chip.ngpio)
__assign_bit(i, bits, test_bit(j++, values));
return 0;
}
static int gpio_fwd_get_multiple_locked(struct gpio_chip *chip,
unsigned long *mask, unsigned long *bits)
{
struct gpiochip_fwd *fwd = gpiochip_get_data(chip);
unsigned long flags;
int error;
if (chip->can_sleep) {
mutex_lock(&fwd->mlock);
error = gpio_fwd_get_multiple(fwd, mask, bits);
mutex_unlock(&fwd->mlock);
} else {
spin_lock_irqsave(&fwd->slock, flags);
error = gpio_fwd_get_multiple(fwd, mask, bits);
spin_unlock_irqrestore(&fwd->slock, flags);
}
return error;
}
static void gpio_fwd_set(struct gpio_chip *chip, unsigned int offset, int value)
{
struct gpiochip_fwd *fwd = gpiochip_get_data(chip);
gpiod_set_value(fwd->descs[offset], value);
}
static void gpio_fwd_set_multiple(struct gpiochip_fwd *fwd, unsigned long *mask,
unsigned long *bits)
{
struct gpio_desc **descs;
unsigned long *values;
unsigned int i, j = 0;
/* Both values bitmap and desc pointers are stored in tmp[] */
values = &fwd->tmp[0];
descs = (void *)&fwd->tmp[BITS_TO_LONGS(fwd->chip.ngpio)];
for_each_set_bit(i, mask, fwd->chip.ngpio) {
__assign_bit(j, values, test_bit(i, bits));
descs[j++] = fwd->descs[i];
}
gpiod_set_array_value(j, descs, NULL, values);
}
static void gpio_fwd_set_multiple_locked(struct gpio_chip *chip,
unsigned long *mask, unsigned long *bits)
{
struct gpiochip_fwd *fwd = gpiochip_get_data(chip);
unsigned long flags;
if (chip->can_sleep) {
mutex_lock(&fwd->mlock);
gpio_fwd_set_multiple(fwd, mask, bits);
mutex_unlock(&fwd->mlock);
} else {
spin_lock_irqsave(&fwd->slock, flags);
gpio_fwd_set_multiple(fwd, mask, bits);
spin_unlock_irqrestore(&fwd->slock, flags);
}
}
static int gpio_fwd_set_config(struct gpio_chip *chip, unsigned int offset,
unsigned long config)
{
struct gpiochip_fwd *fwd = gpiochip_get_data(chip);
return gpiod_set_config(fwd->descs[offset], config);
}
/**
* gpiochip_fwd_create() - Create a new GPIO forwarder
* @dev: Parent device pointer
* @ngpios: Number of GPIOs in the forwarder.
* @descs: Array containing the GPIO descriptors to forward to.
* This array must contain @ngpios entries, and must not be deallocated
* before the forwarder has been destroyed again.
*
* This function creates a new gpiochip, which forwards all GPIO operations to
* the passed GPIO descriptors.
*
* Return: An opaque object pointer, or an ERR_PTR()-encoded negative error
* code on failure.
*/
static struct gpiochip_fwd *gpiochip_fwd_create(struct device *dev,
unsigned int ngpios,
struct gpio_desc *descs[])
{
const char *label = dev_name(dev);
struct gpiochip_fwd *fwd;
struct gpio_chip *chip;
unsigned int i;
int error;
fwd = devm_kzalloc(dev, struct_size(fwd, tmp,
BITS_TO_LONGS(ngpios) + ngpios), GFP_KERNEL);
if (!fwd)
return ERR_PTR(-ENOMEM);
chip = &fwd->chip;
/*
* If any of the GPIO lines are sleeping, then the entire forwarder
* will be sleeping.
* If any of the chips support .set_config(), then the forwarder will
* support setting configs.
*/
for (i = 0; i < ngpios; i++) {
struct gpio_chip *parent = gpiod_to_chip(descs[i]);
dev_dbg(dev, "%u => gpio-%d\n", i, desc_to_gpio(descs[i]));
if (gpiod_cansleep(descs[i]))
chip->can_sleep = true;
if (parent && parent->set_config)
chip->set_config = gpio_fwd_set_config;
}
chip->label = label;
chip->parent = dev;
chip->owner = THIS_MODULE;
chip->get_direction = gpio_fwd_get_direction;
chip->direction_input = gpio_fwd_direction_input;
chip->direction_output = gpio_fwd_direction_output;
chip->get = gpio_fwd_get;
chip->get_multiple = gpio_fwd_get_multiple_locked;
chip->set = gpio_fwd_set;
chip->set_multiple = gpio_fwd_set_multiple_locked;
chip->base = -1;
chip->ngpio = ngpios;
fwd->descs = descs;
if (chip->can_sleep)
mutex_init(&fwd->mlock);
else
spin_lock_init(&fwd->slock);
error = devm_gpiochip_add_data(dev, chip, fwd);
if (error)
return ERR_PTR(error);
return fwd;
}
/*
* GPIO Aggregator platform device
*/
static int gpio_aggregator_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct gpio_desc **descs;
struct gpiochip_fwd *fwd;
int i, n;
n = gpiod_count(dev, NULL);
if (n < 0)
return n;
descs = devm_kmalloc_array(dev, n, sizeof(*descs), GFP_KERNEL);
if (!descs)
return -ENOMEM;
for (i = 0; i < n; i++) {
descs[i] = devm_gpiod_get_index(dev, NULL, i, GPIOD_ASIS);
if (IS_ERR(descs[i]))
return PTR_ERR(descs[i]);
}
fwd = gpiochip_fwd_create(dev, n, descs);
if (IS_ERR(fwd))
return PTR_ERR(fwd);
platform_set_drvdata(pdev, fwd);
return 0;
}
#ifdef CONFIG_OF
static const struct of_device_id gpio_aggregator_dt_ids[] = {
/*
* Add GPIO-operated devices controlled from userspace below,
* or use "driver_override" in sysfs
*/
{}
};
MODULE_DEVICE_TABLE(of, gpio_aggregator_dt_ids);
#endif
static struct platform_driver gpio_aggregator_driver = {
.probe = gpio_aggregator_probe,
.driver = {
.name = DRV_NAME,
.groups = gpio_aggregator_groups,
.of_match_table = of_match_ptr(gpio_aggregator_dt_ids),
},
};
static int __init gpio_aggregator_init(void)
{
return platform_driver_register(&gpio_aggregator_driver);
}
module_init(gpio_aggregator_init);
static void __exit gpio_aggregator_exit(void)
{
gpio_aggregator_remove_all();
platform_driver_unregister(&gpio_aggregator_driver);
}
module_exit(gpio_aggregator_exit);
MODULE_AUTHOR("Geert Uytterhoeven <[email protected]>");
MODULE_DESCRIPTION("GPIO Aggregator");
MODULE_LICENSE("GPL v2");
|
784131.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 "spdk/stdinc.h"
#include "spdk_cunit.h"
#include "spdk/blob.h"
#include "spdk/string.h"
#include "spdk_internal/thread.h"
#include "common/lib/ut_multithread.c"
#include "../bs_dev_common.c"
#include "blob/blobstore.c"
#include "blob/request.c"
#include "blob/zeroes.c"
#include "blob/blob_bs_dev.c"
struct spdk_blob_store *g_bs;
spdk_blob_id g_blobid;
struct spdk_blob *g_blob;
int g_bserrno;
struct spdk_xattr_names *g_names;
int g_done;
char *g_xattr_names[] = {"first", "second", "third"};
char *g_xattr_values[] = {"one", "two", "three"};
uint64_t g_ctx = 1729;
struct spdk_bs_super_block_ver1 {
uint8_t signature[8];
uint32_t version;
uint32_t length;
uint32_t clean; /* If there was a clean shutdown, this is 1. */
spdk_blob_id super_blob;
uint32_t cluster_size; /* In bytes */
uint32_t used_page_mask_start; /* Offset from beginning of disk, in pages */
uint32_t used_page_mask_len; /* Count, in pages */
uint32_t used_cluster_mask_start; /* Offset from beginning of disk, in pages */
uint32_t used_cluster_mask_len; /* Count, in pages */
uint32_t md_start; /* Offset from beginning of disk, in pages */
uint32_t md_len; /* Count, in pages */
uint8_t reserved[4036];
uint32_t crc;
} __attribute__((packed));
SPDK_STATIC_ASSERT(sizeof(struct spdk_bs_super_block_ver1) == 0x1000, "Invalid super block size");
static void
_get_xattr_value(void *arg, const char *name,
const void **value, size_t *value_len)
{
uint64_t i;
SPDK_CU_ASSERT_FATAL(value_len != NULL);
SPDK_CU_ASSERT_FATAL(value != NULL);
CU_ASSERT(arg == &g_ctx);
for (i = 0; i < sizeof(g_xattr_names); i++) {
if (!strcmp(name, g_xattr_names[i])) {
*value_len = strlen(g_xattr_values[i]);
*value = g_xattr_values[i];
break;
}
}
}
static void
_get_xattr_value_null(void *arg, const char *name,
const void **value, size_t *value_len)
{
SPDK_CU_ASSERT_FATAL(value_len != NULL);
SPDK_CU_ASSERT_FATAL(value != NULL);
CU_ASSERT(arg == NULL);
*value_len = 0;
*value = NULL;
}
static int
_get_snapshots_count(struct spdk_blob_store *bs)
{
struct spdk_blob_list *snapshot = NULL;
int count = 0;
TAILQ_FOREACH(snapshot, &bs->snapshots, link) {
count += 1;
}
return count;
}
static void
bs_op_complete(void *cb_arg, int bserrno)
{
g_bserrno = bserrno;
}
static void
bs_op_with_handle_complete(void *cb_arg, struct spdk_blob_store *bs,
int bserrno)
{
g_bs = bs;
g_bserrno = bserrno;
}
static void
blob_op_complete(void *cb_arg, int bserrno)
{
g_bserrno = bserrno;
}
static void
blob_op_with_id_complete(void *cb_arg, spdk_blob_id blobid, int bserrno)
{
g_blobid = blobid;
g_bserrno = bserrno;
}
static void
blob_op_with_handle_complete(void *cb_arg, struct spdk_blob *blb, int bserrno)
{
g_blob = blb;
g_bserrno = bserrno;
}
static void
blob_init(void)
{
struct spdk_bs_dev *dev;
dev = init_dev();
/* should fail for an unsupported blocklen */
dev->blocklen = 500;
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -EINVAL);
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
blob_super(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
spdk_blob_id blobid;
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
/* Get the super blob without having set one */
spdk_bs_get_super(bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -ENOENT);
CU_ASSERT(g_blobid == SPDK_BLOBID_INVALID);
/* Create a blob */
spdk_bs_create_blob(bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
/* Set the blob as the super blob */
spdk_bs_set_super(bs, blobid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Get the super blob */
spdk_bs_get_super(bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(blobid == g_blobid);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
blob_open(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob;
spdk_blob_id blobid, blobid2;
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
spdk_bs_create_blob(bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blob != NULL);
blob = g_blob;
blobid2 = spdk_blob_get_id(blob);
CU_ASSERT(blobid == blobid2);
/* Try to open file again. It should return success. */
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(blob == g_blob);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/*
* Close the file a second time, releasing the second reference. This
* should succeed.
*/
blob = g_blob;
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/*
* Try to open file again. It should succeed. This tests the case
* where the file is opened, closed, then re-opened again.
*/
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blob != NULL);
blob = g_blob;
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
blob_create(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob;
struct spdk_blob_opts opts;
spdk_blob_id blobid;
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
/* Create blob with 10 clusters */
spdk_blob_opts_init(&opts);
opts.num_clusters = 10;
spdk_bs_create_blob_ext(bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
CU_ASSERT(spdk_blob_get_num_clusters(blob) == 10);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Create blob with 0 clusters */
spdk_blob_opts_init(&opts);
opts.num_clusters = 0;
spdk_bs_create_blob_ext(bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
CU_ASSERT(spdk_blob_get_num_clusters(blob) == 0);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Create blob with default options (opts == NULL) */
spdk_bs_create_blob_ext(bs, NULL, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
CU_ASSERT(spdk_blob_get_num_clusters(blob) == 0);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Try to create blob with size larger than blobstore */
spdk_blob_opts_init(&opts);
opts.num_clusters = bs->total_clusters + 1;
spdk_bs_create_blob_ext(bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -ENOSPC);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
blob_create_internal(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob;
struct spdk_blob_opts opts;
struct spdk_blob_xattr_opts internal_xattrs;
const void *value;
size_t value_len;
spdk_blob_id blobid;
int rc;
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
/* Create blob with custom xattrs */
spdk_blob_opts_init(&opts);
_spdk_blob_xattrs_init(&internal_xattrs);
internal_xattrs.count = 3;
internal_xattrs.names = g_xattr_names;
internal_xattrs.get_value = _get_xattr_value;
internal_xattrs.ctx = &g_ctx;
_spdk_bs_create_blob(bs, &opts, &internal_xattrs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
rc = _spdk_blob_get_xattr_value(blob, g_xattr_names[0], &value, &value_len, true);
CU_ASSERT(rc == 0);
SPDK_CU_ASSERT_FATAL(value != NULL);
CU_ASSERT(value_len == strlen(g_xattr_values[0]));
CU_ASSERT_NSTRING_EQUAL_FATAL(value, g_xattr_values[0], value_len);
rc = _spdk_blob_get_xattr_value(blob, g_xattr_names[1], &value, &value_len, true);
CU_ASSERT(rc == 0);
SPDK_CU_ASSERT_FATAL(value != NULL);
CU_ASSERT(value_len == strlen(g_xattr_values[1]));
CU_ASSERT_NSTRING_EQUAL((char *)value, g_xattr_values[1], value_len);
rc = _spdk_blob_get_xattr_value(blob, g_xattr_names[2], &value, &value_len, true);
CU_ASSERT(rc == 0);
SPDK_CU_ASSERT_FATAL(value != NULL);
CU_ASSERT(value_len == strlen(g_xattr_values[2]));
CU_ASSERT_NSTRING_EQUAL((char *)value, g_xattr_values[2], value_len);
rc = spdk_blob_get_xattr_value(blob, g_xattr_names[0], &value, &value_len);
CU_ASSERT(rc != 0);
rc = spdk_blob_get_xattr_value(blob, g_xattr_names[1], &value, &value_len);
CU_ASSERT(rc != 0);
rc = spdk_blob_get_xattr_value(blob, g_xattr_names[2], &value, &value_len);
CU_ASSERT(rc != 0);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Create blob with NULL internal options */
_spdk_bs_create_blob(bs, NULL, NULL, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
CU_ASSERT(TAILQ_FIRST(&g_blob->xattrs_internal) == NULL);
blob = g_blob;
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
blob_thin_provision(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob;
struct spdk_blob_opts opts;
struct spdk_bs_opts bs_opts;
spdk_blob_id blobid;
dev = init_dev();
spdk_bs_opts_init(&bs_opts);
snprintf(bs_opts.bstype.bstype, sizeof(bs_opts.bstype.bstype), "TESTTYPE");
/* Initialize a new blob store */
spdk_bs_init(dev, &bs_opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
/* Create blob with thin provisioning enabled */
spdk_blob_opts_init(&opts);
opts.thin_provision = true;
opts.num_clusters = 10;
spdk_bs_create_blob_ext(bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
CU_ASSERT(blob->invalid_flags & SPDK_BLOB_THIN_PROV);
spdk_blob_close(blob, blob_op_complete, NULL);
CU_ASSERT(g_bserrno == 0);
/* Do not shut down cleanly. This makes sure that when we load again
* and try to recover a valid used_cluster map, that blobstore will
* ignore clusters with index 0 since these are unallocated clusters.
*/
/* Load an existing blob store and check if invalid_flags is set */
dev = init_dev();
snprintf(bs_opts.bstype.bstype, sizeof(bs_opts.bstype.bstype), "TESTTYPE");
spdk_bs_load(dev, &bs_opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
CU_ASSERT(blob->invalid_flags & SPDK_BLOB_THIN_PROV);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
blob_snapshot(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob;
struct spdk_blob *snapshot, *snapshot2;
struct spdk_blob_bs_dev *blob_bs_dev;
struct spdk_blob_opts opts;
struct spdk_blob_xattr_opts xattrs;
spdk_blob_id blobid;
spdk_blob_id snapshotid;
spdk_blob_id snapshotid2;
const void *value;
size_t value_len;
int rc;
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
/* Create blob with 10 clusters */
spdk_blob_opts_init(&opts);
opts.num_clusters = 10;
spdk_bs_create_blob_ext(bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
CU_ASSERT(spdk_blob_get_num_clusters(blob) == 10);
/* Create snapshot from blob */
CU_ASSERT_EQUAL(_get_snapshots_count(bs), 0);
spdk_bs_create_snapshot(bs, blobid, NULL, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
CU_ASSERT_EQUAL(_get_snapshots_count(bs), 1);
snapshotid = g_blobid;
spdk_bs_open_blob(bs, snapshotid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
snapshot = g_blob;
CU_ASSERT(snapshot->data_ro == true);
CU_ASSERT(snapshot->md_ro == true);
CU_ASSERT(spdk_blob_get_num_clusters(snapshot) == 10);
CU_ASSERT(spdk_blob_get_num_clusters(blob) == 10);
CU_ASSERT(blob->invalid_flags & SPDK_BLOB_THIN_PROV);
CU_ASSERT(spdk_mem_all_zero(blob->active.clusters,
blob->active.num_clusters * sizeof(blob->active.clusters[0])));
/* Try to create snapshot from clone with xattrs */
xattrs.names = g_xattr_names;
xattrs.get_value = _get_xattr_value;
xattrs.count = 3;
xattrs.ctx = &g_ctx;
spdk_bs_create_snapshot(bs, blobid, &xattrs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
CU_ASSERT_EQUAL(_get_snapshots_count(bs), 2);
snapshotid2 = g_blobid;
spdk_bs_open_blob(bs, snapshotid2, blob_op_with_handle_complete, NULL);
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
snapshot2 = g_blob;
CU_ASSERT(snapshot2->data_ro == true);
CU_ASSERT(snapshot2->md_ro == true);
CU_ASSERT(spdk_blob_get_num_clusters(snapshot2) == 10);
/* Confirm that blob is backed by snapshot2 and snapshot2 is backed by snapshot */
CU_ASSERT(snapshot->back_bs_dev == NULL);
SPDK_CU_ASSERT_FATAL(blob->back_bs_dev != NULL);
SPDK_CU_ASSERT_FATAL(snapshot2->back_bs_dev != NULL);
blob_bs_dev = (struct spdk_blob_bs_dev *)blob->back_bs_dev;
CU_ASSERT(blob_bs_dev->blob == snapshot2);
blob_bs_dev = (struct spdk_blob_bs_dev *)snapshot2->back_bs_dev;
CU_ASSERT(blob_bs_dev->blob == snapshot);
rc = spdk_blob_get_xattr_value(snapshot2, g_xattr_names[0], &value, &value_len);
CU_ASSERT(rc == 0);
SPDK_CU_ASSERT_FATAL(value != NULL);
CU_ASSERT(value_len == strlen(g_xattr_values[0]));
CU_ASSERT_NSTRING_EQUAL_FATAL(value, g_xattr_values[0], value_len);
rc = spdk_blob_get_xattr_value(snapshot2, g_xattr_names[1], &value, &value_len);
CU_ASSERT(rc == 0);
SPDK_CU_ASSERT_FATAL(value != NULL);
CU_ASSERT(value_len == strlen(g_xattr_values[1]));
CU_ASSERT_NSTRING_EQUAL((char *)value, g_xattr_values[1], value_len);
rc = spdk_blob_get_xattr_value(snapshot2, g_xattr_names[2], &value, &value_len);
CU_ASSERT(rc == 0);
SPDK_CU_ASSERT_FATAL(value != NULL);
CU_ASSERT(value_len == strlen(g_xattr_values[2]));
CU_ASSERT_NSTRING_EQUAL((char *)value, g_xattr_values[2], value_len);
/* Try to create snapshot from snapshot */
spdk_bs_create_snapshot(bs, snapshotid, NULL, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -EINVAL);
CU_ASSERT(g_blobid == SPDK_BLOBID_INVALID);
CU_ASSERT_EQUAL(_get_snapshots_count(bs), 2);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_delete_blob(bs, blobid, blob_op_complete, NULL);
CU_ASSERT(g_bserrno == 0);
CU_ASSERT_EQUAL(_get_snapshots_count(bs), 2);
spdk_blob_close(snapshot2, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_delete_blob(bs, snapshotid2, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT_EQUAL(_get_snapshots_count(bs), 1);
spdk_blob_close(snapshot, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_delete_blob(bs, snapshotid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT_EQUAL(_get_snapshots_count(bs), 0);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
blob_snapshot_freeze_io(void)
{
struct spdk_thread *thread;
struct spdk_io_channel *channel;
struct spdk_bs_channel *bs_channel;
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob;
struct spdk_blob_opts opts;
spdk_blob_id blobid;
uint32_t num_of_pages = 10;
uint8_t payload_read[num_of_pages * SPDK_BS_PAGE_SIZE];
uint8_t payload_write[num_of_pages * SPDK_BS_PAGE_SIZE];
uint8_t payload_zero[num_of_pages * SPDK_BS_PAGE_SIZE];
memset(payload_write, 0xE5, sizeof(payload_write));
memset(payload_read, 0x00, sizeof(payload_read));
memset(payload_zero, 0x00, sizeof(payload_zero));
dev = init_dev();
memset(g_dev_buffer, 0, DEV_BUFFER_SIZE);
/* Test freeze I/O during snapshot */
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
channel = spdk_bs_alloc_io_channel(bs);
bs_channel = spdk_io_channel_get_ctx(channel);
/* Create blob with 10 clusters */
spdk_blob_opts_init(&opts);
opts.num_clusters = 10;
opts.thin_provision = false;
spdk_bs_create_blob_ext(bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
CU_ASSERT(spdk_blob_get_num_clusters(blob) == 10);
spdk_bs_create_snapshot(bs, blobid, NULL, blob_op_with_id_complete, NULL);
/* This is implementation specific.
* Flag 'frozen_io' is set in _spdk_bs_snapshot_freeze_cpl callback.
* Four async I/O operations happen before that. */
thread = spdk_get_thread();
spdk_thread_poll(thread, 1, 0);
spdk_thread_poll(thread, 1, 0);
spdk_thread_poll(thread, 1, 0);
CU_ASSERT(TAILQ_EMPTY(&bs_channel->queued_io));
/* Blob I/O should be frozen here */
CU_ASSERT(blob->frozen_refcnt == 1);
/* Write to the blob */
spdk_blob_io_write(blob, channel, payload_write, 0, num_of_pages, blob_op_complete, NULL);
/* Verify that I/O is queued */
CU_ASSERT(!TAILQ_EMPTY(&bs_channel->queued_io));
/* Verify that payload is not written to disk */
CU_ASSERT(memcmp(payload_zero, &g_dev_buffer[blob->active.clusters[0]*SPDK_BS_PAGE_SIZE],
SPDK_BS_PAGE_SIZE) == 0);
/* Finish all operations including spdk_bs_create_snapshot */
poll_threads();
/* Verify snapshot */
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
/* Verify that blob has unset frozen_io */
CU_ASSERT(blob->frozen_refcnt == 0);
/* Verify that postponed I/O completed successfully by comparing payload */
spdk_blob_io_read(blob, channel, payload_read, 0, num_of_pages, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_write, payload_read, num_of_pages * SPDK_BS_PAGE_SIZE) == 0);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_free_io_channel(channel);
poll_threads();
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
blob_clone(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob_opts opts;
struct spdk_blob *blob, *snapshot, *clone;
spdk_blob_id blobid, cloneid, snapshotid;
struct spdk_blob_xattr_opts xattrs;
const void *value;
size_t value_len;
int rc;
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
/* Create blob with 10 clusters */
spdk_blob_opts_init(&opts);
opts.num_clusters = 10;
spdk_bs_create_blob_ext(bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
CU_ASSERT(spdk_blob_get_num_clusters(blob) == 10);
/* Create snapshot */
spdk_bs_create_snapshot(bs, blobid, NULL, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
snapshotid = g_blobid;
spdk_bs_open_blob(bs, snapshotid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
snapshot = g_blob;
CU_ASSERT(snapshot->data_ro == true);
CU_ASSERT(snapshot->md_ro == true);
CU_ASSERT(spdk_blob_get_num_clusters(snapshot) == 10);
spdk_blob_close(snapshot, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Create clone from snapshot with xattrs */
xattrs.names = g_xattr_names;
xattrs.get_value = _get_xattr_value;
xattrs.count = 3;
xattrs.ctx = &g_ctx;
spdk_bs_create_clone(bs, snapshotid, &xattrs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
cloneid = g_blobid;
spdk_bs_open_blob(bs, cloneid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
clone = g_blob;
CU_ASSERT(clone->data_ro == false);
CU_ASSERT(clone->md_ro == false);
CU_ASSERT(spdk_blob_get_num_clusters(clone) == 10);
rc = spdk_blob_get_xattr_value(clone, g_xattr_names[0], &value, &value_len);
CU_ASSERT(rc == 0);
SPDK_CU_ASSERT_FATAL(value != NULL);
CU_ASSERT(value_len == strlen(g_xattr_values[0]));
CU_ASSERT_NSTRING_EQUAL_FATAL(value, g_xattr_values[0], value_len);
rc = spdk_blob_get_xattr_value(clone, g_xattr_names[1], &value, &value_len);
CU_ASSERT(rc == 0);
SPDK_CU_ASSERT_FATAL(value != NULL);
CU_ASSERT(value_len == strlen(g_xattr_values[1]));
CU_ASSERT_NSTRING_EQUAL((char *)value, g_xattr_values[1], value_len);
rc = spdk_blob_get_xattr_value(clone, g_xattr_names[2], &value, &value_len);
CU_ASSERT(rc == 0);
SPDK_CU_ASSERT_FATAL(value != NULL);
CU_ASSERT(value_len == strlen(g_xattr_values[2]));
CU_ASSERT_NSTRING_EQUAL((char *)value, g_xattr_values[2], value_len);
spdk_blob_close(clone, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Try to create clone from not read only blob */
spdk_bs_create_clone(bs, blobid, NULL, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -EINVAL);
CU_ASSERT(g_blobid == SPDK_BLOBID_INVALID);
/* Mark blob as read only */
spdk_blob_set_read_only(blob);
spdk_blob_sync_md(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Create clone from read only blob */
spdk_bs_create_clone(bs, blobid, NULL, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
cloneid = g_blobid;
spdk_bs_open_blob(bs, cloneid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
clone = g_blob;
CU_ASSERT(clone->data_ro == false);
CU_ASSERT(clone->md_ro == false);
CU_ASSERT(spdk_blob_get_num_clusters(clone) == 10);
spdk_blob_close(clone, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
_blob_inflate(bool decouple_parent)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob_opts opts;
struct spdk_blob *blob, *snapshot;
spdk_blob_id blobid, snapshotid;
struct spdk_io_channel *channel;
uint64_t free_clusters;
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
channel = spdk_bs_alloc_io_channel(bs);
SPDK_CU_ASSERT_FATAL(channel != NULL);
/* Create blob with 10 clusters */
spdk_blob_opts_init(&opts);
opts.num_clusters = 10;
opts.thin_provision = true;
spdk_bs_create_blob_ext(bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
CU_ASSERT(spdk_blob_get_num_clusters(blob) == 10);
CU_ASSERT(spdk_blob_is_thin_provisioned(blob) == true);
/* 1) Blob with no parent */
if (decouple_parent) {
/* Decouple parent of blob with no parent (should fail) */
spdk_bs_blob_decouple_parent(bs, channel, blobid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno != 0);
} else {
/* Inflate of thin blob with no parent should made it thick */
spdk_bs_inflate_blob(bs, channel, blobid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(spdk_blob_is_thin_provisioned(blob) == false);
}
spdk_bs_create_snapshot(bs, blobid, NULL, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
snapshotid = g_blobid;
CU_ASSERT(spdk_blob_is_thin_provisioned(blob) == true);
CU_ASSERT(spdk_blob_get_num_clusters(blob) == 10);
spdk_bs_open_blob(bs, snapshotid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
snapshot = g_blob;
CU_ASSERT(snapshot->data_ro == true);
CU_ASSERT(snapshot->md_ro == true);
CU_ASSERT(spdk_blob_get_num_clusters(snapshot) == 10);
spdk_blob_close(snapshot, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
free_clusters = spdk_bs_free_cluster_count(bs);
/* 2) Blob with parent */
if (!decouple_parent) {
/* Do full blob inflation */
spdk_bs_inflate_blob(bs, channel, blobid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* all 10 clusters should be allocated */
CU_ASSERT(spdk_bs_free_cluster_count(bs) == free_clusters - 10);
} else {
/* Decouple parent of blob */
spdk_bs_blob_decouple_parent(bs, channel, blobid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* when only parent is removed, none of the clusters should be allocated */
CU_ASSERT(spdk_bs_free_cluster_count(bs) == free_clusters);
}
/* Now, it should be possible to delete snapshot */
spdk_bs_delete_blob(bs, snapshotid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(spdk_blob_get_num_clusters(blob) == 10);
CU_ASSERT(spdk_blob_is_thin_provisioned(blob) == decouple_parent);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
spdk_bs_free_io_channel(channel);
poll_threads();
}
static void
blob_inflate(void)
{
_blob_inflate(false);
_blob_inflate(true);
}
static void
blob_delete(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
spdk_blob_id blobid;
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
/* Create a blob and then delete it. */
spdk_bs_create_blob(bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid > 0);
blobid = g_blobid;
spdk_bs_delete_blob(bs, blobid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Try to open the blob */
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -ENOENT);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
blob_resize(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob;
spdk_blob_id blobid;
uint64_t free_clusters;
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
free_clusters = spdk_bs_free_cluster_count(bs);
spdk_bs_create_blob(bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
CU_ASSERT(free_clusters == spdk_bs_free_cluster_count(bs));
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
/* Confirm that resize fails if blob is marked read-only. */
blob->md_ro = true;
spdk_blob_resize(blob, 5, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -EPERM);
blob->md_ro = false;
/* The blob started at 0 clusters. Resize it to be 5. */
spdk_blob_resize(blob, 5, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT((free_clusters - 5) == spdk_bs_free_cluster_count(bs));
/* Shrink the blob to 3 clusters. This will not actually release
* the old clusters until the blob is synced.
*/
spdk_blob_resize(blob, 3, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Verify there are still 5 clusters in use */
CU_ASSERT((free_clusters - 5) == spdk_bs_free_cluster_count(bs));
spdk_blob_sync_md(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Now there are only 3 clusters in use */
CU_ASSERT((free_clusters - 3) == spdk_bs_free_cluster_count(bs));
/* Resize the blob to be 10 clusters. Growth takes effect immediately. */
spdk_blob_resize(blob, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT((free_clusters - 10) == spdk_bs_free_cluster_count(bs));
/* Try to resize the blob to size larger than blobstore. */
spdk_blob_resize(blob, bs->total_clusters + 1, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -ENOSPC);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_delete_blob(bs, blobid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
blob_read_only(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob;
struct spdk_bs_opts opts;
spdk_blob_id blobid;
int rc;
dev = init_dev();
spdk_bs_opts_init(&opts);
snprintf(opts.bstype.bstype, sizeof(opts.bstype.bstype), "TESTTYPE");
spdk_bs_init(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
spdk_bs_create_blob(bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
rc = spdk_blob_set_read_only(blob);
CU_ASSERT(rc == 0);
CU_ASSERT(blob->data_ro == false);
CU_ASSERT(blob->md_ro == false);
spdk_blob_sync_md(blob, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(blob->data_ro == true);
CU_ASSERT(blob->md_ro == true);
CU_ASSERT(blob->data_ro_flags & SPDK_BLOB_READ_ONLY);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
CU_ASSERT(blob->data_ro == true);
CU_ASSERT(blob->md_ro == true);
CU_ASSERT(blob->data_ro_flags & SPDK_BLOB_READ_ONLY);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
g_blob = NULL;
g_blobid = 0;
/* Load an existing blob store */
dev = init_dev();
snprintf(opts.bstype.bstype, sizeof(opts.bstype.bstype), "TESTTYPE");
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
spdk_bs_open_blob(g_bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
CU_ASSERT(blob->data_ro == true);
CU_ASSERT(blob->md_ro == true);
CU_ASSERT(blob->data_ro_flags & SPDK_BLOB_READ_ONLY);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
}
static void
channel_ops(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_io_channel *channel;
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
channel = spdk_bs_alloc_io_channel(bs);
CU_ASSERT(channel != NULL);
spdk_bs_free_io_channel(channel);
poll_threads();
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
blob_write(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob;
struct spdk_io_channel *channel;
spdk_blob_id blobid;
uint64_t pages_per_cluster;
uint8_t payload[10 * 4096];
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
pages_per_cluster = spdk_bs_get_cluster_size(bs) / spdk_bs_get_page_size(bs);
channel = spdk_bs_alloc_io_channel(bs);
CU_ASSERT(channel != NULL);
spdk_bs_create_blob(bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
/* Write to a blob with 0 size */
spdk_blob_io_write(blob, channel, payload, 0, 1, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -EINVAL);
/* Resize the blob */
spdk_blob_resize(blob, 5, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Confirm that write fails if blob is marked read-only. */
blob->data_ro = true;
spdk_blob_io_write(blob, channel, payload, 0, 1, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -EPERM);
blob->data_ro = false;
/* Write to the blob */
spdk_blob_io_write(blob, channel, payload, 0, 1, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Write starting beyond the end */
spdk_blob_io_write(blob, channel, payload, 5 * pages_per_cluster, 1, blob_op_complete,
NULL);
poll_threads();
CU_ASSERT(g_bserrno == -EINVAL);
/* Write starting at a valid location but going off the end */
spdk_blob_io_write(blob, channel, payload, 4 * pages_per_cluster, pages_per_cluster + 1,
blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -EINVAL);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_free_io_channel(channel);
poll_threads();
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
blob_read(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob;
struct spdk_io_channel *channel;
spdk_blob_id blobid;
uint64_t pages_per_cluster;
uint8_t payload[10 * 4096];
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
pages_per_cluster = spdk_bs_get_cluster_size(bs) / spdk_bs_get_page_size(bs);
channel = spdk_bs_alloc_io_channel(bs);
CU_ASSERT(channel != NULL);
spdk_bs_create_blob(bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
/* Read from a blob with 0 size */
spdk_blob_io_read(blob, channel, payload, 0, 1, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -EINVAL);
/* Resize the blob */
spdk_blob_resize(blob, 5, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Confirm that read passes if blob is marked read-only. */
blob->data_ro = true;
spdk_blob_io_read(blob, channel, payload, 0, 1, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
blob->data_ro = false;
/* Read from the blob */
spdk_blob_io_read(blob, channel, payload, 0, 1, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Read starting beyond the end */
spdk_blob_io_read(blob, channel, payload, 5 * pages_per_cluster, 1, blob_op_complete,
NULL);
poll_threads();
CU_ASSERT(g_bserrno == -EINVAL);
/* Read starting at a valid location but going off the end */
spdk_blob_io_read(blob, channel, payload, 4 * pages_per_cluster, pages_per_cluster + 1,
blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -EINVAL);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_free_io_channel(channel);
poll_threads();
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
blob_rw_verify(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob;
struct spdk_io_channel *channel;
spdk_blob_id blobid;
uint8_t payload_read[10 * 4096];
uint8_t payload_write[10 * 4096];
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
channel = spdk_bs_alloc_io_channel(bs);
CU_ASSERT(channel != NULL);
spdk_bs_create_blob(bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blob != NULL);
blob = g_blob;
spdk_blob_resize(blob, 32, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
memset(payload_write, 0xE5, sizeof(payload_write));
spdk_blob_io_write(blob, channel, payload_write, 4, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
memset(payload_read, 0x00, sizeof(payload_read));
spdk_blob_io_read(blob, channel, payload_read, 4, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_write, payload_read, 4 * 4096) == 0);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_free_io_channel(channel);
poll_threads();
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
blob_rw_verify_iov(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob;
struct spdk_io_channel *channel;
spdk_blob_id blobid;
uint8_t payload_read[10 * 4096];
uint8_t payload_write[10 * 4096];
struct iovec iov_read[3];
struct iovec iov_write[3];
void *buf;
dev = init_dev();
memset(g_dev_buffer, 0, DEV_BUFFER_SIZE);
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
channel = spdk_bs_alloc_io_channel(bs);
CU_ASSERT(channel != NULL);
spdk_bs_create_blob(bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
spdk_blob_resize(blob, 2, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/*
* Manually adjust the offset of the blob's second cluster. This allows
* us to make sure that the readv/write code correctly accounts for I/O
* that cross cluster boundaries. Start by asserting that the allocated
* clusters are where we expect before modifying the second cluster.
*/
CU_ASSERT(blob->active.clusters[0] == 1 * 256);
CU_ASSERT(blob->active.clusters[1] == 2 * 256);
blob->active.clusters[1] = 3 * 256;
memset(payload_write, 0xE5, sizeof(payload_write));
iov_write[0].iov_base = payload_write;
iov_write[0].iov_len = 1 * 4096;
iov_write[1].iov_base = payload_write + 1 * 4096;
iov_write[1].iov_len = 5 * 4096;
iov_write[2].iov_base = payload_write + 6 * 4096;
iov_write[2].iov_len = 4 * 4096;
/*
* Choose a page offset just before the cluster boundary. The first 6 pages of payload
* will get written to the first cluster, the last 4 to the second cluster.
*/
spdk_blob_io_writev(blob, channel, iov_write, 3, 250, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
memset(payload_read, 0xAA, sizeof(payload_read));
iov_read[0].iov_base = payload_read;
iov_read[0].iov_len = 3 * 4096;
iov_read[1].iov_base = payload_read + 3 * 4096;
iov_read[1].iov_len = 4 * 4096;
iov_read[2].iov_base = payload_read + 7 * 4096;
iov_read[2].iov_len = 3 * 4096;
spdk_blob_io_readv(blob, channel, iov_read, 3, 250, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_write, payload_read, 10 * 4096) == 0);
buf = calloc(1, 256 * 4096);
SPDK_CU_ASSERT_FATAL(buf != NULL);
/* Check that cluster 2 on "disk" was not modified. */
CU_ASSERT(memcmp(buf, &g_dev_buffer[512 * 4096], 256 * 4096) == 0);
free(buf);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_free_io_channel(channel);
poll_threads();
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static uint32_t
bs_channel_get_req_count(struct spdk_io_channel *_channel)
{
struct spdk_bs_channel *channel = spdk_io_channel_get_ctx(_channel);
struct spdk_bs_request_set *set;
uint32_t count = 0;
TAILQ_FOREACH(set, &channel->reqs, link) {
count++;
}
return count;
}
static void
blob_rw_verify_iov_nomem(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob;
struct spdk_io_channel *channel;
spdk_blob_id blobid;
uint8_t payload_write[10 * 4096];
struct iovec iov_write[3];
uint32_t req_count;
dev = init_dev();
memset(g_dev_buffer, 0, DEV_BUFFER_SIZE);
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
channel = spdk_bs_alloc_io_channel(bs);
CU_ASSERT(channel != NULL);
spdk_bs_create_blob(bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blob != NULL);
blob = g_blob;
spdk_blob_resize(blob, 2, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/*
* Choose a page offset just before the cluster boundary. The first 6 pages of payload
* will get written to the first cluster, the last 4 to the second cluster.
*/
iov_write[0].iov_base = payload_write;
iov_write[0].iov_len = 1 * 4096;
iov_write[1].iov_base = payload_write + 1 * 4096;
iov_write[1].iov_len = 5 * 4096;
iov_write[2].iov_base = payload_write + 6 * 4096;
iov_write[2].iov_len = 4 * 4096;
MOCK_SET(calloc, NULL);
req_count = bs_channel_get_req_count(channel);
spdk_blob_io_writev(blob, channel, iov_write, 3, 250, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno = -ENOMEM);
CU_ASSERT(req_count == bs_channel_get_req_count(channel));
MOCK_CLEAR(calloc);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_free_io_channel(channel);
poll_threads();
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
blob_rw_iov_read_only(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob;
struct spdk_io_channel *channel;
spdk_blob_id blobid;
uint8_t payload_read[4096];
uint8_t payload_write[4096];
struct iovec iov_read;
struct iovec iov_write;
dev = init_dev();
memset(g_dev_buffer, 0, DEV_BUFFER_SIZE);
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
channel = spdk_bs_alloc_io_channel(bs);
CU_ASSERT(channel != NULL);
spdk_bs_create_blob(bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
spdk_blob_resize(blob, 2, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Verify that writev failed if read_only flag is set. */
blob->data_ro = true;
iov_write.iov_base = payload_write;
iov_write.iov_len = sizeof(payload_write);
spdk_blob_io_writev(blob, channel, &iov_write, 1, 0, 1, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -EPERM);
/* Verify that reads pass if data_ro flag is set. */
iov_read.iov_base = payload_read;
iov_read.iov_len = sizeof(payload_read);
spdk_blob_io_readv(blob, channel, &iov_read, 1, 0, 1, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_free_io_channel(channel);
poll_threads();
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
_blob_io_read_no_split(struct spdk_blob *blob, struct spdk_io_channel *channel,
uint8_t *payload, uint64_t offset, uint64_t length,
spdk_blob_op_complete cb_fn, void *cb_arg)
{
uint64_t i;
uint8_t *buf;
uint64_t page_size = spdk_bs_get_page_size(blob->bs);
/* To be sure that operation is NOT splitted, read one page at the time */
buf = payload;
for (i = 0; i < length; i++) {
spdk_blob_io_read(blob, channel, buf, i + offset, 1, blob_op_complete, NULL);
poll_threads();
if (g_bserrno != 0) {
/* Pass the error code up */
break;
}
buf += page_size;
}
cb_fn(cb_arg, g_bserrno);
}
static void
_blob_io_write_no_split(struct spdk_blob *blob, struct spdk_io_channel *channel,
uint8_t *payload, uint64_t offset, uint64_t length,
spdk_blob_op_complete cb_fn, void *cb_arg)
{
uint64_t i;
uint8_t *buf;
uint64_t page_size = spdk_bs_get_page_size(blob->bs);
/* To be sure that operation is NOT splitted, write one page at the time */
buf = payload;
for (i = 0; i < length; i++) {
spdk_blob_io_write(blob, channel, buf, i + offset, 1, blob_op_complete, NULL);
poll_threads();
if (g_bserrno != 0) {
/* Pass the error code up */
break;
}
buf += page_size;
}
cb_fn(cb_arg, g_bserrno);
}
static void
blob_operation_split_rw(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob;
struct spdk_io_channel *channel;
struct spdk_blob_opts opts;
spdk_blob_id blobid;
uint64_t cluster_size;
uint64_t payload_size;
uint8_t *payload_read;
uint8_t *payload_write;
uint8_t *payload_pattern;
uint64_t page_size;
uint64_t pages_per_cluster;
uint64_t pages_per_payload;
uint64_t i;
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
cluster_size = spdk_bs_get_cluster_size(bs);
page_size = spdk_bs_get_page_size(bs);
pages_per_cluster = cluster_size / page_size;
pages_per_payload = pages_per_cluster * 5;
payload_size = cluster_size * 5;
payload_read = malloc(payload_size);
SPDK_CU_ASSERT_FATAL(payload_read != NULL);
payload_write = malloc(payload_size);
SPDK_CU_ASSERT_FATAL(payload_write != NULL);
payload_pattern = malloc(payload_size);
SPDK_CU_ASSERT_FATAL(payload_pattern != NULL);
/* Prepare random pattern to write */
memset(payload_pattern, 0xFF, payload_size);
for (i = 0; i < pages_per_payload; i++) {
*((uint64_t *)(payload_pattern + page_size * i)) = (i + 1);
}
channel = spdk_bs_alloc_io_channel(bs);
SPDK_CU_ASSERT_FATAL(channel != NULL);
/* Create blob */
spdk_blob_opts_init(&opts);
opts.thin_provision = false;
opts.num_clusters = 5;
spdk_bs_create_blob_ext(bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
CU_ASSERT(spdk_blob_get_num_clusters(blob) == 5);
/* Initial read should return zeroed payload */
memset(payload_read, 0xFF, payload_size);
spdk_blob_io_read(blob, channel, payload_read, 0, pages_per_payload, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(spdk_mem_all_zero(payload_read, payload_size));
/* Fill whole blob except last page */
spdk_blob_io_write(blob, channel, payload_pattern, 0, pages_per_payload - 1,
blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Write last page with a pattern */
spdk_blob_io_write(blob, channel, payload_pattern, pages_per_payload - 1, 1,
blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Read whole blob and check consistency */
memset(payload_read, 0xFF, payload_size);
spdk_blob_io_read(blob, channel, payload_read, 0, pages_per_payload, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_pattern, payload_read, payload_size - page_size) == 0);
CU_ASSERT(memcmp(payload_pattern, payload_read + payload_size - page_size, page_size) == 0);
/* Fill whole blob except first page */
spdk_blob_io_write(blob, channel, payload_pattern, 1, pages_per_payload - 1,
blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Write first page with a pattern */
spdk_blob_io_write(blob, channel, payload_pattern, 0, 1,
blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Read whole blob and check consistency */
memset(payload_read, 0xFF, payload_size);
spdk_blob_io_read(blob, channel, payload_read, 0, pages_per_payload, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_pattern, payload_read + page_size, payload_size - page_size) == 0);
CU_ASSERT(memcmp(payload_pattern, payload_read, page_size) == 0);
/* Fill whole blob with a pattern (5 clusters) */
/* 1. Read test. */
_blob_io_write_no_split(blob, channel, payload_pattern, 0, pages_per_payload,
blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
memset(payload_read, 0xFF, payload_size);
spdk_blob_io_read(blob, channel, payload_read, 0, pages_per_payload, blob_op_complete, NULL);
poll_threads();
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_pattern, payload_read, payload_size) == 0);
/* 2. Write test. */
spdk_blob_io_write(blob, channel, payload_pattern, 0, pages_per_payload,
blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
memset(payload_read, 0xFF, payload_size);
_blob_io_read_no_split(blob, channel, payload_read, 0, pages_per_payload, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_pattern, payload_read, payload_size) == 0);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_free_io_channel(channel);
poll_threads();
/* Unload the blob store */
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
g_blob = NULL;
g_blobid = 0;
free(payload_read);
free(payload_write);
free(payload_pattern);
}
static void
blob_operation_split_rw_iov(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob;
struct spdk_io_channel *channel;
struct spdk_blob_opts opts;
spdk_blob_id blobid;
uint64_t cluster_size;
uint64_t payload_size;
uint8_t *payload_read;
uint8_t *payload_write;
uint8_t *payload_pattern;
uint64_t page_size;
uint64_t pages_per_cluster;
uint64_t pages_per_payload;
struct iovec iov_read[2];
struct iovec iov_write[2];
uint64_t i, j;
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
cluster_size = spdk_bs_get_cluster_size(bs);
page_size = spdk_bs_get_page_size(bs);
pages_per_cluster = cluster_size / page_size;
pages_per_payload = pages_per_cluster * 5;
payload_size = cluster_size * 5;
payload_read = malloc(payload_size);
SPDK_CU_ASSERT_FATAL(payload_read != NULL);
payload_write = malloc(payload_size);
SPDK_CU_ASSERT_FATAL(payload_write != NULL);
payload_pattern = malloc(payload_size);
SPDK_CU_ASSERT_FATAL(payload_pattern != NULL);
/* Prepare random pattern to write */
for (i = 0; i < pages_per_payload; i++) {
for (j = 0; j < page_size / sizeof(uint64_t); j++) {
uint64_t *tmp;
tmp = (uint64_t *)payload_pattern;
tmp += ((page_size * i) / sizeof(uint64_t)) + j;
*tmp = i + 1;
}
}
channel = spdk_bs_alloc_io_channel(bs);
SPDK_CU_ASSERT_FATAL(channel != NULL);
/* Create blob */
spdk_blob_opts_init(&opts);
opts.thin_provision = false;
opts.num_clusters = 5;
spdk_bs_create_blob_ext(bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
CU_ASSERT(spdk_blob_get_num_clusters(blob) == 5);
/* Initial read should return zeroes payload */
memset(payload_read, 0xFF, payload_size);
iov_read[0].iov_base = payload_read;
iov_read[0].iov_len = cluster_size * 3;
iov_read[1].iov_base = payload_read + cluster_size * 3;
iov_read[1].iov_len = cluster_size * 2;
spdk_blob_io_readv(blob, channel, iov_read, 2, 0, pages_per_payload, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(spdk_mem_all_zero(payload_read, payload_size));
/* First of iovs fills whole blob except last page and second of iovs writes last page
* with a pattern. */
iov_write[0].iov_base = payload_pattern;
iov_write[0].iov_len = payload_size - page_size;
iov_write[1].iov_base = payload_pattern;
iov_write[1].iov_len = page_size;
spdk_blob_io_writev(blob, channel, iov_write, 2, 0, pages_per_payload, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Read whole blob and check consistency */
memset(payload_read, 0xFF, payload_size);
iov_read[0].iov_base = payload_read;
iov_read[0].iov_len = cluster_size * 2;
iov_read[1].iov_base = payload_read + cluster_size * 2;
iov_read[1].iov_len = cluster_size * 3;
spdk_blob_io_readv(blob, channel, iov_read, 2, 0, pages_per_payload, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_pattern, payload_read, payload_size - page_size) == 0);
CU_ASSERT(memcmp(payload_pattern, payload_read + payload_size - page_size, page_size) == 0);
/* First of iovs fills only first page and second of iovs writes whole blob except
* first page with a pattern. */
iov_write[0].iov_base = payload_pattern;
iov_write[0].iov_len = page_size;
iov_write[1].iov_base = payload_pattern;
iov_write[1].iov_len = payload_size - page_size;
spdk_blob_io_writev(blob, channel, iov_write, 2, 0, pages_per_payload, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Read whole blob and check consistency */
memset(payload_read, 0xFF, payload_size);
iov_read[0].iov_base = payload_read;
iov_read[0].iov_len = cluster_size * 4;
iov_read[1].iov_base = payload_read + cluster_size * 4;
iov_read[1].iov_len = cluster_size;
spdk_blob_io_readv(blob, channel, iov_read, 2, 0, pages_per_payload, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_pattern, payload_read + page_size, payload_size - page_size) == 0);
CU_ASSERT(memcmp(payload_pattern, payload_read, page_size) == 0);
/* Fill whole blob with a pattern (5 clusters) */
/* 1. Read test. */
_blob_io_write_no_split(blob, channel, payload_pattern, 0, pages_per_payload,
blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
memset(payload_read, 0xFF, payload_size);
iov_read[0].iov_base = payload_read;
iov_read[0].iov_len = cluster_size;
iov_read[1].iov_base = payload_read + cluster_size;
iov_read[1].iov_len = cluster_size * 4;
spdk_blob_io_readv(blob, channel, iov_read, 2, 0, pages_per_payload, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_pattern, payload_read, payload_size) == 0);
/* 2. Write test. */
iov_write[0].iov_base = payload_read;
iov_write[0].iov_len = cluster_size * 2;
iov_write[1].iov_base = payload_read + cluster_size * 2;
iov_write[1].iov_len = cluster_size * 3;
spdk_blob_io_writev(blob, channel, iov_write, 2, 0, pages_per_payload, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
memset(payload_read, 0xFF, payload_size);
_blob_io_read_no_split(blob, channel, payload_read, 0, pages_per_payload, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_pattern, payload_read, payload_size) == 0);
spdk_blob_close(blob, blob_op_complete, NULL);
CU_ASSERT(g_bserrno == 0);
spdk_bs_free_io_channel(channel);
poll_threads();
/* Unload the blob store */
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
g_blob = NULL;
g_blobid = 0;
free(payload_read);
free(payload_write);
free(payload_pattern);
}
static void
blob_unmap(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob;
struct spdk_io_channel *channel;
spdk_blob_id blobid;
struct spdk_blob_opts opts;
uint8_t payload[4096];
int i;
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
channel = spdk_bs_alloc_io_channel(bs);
CU_ASSERT(channel != NULL);
spdk_blob_opts_init(&opts);
opts.num_clusters = 10;
spdk_bs_create_blob_ext(bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
spdk_blob_resize(blob, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
memset(payload, 0, sizeof(payload));
payload[0] = 0xFF;
/*
* Set first byte of every cluster to 0xFF.
* First cluster on device is reserved so let's start from cluster number 1
*/
for (i = 1; i < 11; i++) {
g_dev_buffer[i * SPDK_BLOB_OPTS_CLUSTER_SZ] = 0xFF;
}
/* Confirm writes */
for (i = 0; i < 10; i++) {
payload[0] = 0;
spdk_blob_io_read(blob, channel, &payload, i * SPDK_BLOB_OPTS_CLUSTER_SZ / 4096, 1,
blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(payload[0] == 0xFF);
}
/* Mark some clusters as unallocated */
blob->active.clusters[1] = 0;
blob->active.clusters[2] = 0;
blob->active.clusters[3] = 0;
blob->active.clusters[6] = 0;
blob->active.clusters[8] = 0;
/* Unmap clusters by resizing to 0 */
spdk_blob_resize(blob, 0, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_blob_sync_md(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Confirm that only 'allocated' clusters were unmapped */
for (i = 1; i < 11; i++) {
switch (i) {
case 2:
case 3:
case 4:
case 7:
case 9:
CU_ASSERT(g_dev_buffer[i * SPDK_BLOB_OPTS_CLUSTER_SZ] == 0xFF);
break;
default:
CU_ASSERT(g_dev_buffer[i * SPDK_BLOB_OPTS_CLUSTER_SZ] == 0);
break;
}
}
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_free_io_channel(channel);
poll_threads();
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
blob_iter(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob;
spdk_blob_id blobid;
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
spdk_bs_iter_first(bs, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_blob == NULL);
CU_ASSERT(g_bserrno == -ENOENT);
spdk_bs_create_blob(bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_iter_first(bs, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_blob != NULL);
CU_ASSERT(g_bserrno == 0);
blob = g_blob;
CU_ASSERT(spdk_blob_get_id(blob) == blobid);
spdk_bs_iter_next(bs, blob, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_blob == NULL);
CU_ASSERT(g_bserrno == -ENOENT);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
blob_xattr(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob;
spdk_blob_id blobid;
uint64_t length;
int rc;
const char *name1, *name2;
const void *value;
size_t value_len;
struct spdk_xattr_names *names;
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
spdk_bs_create_blob(bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
/* Test that set_xattr fails if md_ro flag is set. */
blob->md_ro = true;
rc = spdk_blob_set_xattr(blob, "name", "log.txt", strlen("log.txt") + 1);
CU_ASSERT(rc == -EPERM);
blob->md_ro = false;
rc = spdk_blob_set_xattr(blob, "name", "log.txt", strlen("log.txt") + 1);
CU_ASSERT(rc == 0);
length = 2345;
rc = spdk_blob_set_xattr(blob, "length", &length, sizeof(length));
CU_ASSERT(rc == 0);
/* Overwrite "length" xattr. */
length = 3456;
rc = spdk_blob_set_xattr(blob, "length", &length, sizeof(length));
CU_ASSERT(rc == 0);
/* get_xattr should still work even if md_ro flag is set. */
value = NULL;
blob->md_ro = true;
rc = spdk_blob_get_xattr_value(blob, "length", &value, &value_len);
CU_ASSERT(rc == 0);
SPDK_CU_ASSERT_FATAL(value != NULL);
CU_ASSERT(*(uint64_t *)value == length);
CU_ASSERT(value_len == 8);
blob->md_ro = false;
rc = spdk_blob_get_xattr_value(blob, "foobar", &value, &value_len);
CU_ASSERT(rc == -ENOENT);
names = NULL;
rc = spdk_blob_get_xattr_names(blob, &names);
CU_ASSERT(rc == 0);
SPDK_CU_ASSERT_FATAL(names != NULL);
CU_ASSERT(spdk_xattr_names_get_count(names) == 2);
name1 = spdk_xattr_names_get_name(names, 0);
SPDK_CU_ASSERT_FATAL(name1 != NULL);
CU_ASSERT(!strcmp(name1, "name") || !strcmp(name1, "length"));
name2 = spdk_xattr_names_get_name(names, 1);
SPDK_CU_ASSERT_FATAL(name2 != NULL);
CU_ASSERT(!strcmp(name2, "name") || !strcmp(name2, "length"));
CU_ASSERT(strcmp(name1, name2));
spdk_xattr_names_free(names);
/* Confirm that remove_xattr fails if md_ro is set to true. */
blob->md_ro = true;
rc = spdk_blob_remove_xattr(blob, "name");
CU_ASSERT(rc == -EPERM);
blob->md_ro = false;
rc = spdk_blob_remove_xattr(blob, "name");
CU_ASSERT(rc == 0);
rc = spdk_blob_remove_xattr(blob, "foobar");
CU_ASSERT(rc == -ENOENT);
/* Set internal xattr */
length = 7898;
rc = _spdk_blob_set_xattr(blob, "internal", &length, sizeof(length), true);
CU_ASSERT(rc == 0);
rc = _spdk_blob_get_xattr_value(blob, "internal", &value, &value_len, true);
CU_ASSERT(rc == 0);
CU_ASSERT(*(uint64_t *)value == length);
/* try to get public xattr with same name */
rc = spdk_blob_get_xattr_value(blob, "internal", &value, &value_len);
CU_ASSERT(rc != 0);
rc = _spdk_blob_get_xattr_value(blob, "internal", &value, &value_len, false);
CU_ASSERT(rc != 0);
/* Check if SPDK_BLOB_INTERNAL_XATTR is set */
CU_ASSERT((blob->invalid_flags & SPDK_BLOB_INTERNAL_XATTR) ==
SPDK_BLOB_INTERNAL_XATTR);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
/* Check if xattrs are persisted */
dev = init_dev();
spdk_bs_load(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
rc = _spdk_blob_get_xattr_value(blob, "internal", &value, &value_len, true);
CU_ASSERT(rc == 0);
CU_ASSERT(*(uint64_t *)value == length);
/* try to get internal xattr trough public call */
rc = spdk_blob_get_xattr_value(blob, "internal", &value, &value_len);
CU_ASSERT(rc != 0);
rc = _spdk_blob_remove_xattr(blob, "internal", true);
CU_ASSERT(rc == 0);
CU_ASSERT((blob->invalid_flags & SPDK_BLOB_INTERNAL_XATTR) == 0);
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
bs_load(void)
{
struct spdk_bs_dev *dev;
spdk_blob_id blobid;
struct spdk_blob *blob;
struct spdk_bs_super_block *super_block;
uint64_t length;
int rc;
const void *value;
size_t value_len;
struct spdk_bs_opts opts;
dev = init_dev();
spdk_bs_opts_init(&opts);
snprintf(opts.bstype.bstype, sizeof(opts.bstype.bstype), "TESTTYPE");
/* Initialize a new blob store */
spdk_bs_init(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
/* Try to open a blobid that does not exist */
spdk_bs_open_blob(g_bs, 0, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -ENOENT);
CU_ASSERT(g_blob == NULL);
/* Create a blob */
spdk_bs_create_blob(g_bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(g_bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blob != NULL);
blob = g_blob;
/* Try again to open valid blob but without the upper bit set */
spdk_bs_open_blob(g_bs, blobid & 0xFFFFFFFF, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -ENOENT);
CU_ASSERT(g_blob == NULL);
/* Set some xattrs */
rc = spdk_blob_set_xattr(blob, "name", "log.txt", strlen("log.txt") + 1);
CU_ASSERT(rc == 0);
length = 2345;
rc = spdk_blob_set_xattr(blob, "length", &length, sizeof(length));
CU_ASSERT(rc == 0);
/* Resize the blob */
spdk_blob_resize(blob, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
blob = NULL;
g_blob = NULL;
g_blobid = SPDK_BLOBID_INVALID;
/* Unload the blob store */
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
g_blob = NULL;
g_blobid = 0;
super_block = (struct spdk_bs_super_block *)g_dev_buffer;
CU_ASSERT(super_block->clean == 1);
/* Load should fail for device with an unsupported blocklen */
dev = init_dev();
dev->blocklen = SPDK_BS_PAGE_SIZE * 2;
spdk_bs_load(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -EINVAL);
/* Load should when max_md_ops is set to zero */
dev = init_dev();
spdk_bs_opts_init(&opts);
opts.max_md_ops = 0;
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -EINVAL);
/* Load should when max_channel_ops is set to zero */
dev = init_dev();
spdk_bs_opts_init(&opts);
opts.max_channel_ops = 0;
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -EINVAL);
/* Load an existing blob store */
dev = init_dev();
spdk_bs_opts_init(&opts);
snprintf(opts.bstype.bstype, sizeof(opts.bstype.bstype), "TESTTYPE");
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
super_block = (struct spdk_bs_super_block *)g_dev_buffer;
CU_ASSERT(super_block->clean == 1);
CU_ASSERT(super_block->size == dev->blockcnt * dev->blocklen);
spdk_bs_open_blob(g_bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blob != NULL);
blob = g_blob;
/* Verify that blobstore is marked dirty after first metadata sync */
spdk_blob_sync_md(blob, blob_op_complete, NULL);
CU_ASSERT(super_block->clean == 1);
/* Get the xattrs */
value = NULL;
rc = spdk_blob_get_xattr_value(blob, "length", &value, &value_len);
CU_ASSERT(rc == 0);
SPDK_CU_ASSERT_FATAL(value != NULL);
CU_ASSERT(*(uint64_t *)value == length);
CU_ASSERT(value_len == 8);
rc = spdk_blob_get_xattr_value(blob, "foobar", &value, &value_len);
CU_ASSERT(rc == -ENOENT);
CU_ASSERT(spdk_blob_get_num_clusters(blob) == 10);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
blob = NULL;
g_blob = NULL;
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
/* Load should fail: bdev size < saved size */
dev = init_dev();
dev->blockcnt /= 2;
spdk_bs_opts_init(&opts);
snprintf(opts.bstype.bstype, sizeof(opts.bstype.bstype), "TESTTYPE");
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -EILSEQ);
/* Load should succeed: bdev size > saved size */
dev = init_dev();
dev->blockcnt *= 4;
spdk_bs_opts_init(&opts);
snprintf(opts.bstype.bstype, sizeof(opts.bstype.bstype), "TESTTYPE");
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
/* Test compatibility mode */
dev = init_dev();
super_block->size = 0;
super_block->crc = _spdk_blob_md_page_calc_crc(super_block);
spdk_bs_opts_init(&opts);
snprintf(opts.bstype.bstype, sizeof(opts.bstype.bstype), "TESTTYPE");
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
/* Create a blob */
spdk_bs_create_blob(g_bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
/* Blobstore should update number of blocks in super_block */
CU_ASSERT(super_block->size == dev->blockcnt * dev->blocklen);
CU_ASSERT(super_block->clean == 0);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(super_block->clean == 1);
g_bs = NULL;
}
static void
bs_load_pending_removal(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob_opts opts;
struct spdk_blob *blob, *snapshot;
spdk_blob_id blobid, snapshotid;
const void *value;
size_t value_len;
int rc;
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
/* Create blob */
spdk_blob_opts_init(&opts);
opts.num_clusters = 10;
spdk_bs_create_blob_ext(bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
/* Create snapshot */
spdk_bs_create_snapshot(bs, blobid, NULL, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
snapshotid = g_blobid;
spdk_bs_open_blob(bs, snapshotid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
snapshot = g_blob;
/* Set SNAPSHOT_PENDING_REMOVAL xattr */
snapshot->md_ro = false;
rc = _spdk_blob_set_xattr(snapshot, SNAPSHOT_PENDING_REMOVAL, &blobid, sizeof(spdk_blob_id), true);
CU_ASSERT(rc == 0);
snapshot->md_ro = true;
spdk_blob_close(snapshot, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Reload blobstore */
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
dev = init_dev();
spdk_bs_load(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
/* Snapshot should not be removed as blob is still pointing to it */
spdk_bs_open_blob(bs, snapshotid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
snapshot = g_blob;
/* SNAPSHOT_PENDING_REMOVAL xattr should be removed during load */
rc = spdk_blob_get_xattr_value(snapshot, SNAPSHOT_PENDING_REMOVAL, &value, &value_len);
CU_ASSERT(rc != 0);
/* Set SNAPSHOT_PENDING_REMOVAL xattr again */
snapshot->md_ro = false;
rc = _spdk_blob_set_xattr(snapshot, SNAPSHOT_PENDING_REMOVAL, &blobid, sizeof(spdk_blob_id), true);
CU_ASSERT(rc == 0);
snapshot->md_ro = true;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
/* Remove parent_id from blob by removing BLOB_SNAPSHOT xattr */
_spdk_blob_remove_xattr(blob, BLOB_SNAPSHOT, true);
spdk_blob_sync_md(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_blob_close(snapshot, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Reload blobstore */
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
dev = init_dev();
spdk_bs_load(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
/* Snapshot should be removed as blob is not pointing to it anymore */
spdk_bs_open_blob(bs, snapshotid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno != 0);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
bs_load_custom_cluster_size(void)
{
struct spdk_bs_dev *dev;
struct spdk_bs_super_block *super_block;
struct spdk_bs_opts opts;
uint32_t custom_cluster_size = 4194304; /* 4MiB */
uint32_t cluster_sz;
uint64_t total_clusters;
dev = init_dev();
spdk_bs_opts_init(&opts);
opts.cluster_sz = custom_cluster_size;
snprintf(opts.bstype.bstype, sizeof(opts.bstype.bstype), "TESTTYPE");
/* Initialize a new blob store */
spdk_bs_init(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
cluster_sz = g_bs->cluster_sz;
total_clusters = g_bs->total_clusters;
/* Unload the blob store */
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
g_blob = NULL;
g_blobid = 0;
super_block = (struct spdk_bs_super_block *)g_dev_buffer;
CU_ASSERT(super_block->clean == 1);
/* Load an existing blob store */
dev = init_dev();
spdk_bs_opts_init(&opts);
snprintf(opts.bstype.bstype, sizeof(opts.bstype.bstype), "TESTTYPE");
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
/* Compare cluster size and number to one after initialization */
CU_ASSERT(cluster_sz == g_bs->cluster_sz);
CU_ASSERT(total_clusters == g_bs->total_clusters);
super_block = (struct spdk_bs_super_block *)g_dev_buffer;
CU_ASSERT(super_block->clean == 1);
CU_ASSERT(super_block->size == dev->blockcnt * dev->blocklen);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(super_block->clean == 1);
g_bs = NULL;
}
static void
bs_type(void)
{
struct spdk_bs_dev *dev;
struct spdk_bs_opts opts;
dev = init_dev();
spdk_bs_opts_init(&opts);
snprintf(opts.bstype.bstype, sizeof(opts.bstype.bstype), "TESTTYPE");
/* Initialize a new blob store */
spdk_bs_init(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
/* Unload the blob store */
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
g_blob = NULL;
g_blobid = 0;
/* Load non existing blobstore type */
dev = init_dev();
snprintf(opts.bstype.bstype, sizeof(opts.bstype.bstype), "NONEXISTING");
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno != 0);
/* Load with empty blobstore type */
dev = init_dev();
memset(opts.bstype.bstype, 0, sizeof(opts.bstype.bstype));
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
/* Initialize a new blob store with empty bstype */
dev = init_dev();
memset(opts.bstype.bstype, 0, sizeof(opts.bstype.bstype));
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
/* Load non existing blobstore type */
dev = init_dev();
snprintf(opts.bstype.bstype, sizeof(opts.bstype.bstype), "NONEXISTING");
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno != 0);
/* Load with empty blobstore type */
dev = init_dev();
memset(opts.bstype.bstype, 0, sizeof(opts.bstype.bstype));
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
bs_super_block(void)
{
struct spdk_bs_dev *dev;
struct spdk_bs_super_block *super_block;
struct spdk_bs_opts opts;
struct spdk_bs_super_block_ver1 super_block_v1;
dev = init_dev();
spdk_bs_opts_init(&opts);
snprintf(opts.bstype.bstype, sizeof(opts.bstype.bstype), "TESTTYPE");
/* Initialize a new blob store */
spdk_bs_init(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
/* Unload the blob store */
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
g_blob = NULL;
g_blobid = 0;
/* Load an existing blob store with version newer than supported */
super_block = (struct spdk_bs_super_block *)g_dev_buffer;
super_block->version++;
dev = init_dev();
memset(opts.bstype.bstype, 0, sizeof(opts.bstype.bstype));
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno != 0);
/* Create a new blob store with super block version 1 */
dev = init_dev();
super_block_v1.version = 1;
memcpy(super_block_v1.signature, "SPDKBLOB", sizeof(super_block_v1.signature));
super_block_v1.length = 0x1000;
super_block_v1.clean = 1;
super_block_v1.super_blob = 0xFFFFFFFFFFFFFFFF;
super_block_v1.cluster_size = 0x100000;
super_block_v1.used_page_mask_start = 0x01;
super_block_v1.used_page_mask_len = 0x01;
super_block_v1.used_cluster_mask_start = 0x02;
super_block_v1.used_cluster_mask_len = 0x01;
super_block_v1.md_start = 0x03;
super_block_v1.md_len = 0x40;
memset(super_block_v1.reserved, 0, 4036);
super_block_v1.crc = _spdk_blob_md_page_calc_crc(&super_block_v1);
memcpy(g_dev_buffer, &super_block_v1, sizeof(struct spdk_bs_super_block_ver1));
memset(opts.bstype.bstype, 0, sizeof(opts.bstype.bstype));
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
/*
* Create a blobstore and then unload it.
*/
static void
bs_unload(void)
{
struct spdk_bs_dev *dev;
struct spdk_blob_store *bs;
spdk_blob_id blobid;
struct spdk_blob *blob;
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
/* Create a blob and open it. */
g_bserrno = -1;
spdk_bs_create_blob(bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid > 0);
blobid = g_blobid;
g_bserrno = -1;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blob != NULL);
blob = g_blob;
/* Try to unload blobstore, should fail with open blob */
g_bserrno = -1;
spdk_bs_unload(bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -EBUSY);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
/* Close the blob, then successfully unload blobstore */
g_bserrno = -1;
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bserrno = -1;
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
/*
* Create a blobstore with a cluster size different than the default, and ensure it is
* persisted.
*/
static void
bs_cluster_sz(void)
{
struct spdk_bs_dev *dev;
struct spdk_bs_opts opts;
uint32_t cluster_sz;
/* Set cluster size to zero */
dev = init_dev();
spdk_bs_opts_init(&opts);
opts.cluster_sz = 0;
/* Initialize a new blob store */
spdk_bs_init(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -EINVAL);
SPDK_CU_ASSERT_FATAL(g_bs == NULL);
/*
* Set cluster size to blobstore page size,
* to work it is required to be at least twice the blobstore page size.
*/
dev = init_dev();
spdk_bs_opts_init(&opts);
opts.cluster_sz = SPDK_BS_PAGE_SIZE;
/* Initialize a new blob store */
spdk_bs_init(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -ENOMEM);
SPDK_CU_ASSERT_FATAL(g_bs == NULL);
/*
* Set cluster size to lower than page size,
* to work it is required to be at least twice the blobstore page size.
*/
dev = init_dev();
spdk_bs_opts_init(&opts);
opts.cluster_sz = SPDK_BS_PAGE_SIZE - 1;
/* Initialize a new blob store */
spdk_bs_init(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -EINVAL);
SPDK_CU_ASSERT_FATAL(g_bs == NULL);
/* Set cluster size to twice the default */
dev = init_dev();
spdk_bs_opts_init(&opts);
opts.cluster_sz *= 2;
cluster_sz = opts.cluster_sz;
/* Initialize a new blob store */
spdk_bs_init(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
CU_ASSERT(spdk_bs_get_cluster_size(g_bs) == cluster_sz);
/* Unload the blob store */
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
g_blob = NULL;
g_blobid = 0;
dev = init_dev();
/* Load an existing blob store */
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
CU_ASSERT(spdk_bs_get_cluster_size(g_bs) == cluster_sz);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
/*
* Create a blobstore, reload it and ensure total usable cluster count
* stays the same.
*/
static void
bs_usable_clusters(void)
{
struct spdk_bs_dev *dev;
struct spdk_bs_opts opts;
uint32_t clusters;
int i;
/* Init blobstore */
dev = init_dev();
spdk_bs_opts_init(&opts);
spdk_bs_init(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
clusters = spdk_bs_total_data_cluster_count(g_bs);
/* Unload the blob store */
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
dev = init_dev();
/* Load an existing blob store */
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
CU_ASSERT(spdk_bs_total_data_cluster_count(g_bs) == clusters);
/* Create and resize blobs to make sure that useable cluster count won't change */
for (i = 0; i < 4; i++) {
g_bserrno = -1;
g_blobid = SPDK_BLOBID_INVALID;
spdk_bs_create_blob(g_bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
g_bserrno = -1;
g_blob = NULL;
spdk_bs_open_blob(g_bs, g_blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blob != NULL);
spdk_blob_resize(g_blob, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bserrno = -1;
spdk_blob_close(g_blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(spdk_bs_total_data_cluster_count(g_bs) == clusters);
}
/* Reload the blob store to make sure that nothing changed */
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
dev = init_dev();
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
CU_ASSERT(spdk_bs_total_data_cluster_count(g_bs) == clusters);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
/*
* Test resizing of the metadata blob. This requires creating enough blobs
* so that one cluster is not enough to fit the metadata for those blobs.
* To induce this condition to happen more quickly, we reduce the cluster
* size to 16KB, which means only 4 4KB blob metadata pages can fit.
*/
static void
bs_resize_md(void)
{
const int CLUSTER_PAGE_COUNT = 4;
const int NUM_BLOBS = CLUSTER_PAGE_COUNT * 4;
struct spdk_bs_dev *dev;
struct spdk_bs_opts opts;
uint32_t cluster_sz;
spdk_blob_id blobids[NUM_BLOBS];
int i;
dev = init_dev();
spdk_bs_opts_init(&opts);
opts.cluster_sz = CLUSTER_PAGE_COUNT * 4096;
cluster_sz = opts.cluster_sz;
/* Initialize a new blob store */
spdk_bs_init(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
CU_ASSERT(spdk_bs_get_cluster_size(g_bs) == cluster_sz);
for (i = 0; i < NUM_BLOBS; i++) {
g_bserrno = -1;
g_blobid = SPDK_BLOBID_INVALID;
spdk_bs_create_blob(g_bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobids[i] = g_blobid;
}
/* Unload the blob store */
g_bserrno = -1;
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Load an existing blob store */
g_bserrno = -1;
g_bs = NULL;
dev = init_dev();
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
CU_ASSERT(spdk_bs_get_cluster_size(g_bs) == cluster_sz);
for (i = 0; i < NUM_BLOBS; i++) {
g_bserrno = -1;
g_blob = NULL;
spdk_bs_open_blob(g_bs, blobids[i], blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blob != NULL);
g_bserrno = -1;
spdk_blob_close(g_blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
}
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
bs_destroy(void)
{
struct spdk_bs_dev *dev;
struct spdk_bs_opts opts;
/* Initialize a new blob store */
dev = init_dev();
spdk_bs_opts_init(&opts);
spdk_bs_init(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
/* Destroy the blob store */
g_bserrno = -1;
spdk_bs_destroy(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Loading an non-existent blob store should fail. */
g_bs = NULL;
dev = init_dev();
g_bserrno = 0;
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno != 0);
}
/* Try to hit all of the corner cases associated with serializing
* a blob to disk
*/
static void
blob_serialize(void)
{
struct spdk_bs_dev *dev;
struct spdk_bs_opts opts;
struct spdk_blob_store *bs;
spdk_blob_id blobid[2];
struct spdk_blob *blob[2];
uint64_t i;
char *value;
int rc;
dev = init_dev();
/* Initialize a new blobstore with very small clusters */
spdk_bs_opts_init(&opts);
opts.cluster_sz = dev->blocklen * 8;
spdk_bs_init(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
/* Create and open two blobs */
for (i = 0; i < 2; i++) {
spdk_bs_create_blob(bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid[i] = g_blobid;
/* Open a blob */
spdk_bs_open_blob(bs, blobid[i], blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blob != NULL);
blob[i] = g_blob;
/* Set a fairly large xattr on both blobs to eat up
* metadata space
*/
value = calloc(dev->blocklen - 64, sizeof(char));
SPDK_CU_ASSERT_FATAL(value != NULL);
memset(value, i, dev->blocklen / 2);
rc = spdk_blob_set_xattr(blob[i], "name", value, dev->blocklen - 64);
CU_ASSERT(rc == 0);
free(value);
}
/* Resize the blobs, alternating 1 cluster at a time.
* This thwarts run length encoding and will cause spill
* over of the extents.
*/
for (i = 0; i < 6; i++) {
spdk_blob_resize(blob[i % 2], (i / 2) + 1, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
}
for (i = 0; i < 2; i++) {
spdk_blob_sync_md(blob[i], blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
}
/* Close the blobs */
for (i = 0; i < 2; i++) {
spdk_blob_close(blob[i], blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
}
/* Unload the blobstore */
spdk_bs_unload(bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
g_blob = NULL;
g_blobid = 0;
bs = NULL;
dev = init_dev();
/* Load an existing blob store */
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
for (i = 0; i < 2; i++) {
blob[i] = NULL;
spdk_bs_open_blob(bs, blobid[i], blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blob != NULL);
blob[i] = g_blob;
CU_ASSERT(spdk_blob_get_num_clusters(blob[i]) == 3);
spdk_blob_close(blob[i], blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
}
spdk_bs_unload(bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
blob_crc(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob;
spdk_blob_id blobid;
uint32_t page_num;
int index;
struct spdk_blob_md_page *page;
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
spdk_bs_create_blob(bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blob != NULL);
blob = g_blob;
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
page_num = _spdk_bs_blobid_to_page(blobid);
index = DEV_BUFFER_BLOCKLEN * (bs->md_start + page_num);
page = (struct spdk_blob_md_page *)&g_dev_buffer[index];
page->crc = 0;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -EINVAL);
CU_ASSERT(g_blob == NULL);
g_bserrno = 0;
spdk_bs_delete_blob(bs, blobid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -EINVAL);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
super_block_crc(void)
{
struct spdk_bs_dev *dev;
struct spdk_bs_super_block *super_block;
struct spdk_bs_opts opts;
dev = init_dev();
spdk_bs_opts_init(&opts);
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
super_block = (struct spdk_bs_super_block *)g_dev_buffer;
super_block->crc = 0;
dev = init_dev();
/* Load an existing blob store */
g_bserrno = 0;
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -EILSEQ);
}
/* For blob dirty shutdown test case we do the following sub-test cases:
* 1 Initialize new blob store and create 1 super blob with some xattrs, then we
* dirty shutdown and reload the blob store and verify the xattrs.
* 2 Resize the blob from 10 clusters to 20 clusters and then dirty shutdown,
* reload the blob store and verify the clusters number.
* 3 Create the second blob and then dirty shutdown, reload the blob store
* and verify the second blob.
* 4 Delete the second blob and then dirty shutdown, reload the blob store
* and verify the second blob is invalid.
* 5 Create the second blob again and also create the third blob, modify the
* md of second blob which makes the md invalid, and then dirty shutdown,
* reload the blob store verify the second blob, it should invalid and also
* verify the third blob, it should correct.
*/
static void
blob_dirty_shutdown(void)
{
int rc;
int index;
struct spdk_bs_dev *dev;
spdk_blob_id blobid1, blobid2, blobid3;
struct spdk_blob *blob;
uint64_t length;
uint64_t free_clusters;
const void *value;
size_t value_len;
uint32_t page_num;
struct spdk_blob_md_page *page;
struct spdk_bs_opts opts;
dev = init_dev();
spdk_bs_opts_init(&opts);
/* Initialize a new blob store */
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
/* Create first blob */
spdk_bs_create_blob(g_bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid1 = g_blobid;
spdk_bs_open_blob(g_bs, blobid1, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blob != NULL);
blob = g_blob;
/* Set some xattrs */
rc = spdk_blob_set_xattr(blob, "name", "log.txt", strlen("log.txt") + 1);
CU_ASSERT(rc == 0);
length = 2345;
rc = spdk_blob_set_xattr(blob, "length", &length, sizeof(length));
CU_ASSERT(rc == 0);
/* Put xattr that fits exactly single page.
* This results in adding additional pages to MD.
* First is flags and smaller xattr, second the large xattr,
* third are just the extents.
*/
size_t xattr_length = 4072 - sizeof(struct spdk_blob_md_descriptor_xattr) -
strlen("large_xattr");
char *xattr = calloc(xattr_length, sizeof(char));
SPDK_CU_ASSERT_FATAL(xattr != NULL);
rc = spdk_blob_set_xattr(blob, "large_xattr", xattr, xattr_length);
free(xattr);
SPDK_CU_ASSERT_FATAL(rc == 0);
/* Resize the blob */
spdk_blob_resize(blob, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Set the blob as the super blob */
spdk_bs_set_super(g_bs, blobid1, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
free_clusters = spdk_bs_free_cluster_count(g_bs);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
blob = NULL;
g_blob = NULL;
g_blobid = SPDK_BLOBID_INVALID;
/* Dirty shutdown */
_spdk_bs_free(g_bs);
/* reload blobstore */
dev = init_dev();
spdk_bs_opts_init(&opts);
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Get the super blob */
spdk_bs_get_super(g_bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(blobid1 == g_blobid);
spdk_bs_open_blob(g_bs, blobid1, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blob != NULL);
blob = g_blob;
CU_ASSERT(free_clusters == spdk_bs_free_cluster_count(g_bs));
/* Get the xattrs */
value = NULL;
rc = spdk_blob_get_xattr_value(blob, "length", &value, &value_len);
CU_ASSERT(rc == 0);
SPDK_CU_ASSERT_FATAL(value != NULL);
CU_ASSERT(*(uint64_t *)value == length);
CU_ASSERT(value_len == 8);
CU_ASSERT(spdk_blob_get_num_clusters(blob) == 10);
/* Resize the blob */
spdk_blob_resize(blob, 20, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
free_clusters = spdk_bs_free_cluster_count(g_bs);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
blob = NULL;
g_blob = NULL;
g_blobid = SPDK_BLOBID_INVALID;
/* Dirty shutdown */
_spdk_bs_free(g_bs);
/* reload the blobstore */
dev = init_dev();
spdk_bs_opts_init(&opts);
/* Load an existing blob store */
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
spdk_bs_open_blob(g_bs, blobid1, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blob != NULL);
blob = g_blob;
CU_ASSERT(spdk_blob_get_num_clusters(blob) == 20);
CU_ASSERT(free_clusters == spdk_bs_free_cluster_count(g_bs));
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
blob = NULL;
g_blob = NULL;
g_blobid = SPDK_BLOBID_INVALID;
/* Create second blob */
spdk_bs_create_blob(g_bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid2 = g_blobid;
spdk_bs_open_blob(g_bs, blobid2, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blob != NULL);
blob = g_blob;
/* Set some xattrs */
rc = spdk_blob_set_xattr(blob, "name", "log1.txt", strlen("log1.txt") + 1);
CU_ASSERT(rc == 0);
length = 5432;
rc = spdk_blob_set_xattr(blob, "length", &length, sizeof(length));
CU_ASSERT(rc == 0);
/* Resize the blob */
spdk_blob_resize(blob, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
free_clusters = spdk_bs_free_cluster_count(g_bs);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
blob = NULL;
g_blob = NULL;
g_blobid = SPDK_BLOBID_INVALID;
/* Dirty shutdown */
_spdk_bs_free(g_bs);
/* reload the blobstore */
dev = init_dev();
spdk_bs_opts_init(&opts);
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_open_blob(g_bs, blobid2, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blob != NULL);
blob = g_blob;
/* Get the xattrs */
value = NULL;
rc = spdk_blob_get_xattr_value(blob, "length", &value, &value_len);
CU_ASSERT(rc == 0);
SPDK_CU_ASSERT_FATAL(value != NULL);
CU_ASSERT(*(uint64_t *)value == length);
CU_ASSERT(value_len == 8);
CU_ASSERT(spdk_blob_get_num_clusters(blob) == 10);
CU_ASSERT(free_clusters == spdk_bs_free_cluster_count(g_bs));
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_delete_blob(g_bs, blobid2, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
free_clusters = spdk_bs_free_cluster_count(g_bs);
/* Dirty shutdown */
_spdk_bs_free(g_bs);
/* reload the blobstore */
dev = init_dev();
spdk_bs_opts_init(&opts);
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_open_blob(g_bs, blobid2, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno != 0);
CU_ASSERT(g_blob == NULL);
spdk_bs_open_blob(g_bs, blobid1, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blob != NULL);
CU_ASSERT(free_clusters == spdk_bs_free_cluster_count(g_bs));
spdk_blob_close(g_blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
/* reload the blobstore */
dev = init_dev();
spdk_bs_opts_init(&opts);
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Create second blob */
spdk_bs_create_blob(g_bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid2 = g_blobid;
/* Create third blob */
spdk_bs_create_blob(g_bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid3 = g_blobid;
spdk_bs_open_blob(g_bs, blobid2, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blob != NULL);
blob = g_blob;
/* Set some xattrs for second blob */
rc = spdk_blob_set_xattr(blob, "name", "log1.txt", strlen("log1.txt") + 1);
CU_ASSERT(rc == 0);
length = 5432;
rc = spdk_blob_set_xattr(blob, "length", &length, sizeof(length));
CU_ASSERT(rc == 0);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
blob = NULL;
g_blob = NULL;
g_blobid = SPDK_BLOBID_INVALID;
spdk_bs_open_blob(g_bs, blobid3, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blob != NULL);
blob = g_blob;
/* Set some xattrs for third blob */
rc = spdk_blob_set_xattr(blob, "name", "log2.txt", strlen("log2.txt") + 1);
CU_ASSERT(rc == 0);
length = 5432;
rc = spdk_blob_set_xattr(blob, "length", &length, sizeof(length));
CU_ASSERT(rc == 0);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
blob = NULL;
g_blob = NULL;
g_blobid = SPDK_BLOBID_INVALID;
/* Mark second blob as invalid */
page_num = _spdk_bs_blobid_to_page(blobid2);
index = DEV_BUFFER_BLOCKLEN * (g_bs->md_start + page_num);
page = (struct spdk_blob_md_page *)&g_dev_buffer[index];
page->sequence_num = 1;
page->crc = _spdk_blob_md_page_calc_crc(page);
free_clusters = spdk_bs_free_cluster_count(g_bs);
/* Dirty shutdown */
_spdk_bs_free(g_bs);
/* reload the blobstore */
dev = init_dev();
spdk_bs_opts_init(&opts);
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_open_blob(g_bs, blobid2, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno != 0);
CU_ASSERT(g_blob == NULL);
spdk_bs_open_blob(g_bs, blobid3, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blob != NULL);
blob = g_blob;
CU_ASSERT(free_clusters == spdk_bs_free_cluster_count(g_bs));
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
blob = NULL;
g_blob = NULL;
g_blobid = SPDK_BLOBID_INVALID;
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
blob_flags(void)
{
struct spdk_bs_dev *dev;
spdk_blob_id blobid_invalid, blobid_data_ro, blobid_md_ro;
struct spdk_blob *blob_invalid, *blob_data_ro, *blob_md_ro;
struct spdk_bs_opts opts;
int rc;
dev = init_dev();
spdk_bs_opts_init(&opts);
/* Initialize a new blob store */
spdk_bs_init(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
/* Create three blobs - one each for testing invalid, data_ro and md_ro flags. */
spdk_bs_create_blob(g_bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid_invalid = g_blobid;
spdk_bs_create_blob(g_bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid_data_ro = g_blobid;
spdk_bs_create_blob(g_bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid_md_ro = g_blobid;
spdk_bs_open_blob(g_bs, blobid_invalid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob_invalid = g_blob;
spdk_bs_open_blob(g_bs, blobid_data_ro, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob_data_ro = g_blob;
spdk_bs_open_blob(g_bs, blobid_md_ro, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob_md_ro = g_blob;
/* Change the size of blob_data_ro to check if flags are serialized
* when blob has non zero number of extents */
spdk_blob_resize(blob_data_ro, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Set the xattr to check if flags are serialized
* when blob has non zero number of xattrs */
rc = spdk_blob_set_xattr(blob_md_ro, "name", "log.txt", strlen("log.txt") + 1);
CU_ASSERT(rc == 0);
blob_invalid->invalid_flags = (1ULL << 63);
blob_invalid->state = SPDK_BLOB_STATE_DIRTY;
blob_data_ro->data_ro_flags = (1ULL << 62);
blob_data_ro->state = SPDK_BLOB_STATE_DIRTY;
blob_md_ro->md_ro_flags = (1ULL << 61);
blob_md_ro->state = SPDK_BLOB_STATE_DIRTY;
g_bserrno = -1;
spdk_blob_sync_md(blob_invalid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bserrno = -1;
spdk_blob_sync_md(blob_data_ro, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bserrno = -1;
spdk_blob_sync_md(blob_md_ro, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bserrno = -1;
spdk_blob_close(blob_invalid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
blob_invalid = NULL;
g_bserrno = -1;
spdk_blob_close(blob_data_ro, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
blob_data_ro = NULL;
g_bserrno = -1;
spdk_blob_close(blob_md_ro, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
blob_md_ro = NULL;
g_blob = NULL;
g_blobid = SPDK_BLOBID_INVALID;
/* Unload the blob store */
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
/* Load an existing blob store */
dev = init_dev();
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
g_blob = NULL;
g_bserrno = 0;
spdk_bs_open_blob(g_bs, blobid_invalid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno != 0);
CU_ASSERT(g_blob == NULL);
g_blob = NULL;
g_bserrno = -1;
spdk_bs_open_blob(g_bs, blobid_data_ro, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob_data_ro = g_blob;
/* If an unknown data_ro flag was found, the blob should be marked both data and md read-only. */
CU_ASSERT(blob_data_ro->data_ro == true);
CU_ASSERT(blob_data_ro->md_ro == true);
CU_ASSERT(spdk_blob_get_num_clusters(blob_data_ro) == 10);
g_blob = NULL;
g_bserrno = -1;
spdk_bs_open_blob(g_bs, blobid_md_ro, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob_md_ro = g_blob;
CU_ASSERT(blob_md_ro->data_ro == false);
CU_ASSERT(blob_md_ro->md_ro == true);
g_bserrno = -1;
spdk_blob_sync_md(blob_md_ro, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_blob_close(blob_data_ro, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_blob_close(blob_md_ro, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
}
static void
bs_version(void)
{
struct spdk_bs_super_block *super;
struct spdk_bs_dev *dev;
struct spdk_bs_opts opts;
spdk_blob_id blobid;
dev = init_dev();
spdk_bs_opts_init(&opts);
/* Initialize a new blob store */
spdk_bs_init(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
/* Unload the blob store */
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
/*
* Change the bs version on disk. This will allow us to
* test that the version does not get modified automatically
* when loading and unloading the blobstore.
*/
super = (struct spdk_bs_super_block *)&g_dev_buffer[0];
CU_ASSERT(super->version == SPDK_BS_VERSION);
CU_ASSERT(super->clean == 1);
super->version = 2;
/*
* Version 2 metadata does not have a used blobid mask, so clear
* those fields in the super block and zero the corresponding
* region on "disk". We will use this to ensure blob IDs are
* correctly reconstructed.
*/
memset(&g_dev_buffer[super->used_blobid_mask_start * SPDK_BS_PAGE_SIZE], 0,
super->used_blobid_mask_len * SPDK_BS_PAGE_SIZE);
super->used_blobid_mask_start = 0;
super->used_blobid_mask_len = 0;
super->crc = _spdk_blob_md_page_calc_crc(super);
/* Load an existing blob store */
dev = init_dev();
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
CU_ASSERT(super->clean == 1);
/*
* Create a blob - just to make sure that when we unload it
* results in writing the super block (since metadata pages
* were allocated.
*/
spdk_bs_create_blob(g_bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
/* Unload the blob store */
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
CU_ASSERT(super->version == 2);
CU_ASSERT(super->used_blobid_mask_start == 0);
CU_ASSERT(super->used_blobid_mask_len == 0);
dev = init_dev();
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
g_blob = NULL;
spdk_bs_open_blob(g_bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blob != NULL);
spdk_blob_close(g_blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
CU_ASSERT(super->version == 2);
CU_ASSERT(super->used_blobid_mask_start == 0);
CU_ASSERT(super->used_blobid_mask_len == 0);
}
static void
blob_set_xattrs(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob;
struct spdk_blob_opts opts;
spdk_blob_id blobid;
const void *value;
size_t value_len;
char *xattr;
size_t xattr_length;
int rc;
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
/* Create blob with extra attributes */
spdk_blob_opts_init(&opts);
opts.xattrs.names = g_xattr_names;
opts.xattrs.get_value = _get_xattr_value;
opts.xattrs.count = 3;
opts.xattrs.ctx = &g_ctx;
spdk_bs_create_blob_ext(bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
/* Get the xattrs */
value = NULL;
rc = spdk_blob_get_xattr_value(blob, g_xattr_names[0], &value, &value_len);
CU_ASSERT(rc == 0);
SPDK_CU_ASSERT_FATAL(value != NULL);
CU_ASSERT(value_len == strlen(g_xattr_values[0]));
CU_ASSERT_NSTRING_EQUAL_FATAL(value, g_xattr_values[0], value_len);
rc = spdk_blob_get_xattr_value(blob, g_xattr_names[1], &value, &value_len);
CU_ASSERT(rc == 0);
SPDK_CU_ASSERT_FATAL(value != NULL);
CU_ASSERT(value_len == strlen(g_xattr_values[1]));
CU_ASSERT_NSTRING_EQUAL((char *)value, g_xattr_values[1], value_len);
rc = spdk_blob_get_xattr_value(blob, g_xattr_names[2], &value, &value_len);
CU_ASSERT(rc == 0);
SPDK_CU_ASSERT_FATAL(value != NULL);
CU_ASSERT(value_len == strlen(g_xattr_values[2]));
CU_ASSERT_NSTRING_EQUAL((char *)value, g_xattr_values[2], value_len);
/* Try to get non existing attribute */
rc = spdk_blob_get_xattr_value(blob, "foobar", &value, &value_len);
CU_ASSERT(rc == -ENOENT);
/* Try xattr exceeding maximum length of descriptor in single page */
xattr_length = SPDK_BS_MAX_DESC_SIZE - sizeof(struct spdk_blob_md_descriptor_xattr) -
strlen("large_xattr") + 1;
xattr = calloc(xattr_length, sizeof(char));
SPDK_CU_ASSERT_FATAL(xattr != NULL);
rc = spdk_blob_set_xattr(blob, "large_xattr", xattr, xattr_length);
free(xattr);
SPDK_CU_ASSERT_FATAL(rc == -ENOMEM);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
blob = NULL;
g_blob = NULL;
g_blobid = SPDK_BLOBID_INVALID;
/* NULL callback */
spdk_blob_opts_init(&opts);
opts.xattrs.names = g_xattr_names;
opts.xattrs.get_value = NULL;
opts.xattrs.count = 1;
opts.xattrs.ctx = &g_ctx;
spdk_bs_create_blob_ext(bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -EINVAL);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
/* NULL values */
spdk_blob_opts_init(&opts);
opts.xattrs.names = g_xattr_names;
opts.xattrs.get_value = _get_xattr_value_null;
opts.xattrs.count = 1;
opts.xattrs.ctx = NULL;
spdk_bs_create_blob_ext(bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == -EINVAL);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
blob_thin_prov_alloc(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob;
struct spdk_blob_opts opts;
spdk_blob_id blobid;
uint64_t free_clusters;
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
free_clusters = spdk_bs_free_cluster_count(bs);
/* Set blob as thin provisioned */
spdk_blob_opts_init(&opts);
opts.thin_provision = true;
spdk_bs_create_blob_ext(bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
CU_ASSERT(free_clusters == spdk_bs_free_cluster_count(bs));
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
CU_ASSERT(blob->active.num_clusters == 0);
CU_ASSERT(spdk_blob_get_num_clusters(blob) == 0);
/* The blob started at 0 clusters. Resize it to be 5, but still unallocated. */
spdk_blob_resize(blob, 5, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(free_clusters == spdk_bs_free_cluster_count(bs));
CU_ASSERT(blob->active.num_clusters == 5);
CU_ASSERT(spdk_blob_get_num_clusters(blob) == 5);
/* Grow it to 1TB - still unallocated */
spdk_blob_resize(blob, 262144, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(free_clusters == spdk_bs_free_cluster_count(bs));
CU_ASSERT(blob->active.num_clusters == 262144);
CU_ASSERT(spdk_blob_get_num_clusters(blob) == 262144);
spdk_blob_sync_md(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Sync must not change anything */
CU_ASSERT(free_clusters == spdk_bs_free_cluster_count(bs));
CU_ASSERT(blob->active.num_clusters == 262144);
CU_ASSERT(spdk_blob_get_num_clusters(blob) == 262144);
/* Since clusters are not allocated,
* number of metadata pages is expected to be minimal.
*/
CU_ASSERT(blob->active.num_pages == 1);
/* Shrink the blob to 3 clusters - still unallocated */
spdk_blob_resize(blob, 3, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(free_clusters == spdk_bs_free_cluster_count(bs));
CU_ASSERT(blob->active.num_clusters == 3);
CU_ASSERT(spdk_blob_get_num_clusters(blob) == 3);
spdk_blob_sync_md(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Sync must not change anything */
CU_ASSERT(free_clusters == spdk_bs_free_cluster_count(bs));
CU_ASSERT(blob->active.num_clusters == 3);
CU_ASSERT(spdk_blob_get_num_clusters(blob) == 3);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Unload the blob store */
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
g_blob = NULL;
g_blobid = 0;
/* Load an existing blob store */
dev = init_dev();
spdk_bs_load(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
spdk_bs_open_blob(g_bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
/* Check that clusters allocation and size is still the same */
CU_ASSERT(free_clusters == spdk_bs_free_cluster_count(bs));
CU_ASSERT(blob->active.num_clusters == 3);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_delete_blob(bs, blobid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
blob_insert_cluster_msg(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob;
struct spdk_blob_opts opts;
spdk_blob_id blobid;
uint64_t free_clusters;
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
free_clusters = spdk_bs_free_cluster_count(bs);
/* Set blob as thin provisioned */
spdk_blob_opts_init(&opts);
opts.thin_provision = true;
opts.num_clusters = 4;
spdk_bs_create_blob_ext(bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
CU_ASSERT(free_clusters == spdk_bs_free_cluster_count(bs));
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
CU_ASSERT(blob->active.num_clusters == 4);
CU_ASSERT(spdk_blob_get_num_clusters(blob) == 4);
CU_ASSERT(blob->active.clusters[1] == 0);
_spdk_bs_claim_cluster(bs, 0xF);
_spdk_blob_insert_cluster_on_md_thread(blob, 1, 0xF, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(blob->active.clusters[1] != 0);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Unload the blob store */
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
g_blob = NULL;
g_blobid = 0;
/* Load an existing blob store */
dev = init_dev();
spdk_bs_load(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
spdk_bs_open_blob(g_bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
CU_ASSERT(blob->active.clusters[1] != 0);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_delete_blob(bs, blobid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
blob_thin_prov_rw(void)
{
static const uint8_t zero[10 * 4096] = { 0 };
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob;
struct spdk_io_channel *channel, *channel_thread1;
struct spdk_blob_opts opts;
spdk_blob_id blobid;
uint64_t free_clusters;
uint64_t page_size;
uint8_t payload_read[10 * 4096];
uint8_t payload_write[10 * 4096];
uint64_t write_bytes;
uint64_t read_bytes;
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
free_clusters = spdk_bs_free_cluster_count(bs);
page_size = spdk_bs_get_page_size(bs);
channel = spdk_bs_alloc_io_channel(bs);
CU_ASSERT(channel != NULL);
spdk_blob_opts_init(&opts);
opts.thin_provision = true;
spdk_bs_create_blob_ext(bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
CU_ASSERT(free_clusters == spdk_bs_free_cluster_count(bs));
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
CU_ASSERT(blob->active.num_clusters == 0);
/* The blob started at 0 clusters. Resize it to be 5, but still unallocated. */
spdk_blob_resize(blob, 5, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(free_clusters == spdk_bs_free_cluster_count(bs));
CU_ASSERT(blob->active.num_clusters == 5);
spdk_blob_sync_md(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Sync must not change anything */
CU_ASSERT(free_clusters == spdk_bs_free_cluster_count(bs));
CU_ASSERT(blob->active.num_clusters == 5);
/* Payload should be all zeros from unallocated clusters */
memset(payload_read, 0xFF, sizeof(payload_read));
spdk_blob_io_read(blob, channel, payload_read, 4, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(zero, payload_read, 10 * 4096) == 0);
write_bytes = g_dev_write_bytes;
read_bytes = g_dev_read_bytes;
/* Perform write on thread 1. That will allocate cluster on thread 0 via send_msg */
set_thread(1);
channel_thread1 = spdk_bs_alloc_io_channel(bs);
CU_ASSERT(channel_thread1 != NULL);
memset(payload_write, 0xE5, sizeof(payload_write));
spdk_blob_io_write(blob, channel_thread1, payload_write, 4, 10, blob_op_complete, NULL);
CU_ASSERT(free_clusters - 1 == spdk_bs_free_cluster_count(bs));
/* Perform write on thread 0. That will try to allocate cluster,
* but fail due to another thread issuing the cluster allocation first. */
set_thread(0);
memset(payload_write, 0xE5, sizeof(payload_write));
spdk_blob_io_write(blob, channel, payload_write, 4, 10, blob_op_complete, NULL);
CU_ASSERT(free_clusters - 2 == spdk_bs_free_cluster_count(bs));
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(free_clusters - 1 == spdk_bs_free_cluster_count(bs));
/* For thin-provisioned blob we need to write 20 pages plus one page metadata and
* read 0 bytes */
CU_ASSERT(g_dev_write_bytes - write_bytes == page_size * 21);
CU_ASSERT(g_dev_read_bytes - read_bytes == 0);
spdk_blob_io_read(blob, channel, payload_read, 4, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_write, payload_read, 10 * 4096) == 0);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_delete_blob(bs, blobid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(free_clusters == spdk_bs_free_cluster_count(bs));
spdk_bs_free_io_channel(channel_thread1);
spdk_bs_free_io_channel(channel);
poll_threads();
/* Unload the blob store */
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
g_blob = NULL;
g_blobid = 0;
}
static void
blob_thin_prov_rle(void)
{
static const uint8_t zero[10 * 4096] = { 0 };
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob;
struct spdk_io_channel *channel;
struct spdk_blob_opts opts;
spdk_blob_id blobid;
uint64_t free_clusters;
uint64_t page_size;
uint8_t payload_read[10 * 4096];
uint8_t payload_write[10 * 4096];
uint64_t write_bytes;
uint64_t read_bytes;
uint64_t io_unit;
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
free_clusters = spdk_bs_free_cluster_count(bs);
page_size = spdk_bs_get_page_size(bs);
spdk_blob_opts_init(&opts);
opts.thin_provision = true;
opts.num_clusters = 5;
spdk_bs_create_blob_ext(bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
CU_ASSERT(free_clusters == spdk_bs_free_cluster_count(bs));
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
channel = spdk_bs_alloc_io_channel(bs);
CU_ASSERT(channel != NULL);
/* Target specifically second cluster in a blob as first allocation */
io_unit = _spdk_bs_cluster_to_page(bs, 1) * _spdk_bs_io_unit_per_page(bs);
/* Payload should be all zeros from unallocated clusters */
memset(payload_read, 0xFF, sizeof(payload_read));
spdk_blob_io_read(blob, channel, payload_read, io_unit, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(zero, payload_read, 10 * 4096) == 0);
write_bytes = g_dev_write_bytes;
read_bytes = g_dev_read_bytes;
/* Issue write to second cluster in a blob */
memset(payload_write, 0xE5, sizeof(payload_write));
spdk_blob_io_write(blob, channel, payload_write, io_unit, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(free_clusters - 1 == spdk_bs_free_cluster_count(bs));
/* For thin-provisioned blob we need to write 10 pages plus one page metadata and
* read 0 bytes */
CU_ASSERT(g_dev_write_bytes - write_bytes == page_size * 11);
CU_ASSERT(g_dev_read_bytes - read_bytes == 0);
spdk_blob_io_read(blob, channel, payload_read, io_unit, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_write, payload_read, 10 * 4096) == 0);
spdk_bs_free_io_channel(channel);
poll_threads();
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Unload the blob store */
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
g_blob = NULL;
g_blobid = 0;
/* Load an existing blob store */
dev = init_dev();
spdk_bs_load(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
spdk_bs_open_blob(g_bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
channel = spdk_bs_alloc_io_channel(bs);
CU_ASSERT(channel != NULL);
/* Read second cluster after blob reload to confirm data written */
spdk_blob_io_read(blob, channel, payload_read, io_unit, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_write, payload_read, 10 * 4096) == 0);
spdk_bs_free_io_channel(channel);
poll_threads();
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_delete_blob(bs, blobid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
blob_thin_prov_rw_iov(void)
{
static const uint8_t zero[10 * 4096] = { 0 };
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob;
struct spdk_io_channel *channel;
struct spdk_blob_opts opts;
spdk_blob_id blobid;
uint64_t free_clusters;
uint8_t payload_read[10 * 4096];
uint8_t payload_write[10 * 4096];
struct iovec iov_read[3];
struct iovec iov_write[3];
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
free_clusters = spdk_bs_free_cluster_count(bs);
channel = spdk_bs_alloc_io_channel(bs);
CU_ASSERT(channel != NULL);
spdk_blob_opts_init(&opts);
opts.thin_provision = true;
spdk_bs_create_blob_ext(bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
CU_ASSERT(free_clusters == spdk_bs_free_cluster_count(bs));
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
CU_ASSERT(blob->active.num_clusters == 0);
/* The blob started at 0 clusters. Resize it to be 5, but still unallocated. */
spdk_blob_resize(blob, 5, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(free_clusters == spdk_bs_free_cluster_count(bs));
CU_ASSERT(blob->active.num_clusters == 5);
spdk_blob_sync_md(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Sync must not change anything */
CU_ASSERT(free_clusters == spdk_bs_free_cluster_count(bs));
CU_ASSERT(blob->active.num_clusters == 5);
/* Payload should be all zeros from unallocated clusters */
memset(payload_read, 0xAA, sizeof(payload_read));
iov_read[0].iov_base = payload_read;
iov_read[0].iov_len = 3 * 4096;
iov_read[1].iov_base = payload_read + 3 * 4096;
iov_read[1].iov_len = 4 * 4096;
iov_read[2].iov_base = payload_read + 7 * 4096;
iov_read[2].iov_len = 3 * 4096;
spdk_blob_io_readv(blob, channel, iov_read, 3, 250, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(zero, payload_read, 10 * 4096) == 0);
memset(payload_write, 0xE5, sizeof(payload_write));
iov_write[0].iov_base = payload_write;
iov_write[0].iov_len = 1 * 4096;
iov_write[1].iov_base = payload_write + 1 * 4096;
iov_write[1].iov_len = 5 * 4096;
iov_write[2].iov_base = payload_write + 6 * 4096;
iov_write[2].iov_len = 4 * 4096;
spdk_blob_io_writev(blob, channel, iov_write, 3, 250, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
memset(payload_read, 0xAA, sizeof(payload_read));
iov_read[0].iov_base = payload_read;
iov_read[0].iov_len = 3 * 4096;
iov_read[1].iov_base = payload_read + 3 * 4096;
iov_read[1].iov_len = 4 * 4096;
iov_read[2].iov_base = payload_read + 7 * 4096;
iov_read[2].iov_len = 3 * 4096;
spdk_blob_io_readv(blob, channel, iov_read, 3, 250, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_write, payload_read, 10 * 4096) == 0);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_free_io_channel(channel);
poll_threads();
/* Unload the blob store */
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
g_blob = NULL;
g_blobid = 0;
}
struct iter_ctx {
int current_iter;
spdk_blob_id blobid[4];
};
static void
test_iter(void *arg, struct spdk_blob *blob, int bserrno)
{
struct iter_ctx *iter_ctx = arg;
spdk_blob_id blobid;
CU_ASSERT(bserrno == 0);
blobid = spdk_blob_get_id(blob);
CU_ASSERT(blobid == iter_ctx->blobid[iter_ctx->current_iter++]);
}
static void
bs_load_iter(void)
{
struct spdk_bs_dev *dev;
struct iter_ctx iter_ctx = { 0 };
struct spdk_blob *blob;
int i, rc;
struct spdk_bs_opts opts;
dev = init_dev();
spdk_bs_opts_init(&opts);
snprintf(opts.bstype.bstype, sizeof(opts.bstype.bstype), "TESTTYPE");
/* Initialize a new blob store */
spdk_bs_init(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
for (i = 0; i < 4; i++) {
g_bserrno = -1;
g_blobid = SPDK_BLOBID_INVALID;
spdk_bs_create_blob(g_bs, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
iter_ctx.blobid[i] = g_blobid;
g_bserrno = -1;
g_blob = NULL;
spdk_bs_open_blob(g_bs, g_blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blob != NULL);
blob = g_blob;
/* Just save the blobid as an xattr for testing purposes. */
rc = spdk_blob_set_xattr(blob, "blobid", &g_blobid, sizeof(g_blobid));
CU_ASSERT(rc == 0);
/* Resize the blob */
spdk_blob_resize(blob, i, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
}
g_bserrno = -1;
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
dev = init_dev();
spdk_bs_opts_init(&opts);
snprintf(opts.bstype.bstype, sizeof(opts.bstype.bstype), "TESTTYPE");
opts.iter_cb_fn = test_iter;
opts.iter_cb_arg = &iter_ctx;
/* Test blob iteration during load after a clean shutdown. */
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
/* Dirty shutdown */
_spdk_bs_free(g_bs);
dev = init_dev();
spdk_bs_opts_init(&opts);
snprintf(opts.bstype.bstype, sizeof(opts.bstype.bstype), "TESTTYPE");
opts.iter_cb_fn = test_iter;
iter_ctx.current_iter = 0;
opts.iter_cb_arg = &iter_ctx;
/* Test blob iteration during load after a dirty shutdown. */
spdk_bs_load(dev, &opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
blob_snapshot_rw(void)
{
static const uint8_t zero[10 * 4096] = { 0 };
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob, *snapshot;
struct spdk_io_channel *channel;
struct spdk_blob_opts opts;
spdk_blob_id blobid, snapshotid;
uint64_t free_clusters;
uint64_t cluster_size;
uint64_t page_size;
uint8_t payload_read[10 * 4096];
uint8_t payload_write[10 * 4096];
uint64_t write_bytes;
uint64_t read_bytes;
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
free_clusters = spdk_bs_free_cluster_count(bs);
cluster_size = spdk_bs_get_cluster_size(bs);
page_size = spdk_bs_get_page_size(bs);
channel = spdk_bs_alloc_io_channel(bs);
CU_ASSERT(channel != NULL);
spdk_blob_opts_init(&opts);
opts.thin_provision = true;
opts.num_clusters = 5;
spdk_bs_create_blob_ext(bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
CU_ASSERT(free_clusters == spdk_bs_free_cluster_count(bs));
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
CU_ASSERT(spdk_blob_get_num_clusters(blob) == 5);
memset(payload_read, 0xFF, sizeof(payload_read));
spdk_blob_io_read(blob, channel, payload_read, 4, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(zero, payload_read, 10 * 4096) == 0);
memset(payload_write, 0xE5, sizeof(payload_write));
spdk_blob_io_write(blob, channel, payload_write, 4, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(free_clusters != spdk_bs_free_cluster_count(bs));
/* Create snapshot from blob */
spdk_bs_create_snapshot(bs, blobid, NULL, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
snapshotid = g_blobid;
spdk_bs_open_blob(bs, snapshotid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
snapshot = g_blob;
CU_ASSERT(snapshot->data_ro == true);
CU_ASSERT(snapshot->md_ro == true);
CU_ASSERT(spdk_blob_get_num_clusters(snapshot) == 5);
write_bytes = g_dev_write_bytes;
read_bytes = g_dev_read_bytes;
memset(payload_write, 0xAA, sizeof(payload_write));
spdk_blob_io_write(blob, channel, payload_write, 4, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(free_clusters != spdk_bs_free_cluster_count(bs));
/* For a clone we need to allocate and copy one cluster, update one page of metadata
* and then write 10 pages of payload.
*/
CU_ASSERT(g_dev_write_bytes - write_bytes == page_size * 11 + cluster_size);
CU_ASSERT(g_dev_read_bytes - read_bytes == cluster_size);
spdk_blob_io_read(blob, channel, payload_read, 4, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_write, payload_read, 10 * 4096) == 0);
/* Data on snapshot should not change after write to clone */
memset(payload_write, 0xE5, sizeof(payload_write));
spdk_blob_io_read(snapshot, channel, payload_read, 4, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_write, payload_read, 10 * 4096) == 0);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_blob_close(snapshot, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_delete_blob(bs, blobid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_delete_blob(bs, snapshotid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_free_io_channel(channel);
poll_threads();
/* Unload the blob store */
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
g_blob = NULL;
g_blobid = 0;
}
static void
blob_snapshot_rw_iov(void)
{
static const uint8_t zero[10 * 4096] = { 0 };
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob, *snapshot;
struct spdk_io_channel *channel;
struct spdk_blob_opts opts;
spdk_blob_id blobid, snapshotid;
uint64_t free_clusters;
uint8_t payload_read[10 * 4096];
uint8_t payload_write[10 * 4096];
struct iovec iov_read[3];
struct iovec iov_write[3];
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
free_clusters = spdk_bs_free_cluster_count(bs);
channel = spdk_bs_alloc_io_channel(bs);
CU_ASSERT(channel != NULL);
spdk_blob_opts_init(&opts);
opts.thin_provision = true;
opts.num_clusters = 5;
spdk_bs_create_blob_ext(bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
CU_ASSERT(free_clusters == spdk_bs_free_cluster_count(bs));
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
CU_ASSERT(spdk_blob_get_num_clusters(blob) == 5);
/* Create snapshot from blob */
spdk_bs_create_snapshot(bs, blobid, NULL, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
snapshotid = g_blobid;
spdk_bs_open_blob(bs, snapshotid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
snapshot = g_blob;
CU_ASSERT(snapshot->data_ro == true);
CU_ASSERT(snapshot->md_ro == true);
CU_ASSERT(spdk_blob_get_num_clusters(snapshot) == 5);
/* Payload should be all zeros from unallocated clusters */
memset(payload_read, 0xAA, sizeof(payload_read));
iov_read[0].iov_base = payload_read;
iov_read[0].iov_len = 3 * 4096;
iov_read[1].iov_base = payload_read + 3 * 4096;
iov_read[1].iov_len = 4 * 4096;
iov_read[2].iov_base = payload_read + 7 * 4096;
iov_read[2].iov_len = 3 * 4096;
spdk_blob_io_readv(blob, channel, iov_read, 3, 250, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(zero, payload_read, 10 * 4096) == 0);
memset(payload_write, 0xE5, sizeof(payload_write));
iov_write[0].iov_base = payload_write;
iov_write[0].iov_len = 1 * 4096;
iov_write[1].iov_base = payload_write + 1 * 4096;
iov_write[1].iov_len = 5 * 4096;
iov_write[2].iov_base = payload_write + 6 * 4096;
iov_write[2].iov_len = 4 * 4096;
spdk_blob_io_writev(blob, channel, iov_write, 3, 250, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
memset(payload_read, 0xAA, sizeof(payload_read));
iov_read[0].iov_base = payload_read;
iov_read[0].iov_len = 3 * 4096;
iov_read[1].iov_base = payload_read + 3 * 4096;
iov_read[1].iov_len = 4 * 4096;
iov_read[2].iov_base = payload_read + 7 * 4096;
iov_read[2].iov_len = 3 * 4096;
spdk_blob_io_readv(blob, channel, iov_read, 3, 250, 10, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_write, payload_read, 10 * 4096) == 0);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_blob_close(snapshot, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_free_io_channel(channel);
poll_threads();
/* Unload the blob store */
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
g_blob = NULL;
g_blobid = 0;
}
/**
* Inflate / decouple parent rw unit tests.
*
* --------------
* original blob: 0 1 2 3 4
* ,---------+---------+---------+---------+---------.
* snapshot |xxxxxxxxx|xxxxxxxxx|xxxxxxxxx|xxxxxxxxx| - |
* +---------+---------+---------+---------+---------+
* snapshot2 | - |yyyyyyyyy| - |yyyyyyyyy| - |
* +---------+---------+---------+---------+---------+
* blob | - |zzzzzzzzz| - | - | - |
* '---------+---------+---------+---------+---------'
* . . . . . .
* -------- . . . . . .
* inflate: . . . . . .
* ,---------+---------+---------+---------+---------.
* blob |xxxxxxxxx|zzzzzzzzz|xxxxxxxxx|yyyyyyyyy|000000000|
* '---------+---------+---------+---------+---------'
*
* NOTE: needs to allocate 4 clusters, thin provisioning removed, dependency
* on snapshot2 and snapshot removed . . .
* . . . . . .
* ---------------- . . . . . .
* decouple parent: . . . . . .
* ,---------+---------+---------+---------+---------.
* snapshot |xxxxxxxxx|xxxxxxxxx|xxxxxxxxx|xxxxxxxxx| - |
* +---------+---------+---------+---------+---------+
* blob | - |zzzzzzzzz| - |yyyyyyyyy| - |
* '---------+---------+---------+---------+---------'
*
* NOTE: needs to allocate 1 cluster, 3 clusters unallocated, dependency
* on snapshot2 removed and on snapshot still exists. Snapshot2
* should remain a clone of snapshot.
*/
static void
_blob_inflate_rw(bool decouple_parent)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob *blob, *snapshot, *snapshot2;
struct spdk_io_channel *channel;
struct spdk_blob_opts opts;
spdk_blob_id blobid, snapshotid, snapshot2id;
uint64_t free_clusters;
uint64_t cluster_size;
uint64_t payload_size;
uint8_t *payload_read;
uint8_t *payload_write;
uint8_t *payload_clone;
uint64_t pages_per_cluster;
uint64_t pages_per_payload;
int i;
spdk_blob_id ids[2];
size_t count;
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
free_clusters = spdk_bs_free_cluster_count(bs);
cluster_size = spdk_bs_get_cluster_size(bs);
pages_per_cluster = cluster_size / spdk_bs_get_page_size(bs);
pages_per_payload = pages_per_cluster * 5;
payload_size = cluster_size * 5;
payload_read = malloc(payload_size);
SPDK_CU_ASSERT_FATAL(payload_read != NULL);
payload_write = malloc(payload_size);
SPDK_CU_ASSERT_FATAL(payload_write != NULL);
payload_clone = malloc(payload_size);
SPDK_CU_ASSERT_FATAL(payload_clone != NULL);
channel = spdk_bs_alloc_io_channel(bs);
SPDK_CU_ASSERT_FATAL(channel != NULL);
/* Create blob */
spdk_blob_opts_init(&opts);
opts.thin_provision = true;
opts.num_clusters = 5;
spdk_bs_create_blob_ext(bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
CU_ASSERT(free_clusters == spdk_bs_free_cluster_count(bs));
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
CU_ASSERT(spdk_blob_get_num_clusters(blob) == 5);
/* 1) Initial read should return zeroed payload */
memset(payload_read, 0xFF, payload_size);
spdk_blob_io_read(blob, channel, payload_read, 0, pages_per_payload,
blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(spdk_mem_all_zero(payload_read, payload_size));
/* Fill whole blob with a pattern, except last cluster (to be sure it
* isn't allocated) */
memset(payload_write, 0xE5, payload_size - cluster_size);
spdk_blob_io_write(blob, channel, payload_write, 0, pages_per_payload -
pages_per_cluster, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(free_clusters != spdk_bs_free_cluster_count(bs));
/* 2) Create snapshot from blob (first level) */
spdk_bs_create_snapshot(bs, blobid, NULL, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
snapshotid = g_blobid;
spdk_bs_open_blob(bs, snapshotid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
snapshot = g_blob;
CU_ASSERT(snapshot->data_ro == true);
CU_ASSERT(snapshot->md_ro == true);
CU_ASSERT(spdk_blob_get_num_clusters(snapshot) == 5);
/* Write every second cluster with a pattern.
*
* Last cluster shouldn't be written, to be sure that snapshot nor clone
* doesn't allocate it.
*
* payload_clone stores expected result on "blob" read at the time and
* is used only to check data consistency on clone before and after
* inflation. Initially we fill it with a backing snapshots pattern
* used before.
*/
memset(payload_clone, 0xE5, payload_size - cluster_size);
memset(payload_clone + payload_size - cluster_size, 0x00, cluster_size);
memset(payload_write, 0xAA, payload_size);
for (i = 1; i < 5; i += 2) {
spdk_blob_io_write(blob, channel, payload_write, i * pages_per_cluster,
pages_per_cluster, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Update expected result */
memcpy(payload_clone + (cluster_size * i), payload_write,
cluster_size);
}
CU_ASSERT(free_clusters != spdk_bs_free_cluster_count(bs));
/* Check data consistency on clone */
memset(payload_read, 0xFF, payload_size);
spdk_blob_io_read(blob, channel, payload_read, 0, pages_per_payload,
blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_clone, payload_read, payload_size) == 0);
/* 3) Create second levels snapshot from blob */
spdk_bs_create_snapshot(bs, blobid, NULL, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
snapshot2id = g_blobid;
spdk_bs_open_blob(bs, snapshot2id, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
snapshot2 = g_blob;
CU_ASSERT(snapshot2->data_ro == true);
CU_ASSERT(snapshot2->md_ro == true);
CU_ASSERT(spdk_blob_get_num_clusters(snapshot2) == 5);
CU_ASSERT(snapshot2->parent_id == snapshotid);
/* Write one cluster on the top level blob. This cluster (1) covers
* already allocated cluster in the snapshot2, so shouldn't be inflated
* at all */
spdk_blob_io_write(blob, channel, payload_write, pages_per_cluster,
pages_per_cluster, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Update expected result */
memcpy(payload_clone + cluster_size, payload_write, cluster_size);
/* Check data consistency on clone */
memset(payload_read, 0xFF, payload_size);
spdk_blob_io_read(blob, channel, payload_read, 0, pages_per_payload,
blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_clone, payload_read, payload_size) == 0);
/* Close all blobs */
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_blob_close(snapshot2, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_blob_close(snapshot, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Check snapshot-clone relations */
count = 2;
CU_ASSERT(spdk_blob_get_clones(bs, snapshotid, ids, &count) == 0);
CU_ASSERT(count == 1);
CU_ASSERT(ids[0] == snapshot2id);
count = 2;
CU_ASSERT(spdk_blob_get_clones(bs, snapshot2id, ids, &count) == 0);
CU_ASSERT(count == 1);
CU_ASSERT(ids[0] == blobid);
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, blobid) == snapshot2id);
free_clusters = spdk_bs_free_cluster_count(bs);
if (!decouple_parent) {
/* Do full blob inflation */
spdk_bs_inflate_blob(bs, channel, blobid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* All clusters should be inflated (except one already allocated
* in a top level blob) */
CU_ASSERT(spdk_bs_free_cluster_count(bs) == free_clusters - 4);
/* Check if relation tree updated correctly */
count = 2;
CU_ASSERT(spdk_blob_get_clones(bs, snapshotid, ids, &count) == 0);
/* snapshotid have one clone */
CU_ASSERT(count == 1);
CU_ASSERT(ids[0] == snapshot2id);
/* snapshot2id have no clones */
count = 2;
CU_ASSERT(spdk_blob_get_clones(bs, snapshot2id, ids, &count) == 0);
CU_ASSERT(count == 0);
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, blobid) == SPDK_BLOBID_INVALID);
} else {
/* Decouple parent of blob */
spdk_bs_blob_decouple_parent(bs, channel, blobid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Only one cluster from a parent should be inflated (second one
* is covered by a cluster written on a top level blob, and
* already allocated) */
CU_ASSERT(spdk_bs_free_cluster_count(bs) == free_clusters - 1);
/* Check if relation tree updated correctly */
count = 2;
CU_ASSERT(spdk_blob_get_clones(bs, snapshotid, ids, &count) == 0);
/* snapshotid have two clones now */
CU_ASSERT(count == 2);
CU_ASSERT(ids[0] == blobid || ids[1] == blobid);
CU_ASSERT(ids[0] == snapshot2id || ids[1] == snapshot2id);
/* snapshot2id have no clones */
count = 2;
CU_ASSERT(spdk_blob_get_clones(bs, snapshot2id, ids, &count) == 0);
CU_ASSERT(count == 0);
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, blobid) == snapshotid);
}
/* Try to delete snapshot2 (should pass) */
spdk_bs_delete_blob(bs, snapshot2id, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Try to delete base snapshot */
spdk_bs_delete_blob(bs, snapshotid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Reopen blob after snapshot deletion */
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
CU_ASSERT(spdk_blob_get_num_clusters(blob) == 5);
/* Check data consistency on inflated blob */
memset(payload_read, 0xFF, payload_size);
spdk_blob_io_read(blob, channel, payload_read, 0, pages_per_payload,
blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_clone, payload_read, payload_size) == 0);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_free_io_channel(channel);
poll_threads();
/* Unload the blob store */
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
g_blob = NULL;
g_blobid = 0;
free(payload_read);
free(payload_write);
free(payload_clone);
}
static void
blob_inflate_rw(void)
{
_blob_inflate_rw(false);
_blob_inflate_rw(true);
}
/**
* Snapshot-clones relation test
*
* snapshot
* |
* +-----+-----+
* | |
* blob(ro) snapshot2
* | |
* clone2 clone
*/
static void
blob_relations(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_bs_opts bs_opts;
struct spdk_blob_opts opts;
struct spdk_blob *blob, *snapshot, *snapshot2, *clone, *clone2;
spdk_blob_id blobid, cloneid, snapshotid, cloneid2, snapshotid2;
int rc;
size_t count;
spdk_blob_id ids[10] = {};
dev = init_dev();
spdk_bs_opts_init(&bs_opts);
snprintf(bs_opts.bstype.bstype, sizeof(bs_opts.bstype.bstype), "TESTTYPE");
spdk_bs_init(dev, &bs_opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
/* 1. Create blob with 10 clusters */
spdk_blob_opts_init(&opts);
opts.num_clusters = 10;
spdk_bs_create_blob_ext(bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
CU_ASSERT(!spdk_blob_is_read_only(blob));
CU_ASSERT(!spdk_blob_is_snapshot(blob));
CU_ASSERT(!spdk_blob_is_clone(blob));
CU_ASSERT(!spdk_blob_is_thin_provisioned(blob));
/* blob should not have underlying snapshot nor clones */
CU_ASSERT(blob->parent_id == SPDK_BLOBID_INVALID);
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, blobid) == SPDK_BLOBID_INVALID);
count = SPDK_COUNTOF(ids);
rc = spdk_blob_get_clones(bs, blobid, ids, &count);
CU_ASSERT(rc == 0);
CU_ASSERT(count == 0);
/* 2. Create snapshot */
spdk_bs_create_snapshot(bs, blobid, NULL, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
snapshotid = g_blobid;
spdk_bs_open_blob(bs, snapshotid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
snapshot = g_blob;
CU_ASSERT(spdk_blob_is_read_only(snapshot));
CU_ASSERT(spdk_blob_is_snapshot(snapshot));
CU_ASSERT(!spdk_blob_is_clone(snapshot));
CU_ASSERT(snapshot->parent_id == SPDK_BLOBID_INVALID);
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, snapshotid) == SPDK_BLOBID_INVALID);
/* Check if original blob is converted to the clone of snapshot */
CU_ASSERT(!spdk_blob_is_read_only(blob));
CU_ASSERT(!spdk_blob_is_snapshot(blob));
CU_ASSERT(spdk_blob_is_clone(blob));
CU_ASSERT(spdk_blob_is_thin_provisioned(blob));
CU_ASSERT(blob->parent_id == snapshotid);
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, blobid) == snapshotid);
count = SPDK_COUNTOF(ids);
rc = spdk_blob_get_clones(bs, snapshotid, ids, &count);
CU_ASSERT(rc == 0);
CU_ASSERT(count == 1);
CU_ASSERT(ids[0] == blobid);
/* 3. Create clone from snapshot */
spdk_bs_create_clone(bs, snapshotid, NULL, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
cloneid = g_blobid;
spdk_bs_open_blob(bs, cloneid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
clone = g_blob;
CU_ASSERT(!spdk_blob_is_read_only(clone));
CU_ASSERT(!spdk_blob_is_snapshot(clone));
CU_ASSERT(spdk_blob_is_clone(clone));
CU_ASSERT(spdk_blob_is_thin_provisioned(clone));
CU_ASSERT(clone->parent_id == snapshotid);
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, cloneid) == snapshotid);
count = SPDK_COUNTOF(ids);
rc = spdk_blob_get_clones(bs, cloneid, ids, &count);
CU_ASSERT(rc == 0);
CU_ASSERT(count == 0);
/* Check if clone is on the snapshot's list */
count = SPDK_COUNTOF(ids);
rc = spdk_blob_get_clones(bs, snapshotid, ids, &count);
CU_ASSERT(rc == 0);
CU_ASSERT(ids[0] == blobid || ids[1] == blobid);
CU_ASSERT(ids[0] == cloneid || ids[1] == cloneid);
/* 4. Create snapshot of the clone */
spdk_bs_create_snapshot(bs, cloneid, NULL, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
snapshotid2 = g_blobid;
spdk_bs_open_blob(bs, snapshotid2, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
snapshot2 = g_blob;
CU_ASSERT(spdk_blob_is_read_only(snapshot2));
CU_ASSERT(spdk_blob_is_snapshot(snapshot2));
CU_ASSERT(spdk_blob_is_clone(snapshot2));
CU_ASSERT(snapshot2->parent_id == snapshotid);
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, snapshotid2) == snapshotid);
/* Check if clone is converted to the clone of snapshot2 and snapshot2
* is a child of snapshot */
CU_ASSERT(!spdk_blob_is_read_only(clone));
CU_ASSERT(!spdk_blob_is_snapshot(clone));
CU_ASSERT(spdk_blob_is_clone(clone));
CU_ASSERT(spdk_blob_is_thin_provisioned(clone));
CU_ASSERT(clone->parent_id == snapshotid2);
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, cloneid) == snapshotid2);
count = SPDK_COUNTOF(ids);
rc = spdk_blob_get_clones(bs, snapshotid2, ids, &count);
CU_ASSERT(rc == 0);
CU_ASSERT(count == 1);
CU_ASSERT(ids[0] == cloneid);
/* 5. Try to create clone from read only blob */
/* Mark blob as read only */
spdk_blob_set_read_only(blob);
spdk_blob_sync_md(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Check if previously created blob is read only clone */
CU_ASSERT(spdk_blob_is_read_only(blob));
CU_ASSERT(!spdk_blob_is_snapshot(blob));
CU_ASSERT(spdk_blob_is_clone(blob));
CU_ASSERT(spdk_blob_is_thin_provisioned(blob));
/* Create clone from read only blob */
spdk_bs_create_clone(bs, blobid, NULL, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
cloneid2 = g_blobid;
spdk_bs_open_blob(bs, cloneid2, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
clone2 = g_blob;
CU_ASSERT(!spdk_blob_is_read_only(clone2));
CU_ASSERT(!spdk_blob_is_snapshot(clone2));
CU_ASSERT(spdk_blob_is_clone(clone2));
CU_ASSERT(spdk_blob_is_thin_provisioned(clone2));
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, cloneid2) == blobid);
count = SPDK_COUNTOF(ids);
rc = spdk_blob_get_clones(bs, blobid, ids, &count);
CU_ASSERT(rc == 0);
CU_ASSERT(count == 1);
CU_ASSERT(ids[0] == cloneid2);
/* Close blobs */
spdk_blob_close(clone2, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_blob_close(clone, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_blob_close(snapshot, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_blob_close(snapshot2, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Try to delete snapshot with more than 1 clone */
spdk_bs_delete_blob(bs, snapshotid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno != 0);
spdk_bs_unload(bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
/* Load an existing blob store */
dev = init_dev();
snprintf(bs_opts.bstype.bstype, sizeof(bs_opts.bstype.bstype), "TESTTYPE");
spdk_bs_load(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
/* NULL ids array should return number of clones in count */
count = SPDK_COUNTOF(ids);
rc = spdk_blob_get_clones(bs, snapshotid, NULL, &count);
CU_ASSERT(rc == -ENOMEM);
CU_ASSERT(count == 2);
/* incorrect array size */
count = 1;
rc = spdk_blob_get_clones(bs, snapshotid, ids, &count);
CU_ASSERT(rc == -ENOMEM);
CU_ASSERT(count == 2);
/* Verify structure of loaded blob store */
/* snapshot */
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, snapshotid) == SPDK_BLOBID_INVALID);
count = SPDK_COUNTOF(ids);
rc = spdk_blob_get_clones(bs, snapshotid, ids, &count);
CU_ASSERT(rc == 0);
CU_ASSERT(count == 2);
CU_ASSERT(ids[0] == blobid || ids[1] == blobid);
CU_ASSERT(ids[0] == snapshotid2 || ids[1] == snapshotid2);
/* blob */
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, blobid) == snapshotid);
count = SPDK_COUNTOF(ids);
rc = spdk_blob_get_clones(bs, blobid, ids, &count);
CU_ASSERT(rc == 0);
CU_ASSERT(count == 1);
CU_ASSERT(ids[0] == cloneid2);
/* clone */
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, cloneid) == snapshotid2);
count = SPDK_COUNTOF(ids);
rc = spdk_blob_get_clones(bs, cloneid, ids, &count);
CU_ASSERT(rc == 0);
CU_ASSERT(count == 0);
/* snapshot2 */
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, snapshotid2) == snapshotid);
count = SPDK_COUNTOF(ids);
rc = spdk_blob_get_clones(bs, snapshotid2, ids, &count);
CU_ASSERT(rc == 0);
CU_ASSERT(count == 1);
CU_ASSERT(ids[0] == cloneid);
/* clone2 */
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, cloneid2) == blobid);
count = SPDK_COUNTOF(ids);
rc = spdk_blob_get_clones(bs, cloneid2, ids, &count);
CU_ASSERT(rc == 0);
CU_ASSERT(count == 0);
/* Try to delete blob that user should not be able to remove */
spdk_bs_delete_blob(bs, snapshotid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno != 0);
/* Remove all blobs */
spdk_bs_delete_blob(bs, cloneid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_delete_blob(bs, snapshotid2, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_delete_blob(bs, cloneid2, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_delete_blob(bs, blobid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_delete_blob(bs, snapshotid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_unload(bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
/**
* Snapshot-clones relation test 2
*
* snapshot1
* |
* snapshot2
* |
* +-----+-----+
* | |
* blob(ro) snapshot3
* | |
* | snapshot4
* | | |
* clone2 clone clone3
*/
static void
blob_relations2(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_bs_opts bs_opts;
struct spdk_blob_opts opts;
struct spdk_blob *blob, *snapshot1, *snapshot2, *snapshot3, *snapshot4, *clone, *clone2;
spdk_blob_id blobid, snapshotid1, snapshotid2, snapshotid3, snapshotid4, cloneid, cloneid2,
cloneid3;
int rc;
size_t count;
spdk_blob_id ids[10] = {};
dev = init_dev();
spdk_bs_opts_init(&bs_opts);
snprintf(bs_opts.bstype.bstype, sizeof(bs_opts.bstype.bstype), "TESTTYPE");
spdk_bs_init(dev, &bs_opts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
/* 1. Create blob with 10 clusters */
spdk_blob_opts_init(&opts);
opts.num_clusters = 10;
spdk_bs_create_blob_ext(bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
/* 2. Create snapshot1 */
spdk_bs_create_snapshot(bs, blobid, NULL, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
snapshotid1 = g_blobid;
spdk_bs_open_blob(bs, snapshotid1, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
snapshot1 = g_blob;
CU_ASSERT(snapshot1->parent_id == SPDK_BLOBID_INVALID);
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, snapshotid1) == SPDK_BLOBID_INVALID);
CU_ASSERT(blob->parent_id == snapshotid1);
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, blobid) == snapshotid1);
/* Check if blob is the clone of snapshot1 */
CU_ASSERT(blob->parent_id == snapshotid1);
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, blobid) == snapshotid1);
count = SPDK_COUNTOF(ids);
rc = spdk_blob_get_clones(bs, snapshotid1, ids, &count);
CU_ASSERT(rc == 0);
CU_ASSERT(count == 1);
CU_ASSERT(ids[0] == blobid);
/* 3. Create another snapshot */
spdk_bs_create_snapshot(bs, blobid, NULL, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
snapshotid2 = g_blobid;
spdk_bs_open_blob(bs, snapshotid2, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
snapshot2 = g_blob;
CU_ASSERT(spdk_blob_is_clone(snapshot2));
CU_ASSERT(snapshot2->parent_id == snapshotid1);
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, snapshotid2) == snapshotid1);
/* Check if snapshot2 is the clone of snapshot1 and blob
* is a child of snapshot2 */
CU_ASSERT(blob->parent_id == snapshotid2);
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, blobid) == snapshotid2);
count = SPDK_COUNTOF(ids);
rc = spdk_blob_get_clones(bs, snapshotid2, ids, &count);
CU_ASSERT(rc == 0);
CU_ASSERT(count == 1);
CU_ASSERT(ids[0] == blobid);
/* 4. Create clone from snapshot */
spdk_bs_create_clone(bs, snapshotid2, NULL, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
cloneid = g_blobid;
spdk_bs_open_blob(bs, cloneid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
clone = g_blob;
CU_ASSERT(clone->parent_id == snapshotid2);
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, cloneid) == snapshotid2);
/* Check if clone is on the snapshot's list */
count = SPDK_COUNTOF(ids);
rc = spdk_blob_get_clones(bs, snapshotid2, ids, &count);
CU_ASSERT(rc == 0);
CU_ASSERT(count == 2);
CU_ASSERT(ids[0] == blobid || ids[1] == blobid);
CU_ASSERT(ids[0] == cloneid || ids[1] == cloneid);
/* 5. Create snapshot of the clone */
spdk_bs_create_snapshot(bs, cloneid, NULL, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
snapshotid3 = g_blobid;
spdk_bs_open_blob(bs, snapshotid3, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
snapshot3 = g_blob;
CU_ASSERT(snapshot3->parent_id == snapshotid2);
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, snapshotid3) == snapshotid2);
/* Check if clone is converted to the clone of snapshot3 and snapshot3
* is a child of snapshot2 */
CU_ASSERT(clone->parent_id == snapshotid3);
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, cloneid) == snapshotid3);
count = SPDK_COUNTOF(ids);
rc = spdk_blob_get_clones(bs, snapshotid3, ids, &count);
CU_ASSERT(rc == 0);
CU_ASSERT(count == 1);
CU_ASSERT(ids[0] == cloneid);
/* 6. Create another snapshot of the clone */
spdk_bs_create_snapshot(bs, cloneid, NULL, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
snapshotid4 = g_blobid;
spdk_bs_open_blob(bs, snapshotid4, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
snapshot4 = g_blob;
CU_ASSERT(snapshot4->parent_id == snapshotid3);
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, snapshotid4) == snapshotid3);
/* Check if clone is converted to the clone of snapshot4 and snapshot4
* is a child of snapshot3 */
CU_ASSERT(clone->parent_id == snapshotid4);
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, cloneid) == snapshotid4);
count = SPDK_COUNTOF(ids);
rc = spdk_blob_get_clones(bs, snapshotid4, ids, &count);
CU_ASSERT(rc == 0);
CU_ASSERT(count == 1);
CU_ASSERT(ids[0] == cloneid);
/* 7. Remove snapshot 4 */
spdk_blob_close(snapshot4, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_delete_blob(bs, snapshotid4, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Check if relations are back to state from before creating snapshot 4 */
CU_ASSERT(clone->parent_id == snapshotid3);
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, cloneid) == snapshotid3);
count = SPDK_COUNTOF(ids);
rc = spdk_blob_get_clones(bs, snapshotid3, ids, &count);
CU_ASSERT(rc == 0);
CU_ASSERT(count == 1);
CU_ASSERT(ids[0] == cloneid);
/* 8. Create second clone of snapshot 3 and try to remove snapshot 3 */
spdk_bs_create_clone(bs, snapshotid3, NULL, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
cloneid3 = g_blobid;
spdk_bs_delete_blob(bs, snapshotid3, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno != 0);
/* 9. Open snapshot 3 again and try to remove it while clone 3 is closed */
spdk_bs_open_blob(bs, snapshotid3, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
snapshot3 = g_blob;
spdk_bs_delete_blob(bs, snapshotid3, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno != 0);
spdk_blob_close(snapshot3, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_delete_blob(bs, cloneid3, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* 10. Remove snapshot 1 */
spdk_blob_close(snapshot1, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_delete_blob(bs, snapshotid1, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Check if relations are back to state from before creating snapshot 4 (before step 6) */
CU_ASSERT(snapshot2->parent_id == SPDK_BLOBID_INVALID);
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, snapshotid2) == SPDK_BLOBID_INVALID);
count = SPDK_COUNTOF(ids);
rc = spdk_blob_get_clones(bs, snapshotid2, ids, &count);
CU_ASSERT(rc == 0);
CU_ASSERT(count == 2);
CU_ASSERT(ids[0] == blobid || ids[1] == blobid);
CU_ASSERT(ids[0] == snapshotid3 || ids[1] == snapshotid3);
/* 11. Try to create clone from read only blob */
/* Mark blob as read only */
spdk_blob_set_read_only(blob);
spdk_blob_sync_md(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Create clone from read only blob */
spdk_bs_create_clone(bs, blobid, NULL, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
cloneid2 = g_blobid;
spdk_bs_open_blob(bs, cloneid2, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
clone2 = g_blob;
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, cloneid2) == blobid);
count = SPDK_COUNTOF(ids);
rc = spdk_blob_get_clones(bs, blobid, ids, &count);
CU_ASSERT(rc == 0);
CU_ASSERT(count == 1);
CU_ASSERT(ids[0] == cloneid2);
/* Close blobs */
spdk_blob_close(clone2, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_blob_close(clone, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_blob_close(snapshot2, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_blob_close(snapshot3, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_unload(bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
/* Load an existing blob store */
dev = init_dev();
snprintf(bs_opts.bstype.bstype, sizeof(bs_opts.bstype.bstype), "TESTTYPE");
spdk_bs_load(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
/* Verify structure of loaded blob store */
/* snapshot2 */
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, snapshotid2) == SPDK_BLOBID_INVALID);
count = SPDK_COUNTOF(ids);
rc = spdk_blob_get_clones(bs, snapshotid2, ids, &count);
CU_ASSERT(rc == 0);
CU_ASSERT(count == 2);
CU_ASSERT(ids[0] == blobid || ids[1] == blobid);
CU_ASSERT(ids[0] == snapshotid3 || ids[1] == snapshotid3);
/* blob */
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, blobid) == snapshotid2);
count = SPDK_COUNTOF(ids);
rc = spdk_blob_get_clones(bs, blobid, ids, &count);
CU_ASSERT(rc == 0);
CU_ASSERT(count == 1);
CU_ASSERT(ids[0] == cloneid2);
/* clone */
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, cloneid) == snapshotid3);
count = SPDK_COUNTOF(ids);
rc = spdk_blob_get_clones(bs, cloneid, ids, &count);
CU_ASSERT(rc == 0);
CU_ASSERT(count == 0);
/* snapshot3 */
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, snapshotid3) == snapshotid2);
count = SPDK_COUNTOF(ids);
rc = spdk_blob_get_clones(bs, snapshotid3, ids, &count);
CU_ASSERT(rc == 0);
CU_ASSERT(count == 1);
CU_ASSERT(ids[0] == cloneid);
/* clone2 */
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, cloneid2) == blobid);
count = SPDK_COUNTOF(ids);
rc = spdk_blob_get_clones(bs, cloneid2, ids, &count);
CU_ASSERT(rc == 0);
CU_ASSERT(count == 0);
/* Try to delete all blobs in the worse possible order */
spdk_bs_delete_blob(bs, snapshotid2, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno != 0);
spdk_bs_delete_blob(bs, snapshotid3, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_delete_blob(bs, snapshotid2, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno != 0);
spdk_bs_delete_blob(bs, cloneid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_delete_blob(bs, snapshotid2, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_delete_blob(bs, blobid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_delete_blob(bs, cloneid2, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_unload(bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
blob_delete_snapshot_power_failure(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob_opts opts;
struct spdk_blob *blob, *snapshot;
struct spdk_power_failure_thresholds thresholds = {};
spdk_blob_id blobid, snapshotid;
const void *value;
size_t value_len;
size_t count;
spdk_blob_id ids[3] = {};
int rc;
bool deleted = false;
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
/* Create blob */
spdk_blob_opts_init(&opts);
opts.num_clusters = 10;
spdk_bs_create_blob_ext(bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
/* Create snapshot */
spdk_bs_create_snapshot(bs, blobid, NULL, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
snapshotid = g_blobid;
thresholds.general_threshold = 1;
while (!deleted) {
dev_set_power_failure_thresholds(thresholds);
spdk_bs_delete_blob(bs, snapshotid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno != 0);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
dev_reset_power_failure_event();
dev = init_dev();
spdk_bs_load(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
spdk_bs_open_blob(bs, snapshotid, blob_op_with_handle_complete, NULL);
poll_threads();
if (g_bserrno == 0) {
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
snapshot = g_blob;
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, blobid) == snapshotid);
count = SPDK_COUNTOF(ids);
rc = spdk_blob_get_clones(bs, snapshotid, ids, &count);
CU_ASSERT(rc == 0);
CU_ASSERT(count == 1);
CU_ASSERT(ids[0] == blobid);
rc = spdk_blob_get_xattr_value(snapshot, SNAPSHOT_PENDING_REMOVAL, &value, &value_len);
CU_ASSERT(rc != 0);
spdk_blob_close(snapshot, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
} else {
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, blobid) == SPDK_BLOBID_INVALID);
deleted = true;
}
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Reload blobstore to have the same starting conditions (as the previous blobstore load
* may trigger cleanup after power failure or may not) */
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
dev = init_dev();
spdk_bs_load(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
thresholds.general_threshold++;
}
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
blob_create_snapshot_power_failure(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob_opts opts;
struct spdk_blob *blob, *snapshot;
struct spdk_power_failure_thresholds thresholds = {};
spdk_blob_id blobid, snapshotid;
const void *value;
size_t value_len;
size_t count;
spdk_blob_id ids[3] = {};
int rc;
bool created = false;
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
/* Create blob */
spdk_blob_opts_init(&opts);
opts.num_clusters = 10;
spdk_bs_create_blob_ext(bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
thresholds.general_threshold = 1;
while (!created) {
dev_set_power_failure_thresholds(thresholds);
/* Create snapshot */
spdk_bs_create_snapshot(bs, blobid, NULL, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno != 0);
snapshotid = g_blobid;
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
dev_reset_power_failure_event();
dev = init_dev();
spdk_bs_load(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
if (snapshotid != SPDK_BLOBID_INVALID) {
spdk_bs_open_blob(bs, snapshotid, blob_op_with_handle_complete, NULL);
poll_threads();
}
if ((snapshotid != SPDK_BLOBID_INVALID) && (g_bserrno == 0)) {
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
snapshot = g_blob;
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, blobid) == snapshotid);
count = SPDK_COUNTOF(ids);
rc = spdk_blob_get_clones(bs, snapshotid, ids, &count);
CU_ASSERT(rc == 0);
CU_ASSERT(count == 1);
CU_ASSERT(ids[0] == blobid);
rc = spdk_blob_get_xattr_value(snapshot, SNAPSHOT_IN_PROGRESS, &value, &value_len);
CU_ASSERT(rc != 0);
spdk_blob_close(snapshot, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
created = true;
} else {
CU_ASSERT(spdk_blob_get_parent_snapshot(bs, blobid) == SPDK_BLOBID_INVALID);
CU_ASSERT(!(blob->invalid_flags & SPDK_BLOB_THIN_PROV));
}
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Reload blobstore to have the same starting conditions (as the previous blobstore load
* may trigger cleanup after power failure or may not) */
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
dev = init_dev();
spdk_bs_load(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
thresholds.general_threshold++;
}
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
}
static void
test_io_write(struct spdk_bs_dev *dev, struct spdk_blob *blob, struct spdk_io_channel *channel)
{
uint8_t payload_ff[64 * 512];
uint8_t payload_aa[64 * 512];
uint8_t payload_00[64 * 512];
uint8_t *cluster0, *cluster1;
memset(payload_ff, 0xFF, sizeof(payload_ff));
memset(payload_aa, 0xAA, sizeof(payload_aa));
memset(payload_00, 0x00, sizeof(payload_00));
/* Try to perform I/O with io unit = 512 */
spdk_blob_io_write(blob, channel, payload_ff, 0, 1, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* If thin provisioned is set cluster should be allocated now */
SPDK_CU_ASSERT_FATAL(blob->active.clusters[0] != 0);
cluster0 = &g_dev_buffer[blob->active.clusters[0] * dev->blocklen];
/* Each character 0-F symbolizes single io_unit containing 512 bytes block filled with that character.
* Each page is separated by |. Whole block [...] symbolizes one cluster (containing 4 pages). */
/* cluster0: [ F000 0000 | 0000 0000 | 0000 0000 | 0000 0000 ] */
CU_ASSERT(memcmp(cluster0 + 0 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 1 * 512, payload_00, 31 * 512) == 0);
/* Verify write with offset on first page */
spdk_blob_io_write(blob, channel, payload_ff, 2, 1, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* cluster0: [ F0F0 0000 | 0000 0000 | 0000 0000 | 0000 0000 ] */
CU_ASSERT(memcmp(cluster0 + 0 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 1 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 2 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 3 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 4 * 512, payload_00, 28 * 512) == 0);
/* Verify write with offset on first page */
spdk_blob_io_write(blob, channel, payload_ff, 4, 4, blob_op_complete, NULL);
poll_threads();
/* cluster0: [ F0F0 FFFF | 0000 0000 | 0000 0000 | 0000 0000 ] */
CU_ASSERT(memcmp(cluster0 + 0 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 1 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 2 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 3 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 4 * 512, payload_ff, 4 * 512) == 0);
CU_ASSERT(memcmp(cluster0 + 8 * 512, payload_00, 24 * 512) == 0);
/* Verify write with offset on second page */
spdk_blob_io_write(blob, channel, payload_ff, 8, 4, blob_op_complete, NULL);
poll_threads();
/* cluster0: [ F0F0 FFFF | FFFF 0000 | 0000 0000 | 0000 0000 ] */
CU_ASSERT(memcmp(cluster0 + 0 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 1 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 2 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 3 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 4 * 512, payload_ff, 8 * 512) == 0);
CU_ASSERT(memcmp(cluster0 + 12 * 512, payload_00, 20 * 512) == 0);
/* Verify write across multiple pages */
spdk_blob_io_write(blob, channel, payload_aa, 4, 8, blob_op_complete, NULL);
poll_threads();
/* cluster0: [ F0F0 AAAA | AAAA 0000 | 0000 0000 | 0000 0000 ] */
CU_ASSERT(memcmp(cluster0 + 0 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 1 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 2 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 3 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 4 * 512, payload_aa, 8 * 512) == 0);
CU_ASSERT(memcmp(cluster0 + 12 * 512, payload_00, 20 * 512) == 0);
/* Verify write across multiple clusters */
spdk_blob_io_write(blob, channel, payload_ff, 28, 8, blob_op_complete, NULL);
poll_threads();
SPDK_CU_ASSERT_FATAL(blob->active.clusters[1] != 0);
cluster1 = &g_dev_buffer[blob->active.clusters[1] * dev->blocklen];
/* cluster0: [ F0F0 AAAA | AAAA 0000 | 0000 0000 | 0000 FFFF ]
* cluster1: [ FFFF 0000 | 0000 0000 | 0000 0000 | 0000 0000 ] */
CU_ASSERT(memcmp(cluster0 + 0 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 1 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 2 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 3 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 4 * 512, payload_aa, 8 * 512) == 0);
CU_ASSERT(memcmp(cluster0 + 28 * 512, payload_ff, 4 * 512) == 0);
CU_ASSERT(memcmp(cluster1 + 0 * 512, payload_ff, 4 * 512) == 0);
CU_ASSERT(memcmp(cluster1 + 4 * 512, payload_00, 28 * 512) == 0);
/* Verify write to second cluster */
spdk_blob_io_write(blob, channel, payload_ff, 32 + 12, 2, blob_op_complete, NULL);
poll_threads();
SPDK_CU_ASSERT_FATAL(blob->active.clusters[1] != 0);
cluster1 = &g_dev_buffer[blob->active.clusters[1] * dev->blocklen];
/* cluster0: [ F0F0 AAAA | AAAA 0000 | 0000 0000 | 0000 FFFF ]
* cluster1: [ FFFF 0000 | 0000 FF00 | 0000 0000 | 0000 0000 ] */
CU_ASSERT(memcmp(cluster0 + 0 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 1 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 2 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 3 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 4 * 512, payload_aa, 8 * 512) == 0);
CU_ASSERT(memcmp(cluster0 + 28 * 512, payload_ff, 4 * 512) == 0);
CU_ASSERT(memcmp(cluster1 + 0 * 512, payload_ff, 4 * 512) == 0);
CU_ASSERT(memcmp(cluster1 + 4 * 512, payload_00, 8 * 512) == 0);
CU_ASSERT(memcmp(cluster1 + 12 * 512, payload_ff, 2 * 512) == 0);
CU_ASSERT(memcmp(cluster1 + 14 * 512, payload_00, 18 * 512) == 0);
}
static void
test_io_read(struct spdk_bs_dev *dev, struct spdk_blob *blob, struct spdk_io_channel *channel)
{
uint8_t payload_read[64 * 512];
uint8_t payload_ff[64 * 512];
uint8_t payload_aa[64 * 512];
uint8_t payload_00[64 * 512];
memset(payload_ff, 0xFF, sizeof(payload_ff));
memset(payload_aa, 0xAA, sizeof(payload_aa));
memset(payload_00, 0x00, sizeof(payload_00));
/* Read only first io unit */
/* cluster0: [ (F)0F0 AAAA | AAAA 0000 | 0000 0000 | 0000 FFFF ]
* cluster1: [ FFFF 0000 | 0000 FF00 | 0000 0000 | 0000 0000 ]
* payload_read: F000 0000 | 0000 0000 ... */
memset(payload_read, 0x00, sizeof(payload_read));
spdk_blob_io_read(blob, channel, payload_read, 0, 1, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_read + 0 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(payload_read + 1 * 512, payload_00, 31 * 512) == 0);
/* Read four io_units starting from offset = 2
* cluster0: [ F0(F0 AA)AA | AAAA 0000 | 0000 0000 | 0000 FFFF ]
* cluster1: [ FFFF 0000 | 0000 FF00 | 0000 0000 | 0000 0000 ]
* payload_read: F0AA 0000 | 0000 0000 ... */
memset(payload_read, 0x00, sizeof(payload_read));
spdk_blob_io_read(blob, channel, payload_read, 2, 4, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_read + 0 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(payload_read + 1 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(payload_read + 2 * 512, payload_aa, 512) == 0);
CU_ASSERT(memcmp(payload_read + 3 * 512, payload_aa, 512) == 0);
CU_ASSERT(memcmp(payload_read + 4 * 512, payload_00, 28 * 512) == 0);
/* Read eight io_units across multiple pages
* cluster0: [ F0F0 (AAAA | AAAA) 0000 | 0000 0000 | 0000 FFFF ]
* cluster1: [ FFFF 0000 | 0000 FF00 | 0000 0000 | 0000 0000 ]
* payload_read: AAAA AAAA | 0000 0000 ... */
memset(payload_read, 0x00, sizeof(payload_read));
spdk_blob_io_read(blob, channel, payload_read, 4, 8, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_read + 0 * 512, payload_aa, 8 * 512) == 0);
CU_ASSERT(memcmp(payload_read + 8 * 512, payload_00, 24 * 512) == 0);
/* Read eight io_units across multiple clusters
* cluster0: [ F0F0 AAAA | AAAA 0000 | 0000 0000 | 0000 (FFFF ]
* cluster1: [ FFFF) 0000 | 0000 FF00 | 0000 0000 | 0000 0000 ]
* payload_read: FFFF FFFF | 0000 0000 ... */
memset(payload_read, 0x00, sizeof(payload_read));
spdk_blob_io_read(blob, channel, payload_read, 28, 8, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_read + 0 * 512, payload_ff, 8 * 512) == 0);
CU_ASSERT(memcmp(payload_read + 8 * 512, payload_00, 24 * 512) == 0);
/* Read four io_units from second cluster
* cluster0: [ F0F0 AAAA | AAAA 0000 | 0000 0000 | 0000 FFFF ]
* cluster1: [ FFFF 0000 | 00(00 FF)00 | 0000 0000 | 0000 0000 ]
* payload_read: 00FF 0000 | 0000 0000 ... */
memset(payload_read, 0x00, sizeof(payload_read));
spdk_blob_io_read(blob, channel, payload_read, 32 + 10, 4, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_read + 0 * 512, payload_00, 2 * 512) == 0);
CU_ASSERT(memcmp(payload_read + 2 * 512, payload_ff, 2 * 512) == 0);
CU_ASSERT(memcmp(payload_read + 4 * 512, payload_00, 28 * 512) == 0);
/* Read second cluster
* cluster0: [ F0F0 AAAA | AAAA 0000 | 0000 0000 | 0000 FFFF ]
* cluster1: [ (FFFF 0000 | 0000 FF00 | 0000 0000 | 0000 0000) ]
* payload_read: FFFF 0000 | 0000 FF00 ... */
memset(payload_read, 0x00, sizeof(payload_read));
spdk_blob_io_read(blob, channel, payload_read, 32, 32, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_read + 0 * 512, payload_ff, 4 * 512) == 0);
CU_ASSERT(memcmp(payload_read + 4 * 512, payload_00, 8 * 512) == 0);
CU_ASSERT(memcmp(payload_read + 12 * 512, payload_ff, 2 * 512) == 0);
CU_ASSERT(memcmp(payload_read + 14 * 512, payload_00, 18 * 512) == 0);
/* Read whole two clusters
* cluster0: [ (F0F0 AAAA | AAAA) 0000 | 0000 0000 | 0000 FFFF ]
* cluster1: [ FFFF 0000 | 0000 FF00 | 0000 0000 | 0000 0000) ] */
memset(payload_read, 0x00, sizeof(payload_read));
spdk_blob_io_read(blob, channel, payload_read, 0, 64, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_read + 0 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(payload_read + 1 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(payload_read + 2 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(payload_read + 3 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(payload_read + 4 * 512, payload_aa, 8 * 512) == 0);
CU_ASSERT(memcmp(payload_read + 28 * 512, payload_ff, 4 * 512) == 0);
CU_ASSERT(memcmp(payload_read + (32 + 0) * 512, payload_ff, 4 * 512) == 0);
CU_ASSERT(memcmp(payload_read + (32 + 4) * 512, payload_00, 8 * 512) == 0);
CU_ASSERT(memcmp(payload_read + (32 + 12) * 512, payload_ff, 2 * 512) == 0);
CU_ASSERT(memcmp(payload_read + (32 + 14) * 512, payload_00, 18 * 512) == 0);
}
static void
test_io_unmap(struct spdk_bs_dev *dev, struct spdk_blob *blob, struct spdk_io_channel *channel)
{
uint8_t payload_ff[64 * 512];
uint8_t payload_aa[64 * 512];
uint8_t payload_00[64 * 512];
uint8_t *cluster0, *cluster1;
memset(payload_ff, 0xFF, sizeof(payload_ff));
memset(payload_aa, 0xAA, sizeof(payload_aa));
memset(payload_00, 0x00, sizeof(payload_00));
cluster0 = &g_dev_buffer[blob->active.clusters[0] * dev->blocklen];
cluster1 = &g_dev_buffer[blob->active.clusters[1] * dev->blocklen];
/* Unmap */
spdk_blob_io_unmap(blob, channel, 0, 64, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(cluster0 + 0 * 512, payload_00, 32 * 512) == 0);
CU_ASSERT(memcmp(cluster1 + 0 * 512, payload_00, 32 * 512) == 0);
}
static void
test_io_zeroes(struct spdk_bs_dev *dev, struct spdk_blob *blob, struct spdk_io_channel *channel)
{
uint8_t payload_ff[64 * 512];
uint8_t payload_aa[64 * 512];
uint8_t payload_00[64 * 512];
uint8_t *cluster0, *cluster1;
memset(payload_ff, 0xFF, sizeof(payload_ff));
memset(payload_aa, 0xAA, sizeof(payload_aa));
memset(payload_00, 0x00, sizeof(payload_00));
cluster0 = &g_dev_buffer[blob->active.clusters[0] * dev->blocklen];
cluster1 = &g_dev_buffer[blob->active.clusters[1] * dev->blocklen];
/* Write zeroes */
spdk_blob_io_write_zeroes(blob, channel, 0, 64, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(cluster0 + 0 * 512, payload_00, 32 * 512) == 0);
CU_ASSERT(memcmp(cluster1 + 0 * 512, payload_00, 32 * 512) == 0);
}
static void
test_iov_write(struct spdk_bs_dev *dev, struct spdk_blob *blob, struct spdk_io_channel *channel)
{
uint8_t payload_ff[64 * 512];
uint8_t payload_aa[64 * 512];
uint8_t payload_00[64 * 512];
uint8_t *cluster0, *cluster1;
struct iovec iov[4];
memset(payload_ff, 0xFF, sizeof(payload_ff));
memset(payload_aa, 0xAA, sizeof(payload_aa));
memset(payload_00, 0x00, sizeof(payload_00));
/* Try to perform I/O with io unit = 512 */
iov[0].iov_base = payload_ff;
iov[0].iov_len = 1 * 512;
spdk_blob_io_writev(blob, channel, iov, 1, 0, 1, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* If thin provisioned is set cluster should be allocated now */
SPDK_CU_ASSERT_FATAL(blob->active.clusters[0] != 0);
cluster0 = &g_dev_buffer[blob->active.clusters[0] * dev->blocklen];
/* Each character 0-F symbolizes single io_unit containing 512 bytes block filled with that character.
* Each page is separated by |. Whole block [...] symbolizes one cluster (containing 4 pages). */
/* cluster0: [ F000 0000 | 0000 0000 | 0000 0000 | 0000 0000 ] */
CU_ASSERT(memcmp(cluster0 + 0 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 1 * 512, payload_00, 31 * 512) == 0);
/* Verify write with offset on first page */
iov[0].iov_base = payload_ff;
iov[0].iov_len = 1 * 512;
spdk_blob_io_writev(blob, channel, iov, 1, 2, 1, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* cluster0: [ F0F0 0000 | 0000 0000 | 0000 0000 | 0000 0000 ] */
CU_ASSERT(memcmp(cluster0 + 0 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 1 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 2 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 3 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 4 * 512, payload_00, 28 * 512) == 0);
/* Verify write with offset on first page */
iov[0].iov_base = payload_ff;
iov[0].iov_len = 4 * 512;
spdk_blob_io_writev(blob, channel, iov, 1, 4, 4, blob_op_complete, NULL);
poll_threads();
/* cluster0: [ F0F0 FFFF | 0000 0000 | 0000 0000 | 0000 0000 ] */
CU_ASSERT(memcmp(cluster0 + 0 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 1 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 2 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 3 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 4 * 512, payload_ff, 4 * 512) == 0);
CU_ASSERT(memcmp(cluster0 + 8 * 512, payload_00, 24 * 512) == 0);
/* Verify write with offset on second page */
iov[0].iov_base = payload_ff;
iov[0].iov_len = 4 * 512;
spdk_blob_io_writev(blob, channel, iov, 1, 8, 4, blob_op_complete, NULL);
poll_threads();
/* cluster0: [ F0F0 FFFF | FFFF 0000 | 0000 0000 | 0000 0000 ] */
CU_ASSERT(memcmp(cluster0 + 0 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 1 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 2 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 3 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 4 * 512, payload_ff, 8 * 512) == 0);
CU_ASSERT(memcmp(cluster0 + 12 * 512, payload_00, 20 * 512) == 0);
/* Verify write across multiple pages */
iov[0].iov_base = payload_aa;
iov[0].iov_len = 8 * 512;
spdk_blob_io_writev(blob, channel, iov, 1, 4, 8, blob_op_complete, NULL);
poll_threads();
/* cluster0: [ F0F0 AAAA | AAAA 0000 | 0000 0000 | 0000 0000 ] */
CU_ASSERT(memcmp(cluster0 + 0 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 1 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 2 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 3 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 4 * 512, payload_aa, 8 * 512) == 0);
CU_ASSERT(memcmp(cluster0 + 12 * 512, payload_00, 20 * 512) == 0);
/* Verify write across multiple clusters */
iov[0].iov_base = payload_ff;
iov[0].iov_len = 8 * 512;
spdk_blob_io_writev(blob, channel, iov, 1, 28, 8, blob_op_complete, NULL);
poll_threads();
SPDK_CU_ASSERT_FATAL(blob->active.clusters[1] != 0);
cluster1 = &g_dev_buffer[blob->active.clusters[1] * dev->blocklen];
/* cluster0: [ F0F0 AAAA | AAAA 0000 | 0000 0000 | 0000 FFFF ]
* cluster1: [ FFFF 0000 | 0000 0000 | 0000 0000 | 0000 0000 ] */
CU_ASSERT(memcmp(cluster0 + 0 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 1 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 2 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 3 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 4 * 512, payload_aa, 8 * 512) == 0);
CU_ASSERT(memcmp(cluster0 + 12 * 512, payload_00, 16 * 512) == 0);
CU_ASSERT(memcmp(cluster0 + 28 * 512, payload_ff, 4 * 512) == 0);
CU_ASSERT(memcmp(cluster1 + 0 * 512, payload_ff, 4 * 512) == 0);
CU_ASSERT(memcmp(cluster1 + 4 * 512, payload_00, 28 * 512) == 0);
/* Verify write to second cluster */
iov[0].iov_base = payload_ff;
iov[0].iov_len = 2 * 512;
spdk_blob_io_writev(blob, channel, iov, 1, 32 + 12, 2, blob_op_complete, NULL);
poll_threads();
SPDK_CU_ASSERT_FATAL(blob->active.clusters[1] != 0);
cluster1 = &g_dev_buffer[blob->active.clusters[1] * dev->blocklen];
/* cluster0: [ F0F0 AAAA | AAAA 0000 | 0000 0000 | 0000 FFFF ]
* cluster1: [ FFFF 0000 | 0000 FF00 | 0000 0000 | 0000 0000 ] */
CU_ASSERT(memcmp(cluster0 + 0 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 1 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 2 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 3 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(cluster0 + 4 * 512, payload_aa, 8 * 512) == 0);
CU_ASSERT(memcmp(cluster0 + 28 * 512, payload_ff, 4 * 512) == 0);
CU_ASSERT(memcmp(cluster1 + 0 * 512, payload_ff, 4 * 512) == 0);
CU_ASSERT(memcmp(cluster1 + 4 * 512, payload_00, 8 * 512) == 0);
CU_ASSERT(memcmp(cluster1 + 12 * 512, payload_ff, 2 * 512) == 0);
CU_ASSERT(memcmp(cluster1 + 14 * 512, payload_00, 18 * 512) == 0);
}
static void
test_iov_read(struct spdk_bs_dev *dev, struct spdk_blob *blob, struct spdk_io_channel *channel)
{
uint8_t payload_read[64 * 512];
uint8_t payload_ff[64 * 512];
uint8_t payload_aa[64 * 512];
uint8_t payload_00[64 * 512];
struct iovec iov[4];
memset(payload_ff, 0xFF, sizeof(payload_ff));
memset(payload_aa, 0xAA, sizeof(payload_aa));
memset(payload_00, 0x00, sizeof(payload_00));
/* Read only first io unit */
/* cluster0: [ (F)0F0 AAAA | AAAA 0000 | 0000 0000 | 0000 FFFF ]
* cluster1: [ FFFF 0000 | 0000 FF00 | 0000 0000 | 0000 0000 ]
* payload_read: F000 0000 | 0000 0000 ... */
memset(payload_read, 0x00, sizeof(payload_read));
iov[0].iov_base = payload_read;
iov[0].iov_len = 1 * 512;
spdk_blob_io_readv(blob, channel, iov, 1, 0, 1, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_read + 0 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(payload_read + 1 * 512, payload_00, 31 * 512) == 0);
/* Read four io_units starting from offset = 2
* cluster0: [ F0(F0 AA)AA | AAAA 0000 | 0000 0000 | 0000 FFFF ]
* cluster1: [ FFFF 0000 | 0000 FF00 | 0000 0000 | 0000 0000 ]
* payload_read: F0AA 0000 | 0000 0000 ... */
memset(payload_read, 0x00, sizeof(payload_read));
iov[0].iov_base = payload_read;
iov[0].iov_len = 4 * 512;
spdk_blob_io_readv(blob, channel, iov, 1, 2, 4, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_read + 0 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(payload_read + 1 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(payload_read + 2 * 512, payload_aa, 512) == 0);
CU_ASSERT(memcmp(payload_read + 3 * 512, payload_aa, 512) == 0);
CU_ASSERT(memcmp(payload_read + 4 * 512, payload_00, 28 * 512) == 0);
/* Read eight io_units across multiple pages
* cluster0: [ F0F0 (AAAA | AAAA) 0000 | 0000 0000 | 0000 FFFF ]
* cluster1: [ FFFF 0000 | 0000 FF00 | 0000 0000 | 0000 0000 ]
* payload_read: AAAA AAAA | 0000 0000 ... */
memset(payload_read, 0x00, sizeof(payload_read));
iov[0].iov_base = payload_read;
iov[0].iov_len = 4 * 512;
iov[1].iov_base = payload_read + 4 * 512;
iov[1].iov_len = 4 * 512;
spdk_blob_io_readv(blob, channel, iov, 2, 4, 8, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_read + 0 * 512, payload_aa, 8 * 512) == 0);
CU_ASSERT(memcmp(payload_read + 8 * 512, payload_00, 24 * 512) == 0);
/* Read eight io_units across multiple clusters
* cluster0: [ F0F0 AAAA | AAAA 0000 | 0000 0000 | 0000 (FFFF ]
* cluster1: [ FFFF) 0000 | 0000 FF00 | 0000 0000 | 0000 0000 ]
* payload_read: FFFF FFFF | 0000 0000 ... */
memset(payload_read, 0x00, sizeof(payload_read));
iov[0].iov_base = payload_read;
iov[0].iov_len = 2 * 512;
iov[1].iov_base = payload_read + 2 * 512;
iov[1].iov_len = 2 * 512;
iov[2].iov_base = payload_read + 4 * 512;
iov[2].iov_len = 2 * 512;
iov[3].iov_base = payload_read + 6 * 512;
iov[3].iov_len = 2 * 512;
spdk_blob_io_readv(blob, channel, iov, 4, 28, 8, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_read + 0 * 512, payload_ff, 8 * 512) == 0);
CU_ASSERT(memcmp(payload_read + 8 * 512, payload_00, 24 * 512) == 0);
/* Read four io_units from second cluster
* cluster0: [ F0F0 AAAA | AAAA 0000 | 0000 0000 | 0000 FFFF ]
* cluster1: [ FFFF 0000 | 00(00 FF)00 | 0000 0000 | 0000 0000 ]
* payload_read: 00FF 0000 | 0000 0000 ... */
memset(payload_read, 0x00, sizeof(payload_read));
iov[0].iov_base = payload_read;
iov[0].iov_len = 1 * 512;
iov[1].iov_base = payload_read + 1 * 512;
iov[1].iov_len = 3 * 512;
spdk_blob_io_readv(blob, channel, iov, 2, 32 + 10, 4, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_read + 0 * 512, payload_00, 2 * 512) == 0);
CU_ASSERT(memcmp(payload_read + 2 * 512, payload_ff, 2 * 512) == 0);
CU_ASSERT(memcmp(payload_read + 4 * 512, payload_00, 28 * 512) == 0);
/* Read second cluster
* cluster0: [ F0F0 AAAA | AAAA 0000 | 0000 0000 | 0000 FFFF ]
* cluster1: [ (FFFF 0000 | 0000 FF00 | 0000 0000 | 0000 0000) ]
* payload_read: FFFF 0000 | 0000 FF00 ... */
memset(payload_read, 0x00, sizeof(payload_read));
iov[0].iov_base = payload_read;
iov[0].iov_len = 1 * 512;
iov[1].iov_base = payload_read + 1 * 512;
iov[1].iov_len = 2 * 512;
iov[2].iov_base = payload_read + 3 * 512;
iov[2].iov_len = 4 * 512;
iov[3].iov_base = payload_read + 7 * 512;
iov[3].iov_len = 25 * 512;
spdk_blob_io_readv(blob, channel, iov, 4, 32, 32, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_read + 0 * 512, payload_ff, 4 * 512) == 0);
CU_ASSERT(memcmp(payload_read + 4 * 512, payload_00, 8 * 512) == 0);
CU_ASSERT(memcmp(payload_read + 12 * 512, payload_ff, 2 * 512) == 0);
CU_ASSERT(memcmp(payload_read + 14 * 512, payload_00, 18 * 512) == 0);
/* Read whole two clusters
* cluster0: [ (F0F0 AAAA | AAAA) 0000 | 0000 0000 | 0000 FFFF ]
* cluster1: [ FFFF 0000 | 0000 FF00 | 0000 0000 | 0000 0000) ] */
memset(payload_read, 0x00, sizeof(payload_read));
iov[0].iov_base = payload_read;
iov[0].iov_len = 1 * 512;
iov[1].iov_base = payload_read + 1 * 512;
iov[1].iov_len = 8 * 512;
iov[2].iov_base = payload_read + 9 * 512;
iov[2].iov_len = 16 * 512;
iov[3].iov_base = payload_read + 25 * 512;
iov[3].iov_len = 39 * 512;
spdk_blob_io_readv(blob, channel, iov, 4, 0, 64, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(memcmp(payload_read + 0 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(payload_read + 1 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(payload_read + 2 * 512, payload_ff, 512) == 0);
CU_ASSERT(memcmp(payload_read + 3 * 512, payload_00, 512) == 0);
CU_ASSERT(memcmp(payload_read + 4 * 512, payload_aa, 8 * 512) == 0);
CU_ASSERT(memcmp(payload_read + 28 * 512, payload_ff, 4 * 512) == 0);
CU_ASSERT(memcmp(payload_read + (32 + 0) * 512, payload_ff, 4 * 512) == 0);
CU_ASSERT(memcmp(payload_read + (32 + 4) * 512, payload_00, 8 * 512) == 0);
CU_ASSERT(memcmp(payload_read + (32 + 12) * 512, payload_ff, 2 * 512) == 0);
CU_ASSERT(memcmp(payload_read + (32 + 14) * 512, payload_00, 18 * 512) == 0);
}
static void
blob_io_unit(void)
{
struct spdk_bs_opts bsopts;
struct spdk_blob_opts opts;
struct spdk_bs_dev *dev;
struct spdk_blob *blob, *snapshot, *clone;
spdk_blob_id blobid;
struct spdk_io_channel *channel;
/* Create dev with 512 bytes io unit size */
spdk_bs_opts_init(&bsopts);
bsopts.cluster_sz = SPDK_BS_PAGE_SIZE * 4; /* 8 * 4 = 32 io_unit */
snprintf(bsopts.bstype.bstype, sizeof(bsopts.bstype.bstype), "TESTTYPE");
/* Try to initialize a new blob store with unsupported io_unit */
dev = init_dev();
dev->blocklen = 512;
dev->blockcnt = DEV_BUFFER_SIZE / dev->blocklen;
/* Initialize a new blob store */
spdk_bs_init(dev, &bsopts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
CU_ASSERT(spdk_bs_get_io_unit_size(g_bs) == 512);
channel = spdk_bs_alloc_io_channel(g_bs);
/* Create thick provisioned blob */
spdk_blob_opts_init(&opts);
opts.thin_provision = false;
opts.num_clusters = 32;
spdk_bs_create_blob_ext(g_bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(g_bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blob != NULL);
blob = g_blob;
test_io_write(dev, blob, channel);
test_io_read(dev, blob, channel);
test_io_zeroes(dev, blob, channel);
test_iov_write(dev, blob, channel);
test_iov_read(dev, blob, channel);
test_io_unmap(dev, blob, channel);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
blob = NULL;
g_blob = NULL;
/* Create thin provisioned blob */
spdk_blob_opts_init(&opts);
opts.thin_provision = true;
opts.num_clusters = 32;
spdk_bs_create_blob_ext(g_bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(g_bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blob != NULL);
blob = g_blob;
test_io_write(dev, blob, channel);
test_io_read(dev, blob, channel);
test_io_zeroes(dev, blob, channel);
test_iov_write(dev, blob, channel);
test_iov_read(dev, blob, channel);
/* Create snapshot */
spdk_bs_create_snapshot(g_bs, blobid, NULL, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(g_bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blob != NULL);
snapshot = g_blob;
spdk_bs_create_clone(g_bs, blobid, NULL, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(g_bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blob != NULL);
clone = g_blob;
test_io_read(dev, blob, channel);
test_io_read(dev, snapshot, channel);
test_io_read(dev, clone, channel);
test_iov_read(dev, blob, channel);
test_iov_read(dev, snapshot, channel);
test_iov_read(dev, clone, channel);
/* Inflate clone */
spdk_bs_inflate_blob(g_bs, channel, blobid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
test_io_read(dev, clone, channel);
test_io_unmap(dev, clone, channel);
test_iov_write(dev, clone, channel);
test_iov_read(dev, clone, channel);
spdk_blob_close(blob, blob_op_complete, NULL);
spdk_blob_close(snapshot, blob_op_complete, NULL);
spdk_blob_close(clone, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
blob = NULL;
g_blob = NULL;
/* Unload the blob store */
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
g_blob = NULL;
g_blobid = 0;
}
static void
blob_io_unit_compatiblity(void)
{
struct spdk_bs_opts bsopts;
struct spdk_bs_dev *dev;
struct spdk_bs_super_block *super;
/* Create dev with 512 bytes io unit size */
spdk_bs_opts_init(&bsopts);
bsopts.cluster_sz = SPDK_BS_PAGE_SIZE * 4; /* 8 * 4 = 32 io_unit */
snprintf(bsopts.bstype.bstype, sizeof(bsopts.bstype.bstype), "TESTTYPE");
/* Try to initialize a new blob store with unsupported io_unit */
dev = init_dev();
dev->blocklen = 512;
dev->blockcnt = DEV_BUFFER_SIZE / dev->blocklen;
/* Initialize a new blob store */
spdk_bs_init(dev, &bsopts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
CU_ASSERT(spdk_bs_get_io_unit_size(g_bs) == 512);
/* Unload the blob store */
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
/* Modify super block to behave like older version.
* Check if loaded io unit size equals SPDK_BS_PAGE_SIZE */
super = (struct spdk_bs_super_block *)&g_dev_buffer[0];
super->io_unit_size = 0;
super->crc = _spdk_blob_md_page_calc_crc(super);
dev = init_dev();
dev->blocklen = 512;
dev->blockcnt = DEV_BUFFER_SIZE / dev->blocklen;
spdk_bs_load(dev, &bsopts, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
CU_ASSERT(spdk_bs_get_io_unit_size(g_bs) == SPDK_BS_PAGE_SIZE);
/* Unload the blob store */
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
g_blob = NULL;
g_blobid = 0;
}
static void
blob_simultaneous_operations(void)
{
struct spdk_blob_store *bs;
struct spdk_bs_dev *dev;
struct spdk_blob_opts opts;
struct spdk_blob *blob, *snapshot;
spdk_blob_id blobid, snapshotid;
struct spdk_io_channel *channel;
dev = init_dev();
spdk_bs_init(dev, NULL, bs_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_bs != NULL);
bs = g_bs;
channel = spdk_bs_alloc_io_channel(bs);
SPDK_CU_ASSERT_FATAL(channel != NULL);
spdk_blob_opts_init(&opts);
opts.num_clusters = 10;
spdk_bs_create_blob_ext(bs, &opts, blob_op_with_id_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
blobid = g_blobid;
spdk_bs_open_blob(bs, blobid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
blob = g_blob;
/* Create snapshot and try to remove blob in the same time:
* - snapshot should be created successfully
* - delete operation should fail w -EBUSY */
CU_ASSERT(blob->locked_operation_in_progress == false);
spdk_bs_create_snapshot(bs, blobid, NULL, blob_op_with_id_complete, NULL);
CU_ASSERT(blob->locked_operation_in_progress == true);
spdk_bs_delete_blob(bs, blobid, blob_op_complete, NULL);
CU_ASSERT(blob->locked_operation_in_progress == true);
/* Deletion failure */
CU_ASSERT(g_bserrno == -EBUSY);
poll_threads();
CU_ASSERT(blob->locked_operation_in_progress == false);
/* Snapshot creation success */
CU_ASSERT(g_bserrno == 0);
CU_ASSERT(g_blobid != SPDK_BLOBID_INVALID);
snapshotid = g_blobid;
spdk_bs_open_blob(bs, snapshotid, blob_op_with_handle_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
SPDK_CU_ASSERT_FATAL(g_blob != NULL);
snapshot = g_blob;
/* Inflate blob and try to remove blob in the same time:
* - blob should be inflated successfully
* - delete operation should fail w -EBUSY */
CU_ASSERT(blob->locked_operation_in_progress == false);
spdk_bs_inflate_blob(bs, channel, blobid, blob_op_complete, NULL);
CU_ASSERT(blob->locked_operation_in_progress == true);
spdk_bs_delete_blob(bs, blobid, blob_op_complete, NULL);
CU_ASSERT(blob->locked_operation_in_progress == true);
/* Deletion failure */
CU_ASSERT(g_bserrno == -EBUSY);
poll_threads();
CU_ASSERT(blob->locked_operation_in_progress == false);
/* Inflation success */
CU_ASSERT(g_bserrno == 0);
/* Clone snapshot and try to remove snapshot in the same time:
* - snapshot should be cloned successfully
* - delete operation should fail w -EBUSY */
CU_ASSERT(blob->locked_operation_in_progress == false);
spdk_bs_create_clone(bs, snapshotid, NULL, blob_op_with_id_complete, NULL);
spdk_bs_delete_blob(bs, snapshotid, blob_op_complete, NULL);
/* Deletion failure */
CU_ASSERT(g_bserrno == -EBUSY);
poll_threads();
CU_ASSERT(blob->locked_operation_in_progress == false);
/* Clone created */
CU_ASSERT(g_bserrno == 0);
/* Resize blob and try to remove blob in the same time:
* - blob should be resized successfully
* - delete operation should fail w -EBUSY */
CU_ASSERT(blob->locked_operation_in_progress == false);
spdk_blob_resize(blob, 50, blob_op_complete, NULL);
CU_ASSERT(blob->locked_operation_in_progress == true);
spdk_bs_delete_blob(bs, blobid, blob_op_complete, NULL);
CU_ASSERT(blob->locked_operation_in_progress == true);
/* Deletion failure */
CU_ASSERT(g_bserrno == -EBUSY);
poll_threads();
CU_ASSERT(blob->locked_operation_in_progress == false);
/* Blob resized successfully */
CU_ASSERT(g_bserrno == 0);
spdk_blob_close(blob, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_blob_close(snapshot, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_delete_blob(bs, blobid, blob_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
spdk_bs_unload(g_bs, bs_op_complete, NULL);
poll_threads();
CU_ASSERT(g_bserrno == 0);
g_bs = NULL;
spdk_bs_free_io_channel(channel);
poll_threads();
}
int main(int argc, char **argv)
{
CU_pSuite suite = NULL;
unsigned int num_failures;
if (CU_initialize_registry() != CUE_SUCCESS) {
return CU_get_error();
}
suite = CU_add_suite("blob", NULL, NULL);
if (suite == NULL) {
CU_cleanup_registry();
return CU_get_error();
}
if (
CU_add_test(suite, "blob_init", blob_init) == NULL ||
CU_add_test(suite, "blob_open", blob_open) == NULL ||
CU_add_test(suite, "blob_create", blob_create) == NULL ||
CU_add_test(suite, "blob_create_internal", blob_create_internal) == NULL ||
CU_add_test(suite, "blob_thin_provision", blob_thin_provision) == NULL ||
CU_add_test(suite, "blob_snapshot", blob_snapshot) == NULL ||
CU_add_test(suite, "blob_clone", blob_clone) == NULL ||
CU_add_test(suite, "blob_inflate", blob_inflate) == NULL ||
CU_add_test(suite, "blob_delete", blob_delete) == NULL ||
CU_add_test(suite, "blob_resize", blob_resize) == NULL ||
CU_add_test(suite, "blob_read_only", blob_read_only) == NULL ||
CU_add_test(suite, "channel_ops", channel_ops) == NULL ||
CU_add_test(suite, "blob_super", blob_super) == NULL ||
CU_add_test(suite, "blob_write", blob_write) == NULL ||
CU_add_test(suite, "blob_read", blob_read) == NULL ||
CU_add_test(suite, "blob_rw_verify", blob_rw_verify) == NULL ||
CU_add_test(suite, "blob_rw_verify_iov", blob_rw_verify_iov) == NULL ||
CU_add_test(suite, "blob_rw_verify_iov_nomem", blob_rw_verify_iov_nomem) == NULL ||
CU_add_test(suite, "blob_rw_iov_read_only", blob_rw_iov_read_only) == NULL ||
CU_add_test(suite, "blob_unmap", blob_unmap) == NULL ||
CU_add_test(suite, "blob_iter", blob_iter) == NULL ||
CU_add_test(suite, "blob_xattr", blob_xattr) == NULL ||
CU_add_test(suite, "bs_load", bs_load) == NULL ||
CU_add_test(suite, "bs_load_pending_removal", bs_load_pending_removal) == NULL ||
CU_add_test(suite, "bs_load_custom_cluster_size", bs_load_custom_cluster_size) == NULL ||
CU_add_test(suite, "bs_unload", bs_unload) == NULL ||
CU_add_test(suite, "bs_cluster_sz", bs_cluster_sz) == NULL ||
CU_add_test(suite, "bs_usable_clusters", bs_usable_clusters) == NULL ||
CU_add_test(suite, "bs_resize_md", bs_resize_md) == NULL ||
CU_add_test(suite, "bs_destroy", bs_destroy) == NULL ||
CU_add_test(suite, "bs_type", bs_type) == NULL ||
CU_add_test(suite, "bs_super_block", bs_super_block) == NULL ||
CU_add_test(suite, "blob_serialize", blob_serialize) == NULL ||
CU_add_test(suite, "blob_crc", blob_crc) == NULL ||
CU_add_test(suite, "super_block_crc", super_block_crc) == NULL ||
CU_add_test(suite, "blob_dirty_shutdown", blob_dirty_shutdown) == NULL ||
CU_add_test(suite, "blob_flags", blob_flags) == NULL ||
CU_add_test(suite, "bs_version", bs_version) == NULL ||
CU_add_test(suite, "blob_set_xattrs", blob_set_xattrs) == NULL ||
CU_add_test(suite, "blob_thin_prov_alloc", blob_thin_prov_alloc) == NULL ||
CU_add_test(suite, "blob_insert_cluster_msg", blob_insert_cluster_msg) == NULL ||
CU_add_test(suite, "blob_thin_prov_rw", blob_thin_prov_rw) == NULL ||
CU_add_test(suite, "blob_thin_prov_rle", blob_thin_prov_rle) == NULL ||
CU_add_test(suite, "blob_thin_prov_rw_iov", blob_thin_prov_rw_iov) == NULL ||
CU_add_test(suite, "bs_load_iter", bs_load_iter) == NULL ||
CU_add_test(suite, "blob_snapshot_rw", blob_snapshot_rw) == NULL ||
CU_add_test(suite, "blob_snapshot_rw_iov", blob_snapshot_rw_iov) == NULL ||
CU_add_test(suite, "blob_relations", blob_relations) == NULL ||
CU_add_test(suite, "blob_relations2", blob_relations2) == NULL ||
CU_add_test(suite, "blob_delete_snapshot_power_failure",
blob_delete_snapshot_power_failure) == NULL ||
CU_add_test(suite, "blob_create_snapshot_power_failure",
blob_create_snapshot_power_failure) == NULL ||
CU_add_test(suite, "blob_inflate_rw", blob_inflate_rw) == NULL ||
CU_add_test(suite, "blob_snapshot_freeze_io", blob_snapshot_freeze_io) == NULL ||
CU_add_test(suite, "blob_operation_split_rw", blob_operation_split_rw) == NULL ||
CU_add_test(suite, "blob_operation_split_rw_iov", blob_operation_split_rw_iov) == NULL ||
CU_add_test(suite, "blob_io_unit", blob_io_unit) == NULL ||
CU_add_test(suite, "blob_io_unit_compatiblity", blob_io_unit_compatiblity) == NULL ||
CU_add_test(suite, "blob_simultaneous_operations", blob_simultaneous_operations) == NULL
) {
CU_cleanup_registry();
return CU_get_error();
}
allocate_threads(2);
set_thread(0);
g_dev_buffer = calloc(1, DEV_BUFFER_SIZE);
CU_basic_set_mode(CU_BRM_VERBOSE);
CU_basic_run_tests();
num_failures = CU_get_number_of_failures();
CU_cleanup_registry();
free(g_dev_buffer);
free_threads();
return num_failures;
}
|
897693.c | /*
* Copyright 2006 Jacek Caban for CodeWeavers
*
* 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 <assert.h>
#include <math.h>
#define COBJMACROS
#include "windef.h"
#include "winbase.h"
#include "winuser.h"
#include "ole2.h"
#include "mshtmdid.h"
#include "mshtml_private.h"
#include "htmlstyle.h"
#include "wine/debug.h"
WINE_DEFAULT_DEBUG_CHANNEL(mshtml);
static const WCHAR backgroundW[] =
{'b','a','c','k','g','r','o','u','n','d',0};
static const WCHAR background_attachmentW[] =
{'b','a','c','k','g','r','o','u','n','d','-','a','t','t','a','c','h','m','e','n','t',0};
static const WCHAR background_clipW[] =
{'b','a','c','k','g','r','o','u','n','d','-','c','l','i','p',0};
static const WCHAR background_colorW[] =
{'b','a','c','k','g','r','o','u','n','d','-','c','o','l','o','r',0};
static const WCHAR background_imageW[] =
{'b','a','c','k','g','r','o','u','n','d','-','i','m','a','g','e',0};
static const WCHAR background_positionW[] =
{'b','a','c','k','g','r','o','u','n','d','-','p','o','s','i','t','i','o','n',0};
static const WCHAR background_position_xW[] =
{'b','a','c','k','g','r','o','u','n','d','-','p','o','s','i','t','i','o','n','-','x',0};
static const WCHAR background_position_yW[] =
{'b','a','c','k','g','r','o','u','n','d','-','p','o','s','i','t','i','o','n','-','y',0};
static const WCHAR background_repeatW[] =
{'b','a','c','k','g','r','o','u','n','d','-','r','e','p','e','a','t',0};
static const WCHAR borderW[] =
{'b','o','r','d','e','r',0};
static const WCHAR border_bottomW[] =
{'b','o','r','d','e','r','-','b','o','t','t','o','m',0};
static const WCHAR border_bottom_colorW[] =
{'b','o','r','d','e','r','-','b','o','t','t','o','m','-','c','o','l','o','r',0};
static const WCHAR border_bottom_styleW[] =
{'b','o','r','d','e','r','-','b','o','t','t','o','m','-','s','t','y','l','e',0};
static const WCHAR border_bottom_widthW[] =
{'b','o','r','d','e','r','-','b','o','t','t','o','m','-','w','i','d','t','h',0};
static const WCHAR border_colorW[] =
{'b','o','r','d','e','r','-','c','o','l','o','r',0};
static const WCHAR border_leftW[] =
{'b','o','r','d','e','r','-','l','e','f','t',0};
static const WCHAR border_left_colorW[] =
{'b','o','r','d','e','r','-','l','e','f','t','-','c','o','l','o','r',0};
static const WCHAR border_left_styleW[] =
{'b','o','r','d','e','r','-','l','e','f','t','-','s','t','y','l','e',0};
static const WCHAR border_left_widthW[] =
{'b','o','r','d','e','r','-','l','e','f','t','-','w','i','d','t','h',0};
static const WCHAR border_rightW[] =
{'b','o','r','d','e','r','-','r','i','g','h','t',0};
static const WCHAR border_right_colorW[] =
{'b','o','r','d','e','r','-','r','i','g','h','t','-','c','o','l','o','r',0};
static const WCHAR border_right_styleW[] =
{'b','o','r','d','e','r','-','r','i','g','h','t','-','s','t','y','l','e',0};
static const WCHAR border_right_widthW[] =
{'b','o','r','d','e','r','-','r','i','g','h','t','-','w','i','d','t','h',0};
static const WCHAR border_topW[] =
{'b','o','r','d','e','r','-','t','o','p',0};
static const WCHAR border_top_colorW[] =
{'b','o','r','d','e','r','-','t','o','p','-','c','o','l','o','r',0};
static const WCHAR border_styleW[] =
{'b','o','r','d','e','r','-','s','t','y','l','e',0};
static const WCHAR border_top_styleW[] =
{'b','o','r','d','e','r','-','t','o','p','-','s','t','y','l','e',0};
static const WCHAR border_top_widthW[] =
{'b','o','r','d','e','r','-','t','o','p','-','w','i','d','t','h',0};
static const WCHAR border_widthW[] =
{'b','o','r','d','e','r','-','w','i','d','t','h',0};
static const WCHAR bottomW[] =
{'b','o','t','t','o','m',0};
/* FIXME: Use unprefixed version (requires Gecko changes). */
static const WCHAR box_sizingW[] =
{'-','m','o','z','-','b','o','x','-','s','i','z','i','n','g',0};
static const WCHAR clearW[] =
{'c','l','e','a','r',0};
static const WCHAR clipW[] =
{'c','l','i','p',0};
static const WCHAR colorW[] =
{'c','o','l','o','r',0};
static const WCHAR cursorW[] =
{'c','u','r','s','o','r',0};
static const WCHAR directionW[] =
{'d','i','r','e','c','t','i','o','n',0};
static const WCHAR displayW[] =
{'d','i','s','p','l','a','y',0};
static const WCHAR filterW[] =
{'f','i','l','e','t','e','r',0};
static const WCHAR floatW[] =
{'f','l','o','a','t',0};
static const WCHAR font_familyW[] =
{'f','o','n','t','-','f','a','m','i','l','y',0};
static const WCHAR font_sizeW[] =
{'f','o','n','t','-','s','i','z','e',0};
static const WCHAR font_styleW[] =
{'f','o','n','t','-','s','t','y','l','e',0};
static const WCHAR font_variantW[] =
{'f','o','n','t','-','v','a','r','i','a','n','t',0};
static const WCHAR font_weightW[] =
{'f','o','n','t','-','w','e','i','g','h','t',0};
static const WCHAR heightW[] =
{'h','e','i','g','h','t',0};
static const WCHAR leftW[] =
{'l','e','f','t',0};
static const WCHAR letter_spacingW[] =
{'l','e','t','t','e','r','-','s','p','a','c','i','n','g',0};
static const WCHAR line_heightW[] =
{'l','i','n','e','-','h','e','i','g','h','t',0};
static const WCHAR list_styleW[] =
{'l','i','s','t','-','s','t','y','l','e',0};
static const WCHAR list_style_typeW[] =
{'l','i','s','t','-','s','t','y','l','e','-','t','y','p','e',0};
static const WCHAR list_style_positionW[] =
{'l','i','s','t','-','s','t','y','l','e','-','p','o','s','i','t','i','o','n',0};
static const WCHAR marginW[] =
{'m','a','r','g','i','n',0};
static const WCHAR margin_bottomW[] =
{'m','a','r','g','i','n','-','b','o','t','t','o','m',0};
static const WCHAR margin_leftW[] =
{'m','a','r','g','i','n','-','l','e','f','t',0};
static const WCHAR margin_rightW[] =
{'m','a','r','g','i','n','-','r','i','g','h','t',0};
static const WCHAR margin_topW[] =
{'m','a','r','g','i','n','-','t','o','p',0};
static const WCHAR max_heightW[] =
{'m','a','x','-','h','e','i','g','h','t',0};
static const WCHAR max_widthW[] =
{'m','a','x','-','w','i','d','t','h',0};
static const WCHAR min_heightW[] =
{'m','i','n','-','h','e','i','g','h','t',0};
static const WCHAR min_widthW[] =
{'m','i','n','-','w','i','d','t','h',0};
static const WCHAR opacityW[] =
{'o','p','a','c','i','t','y',0};
static const WCHAR outlineW[] =
{'o','u','t','l','i','n','e',0};
static const WCHAR overflowW[] =
{'o','v','e','r','f','l','o','w',0};
static const WCHAR overflow_xW[] =
{'o','v','e','r','f','l','o','w','-','x',0};
static const WCHAR overflow_yW[] =
{'o','v','e','r','f','l','o','w','-','y',0};
static const WCHAR paddingW[] =
{'p','a','d','d','i','n','g',0};
static const WCHAR padding_bottomW[] =
{'p','a','d','d','i','n','g','-','b','o','t','t','o','m',0};
static const WCHAR padding_leftW[] =
{'p','a','d','d','i','n','g','-','l','e','f','t',0};
static const WCHAR padding_rightW[] =
{'p','a','d','d','i','n','g','-','r','i','g','h','t',0};
static const WCHAR padding_topW[] =
{'p','a','d','d','i','n','g','-','t','o','p',0};
static const WCHAR page_break_afterW[] =
{'p','a','g','e','-','b','r','e','a','k','-','a','f','t','e','r',0};
static const WCHAR page_break_beforeW[] =
{'p','a','g','e','-','b','r','e','a','k','-','b','e','f','o','r','e',0};
static const WCHAR positionW[] =
{'p','o','s','i','t','i','o','n',0};
static const WCHAR rightW[] =
{'r','i','g','h','t',0};
static const WCHAR table_layoutW[] =
{'t','a','b','l','e','-','l','a','y','o','u','t',0};
static const WCHAR text_alignW[] =
{'t','e','x','t','-','a','l','i','g','n',0};
static const WCHAR text_decorationW[] =
{'t','e','x','t','-','d','e','c','o','r','a','t','i','o','n',0};
static const WCHAR text_indentW[] =
{'t','e','x','t','-','i','n','d','e','n','t',0};
static const WCHAR text_transformW[] =
{'t','e','x','t','-','t','r','a','n','s','f','o','r','m',0};
static const WCHAR topW[] =
{'t','o','p',0};
static const WCHAR vertical_alignW[] =
{'v','e','r','t','i','c','a','l','-','a','l','i','g','n',0};
static const WCHAR visibilityW[] =
{'v','i','s','i','b','i','l','i','t','y',0};
static const WCHAR white_spaceW[] =
{'w','h','i','t','e','-','s','p','a','c','e',0};
static const WCHAR widthW[] =
{'w','i','d','t','h',0};
static const WCHAR word_spacingW[] =
{'w','o','r','d','-','s','p','a','c','i','n','g',0};
static const WCHAR word_wrapW[] =
{'w','o','r','d','-','w','r','a','p',0};
static const WCHAR z_indexW[] =
{'z','-','i','n','d','e','x',0};
static const WCHAR autoW[] = {'a','u','t','o',0};
static const WCHAR blinkW[] = {'b','l','i','n','k',0};
static const WCHAR boldW[] = {'b','o','l','d',0};
static const WCHAR bolderW[] = {'b','o','l','d','e','r',0};
static const WCHAR capsW[] = {'s','m','a','l','l','-','c','a','p','s',0};
static const WCHAR dashedW[] = {'d','a','s','h','e','d',0};
static const WCHAR dottedW[] = {'d','o','t','t','e','d',0};
static const WCHAR doubleW[] = {'d','o','u','b','l','e',0};
static const WCHAR grooveW[] = {'g','r','o','o','v','e',0};
static const WCHAR hiddenW[] = {'h','i','d','d','e','n',0};
static const WCHAR insetW[] = {'i','n','s','e','t',0};
static const WCHAR italicW[] = {'i','t','a','l','i','c',0};
static const WCHAR lighterW[] = {'l','i','g','h','t','e','r',0};
static const WCHAR line_throughW[] = {'l','i','n','e','-','t','h','r','o','u','g','h',0};
static const WCHAR no_repeatW[] = {'n','o','-','r','e','p','e','a','t',0};
static const WCHAR noneW[] = {'n','o','n','e',0};
static const WCHAR normalW[] = {'n','o','r','m','a','l',0};
static const WCHAR obliqueW[] = {'o','b','l','i','q','u','e',0};
static const WCHAR outsetW[] = {'o','u','t','s','e','t',0};
static const WCHAR overlineW[] = {'o','v','e','r','l','i','n','e',0};
static const WCHAR repeatW[] = {'r','e','p','e','a','t',0};
static const WCHAR repeat_xW[] = {'r','e','p','e','a','t','-','x',0};
static const WCHAR repeat_yW[] = {'r','e','p','e','a','t','-','y',0};
static const WCHAR ridgeW[] = {'r','i','d','g','e',0};
static const WCHAR scrollW[] = {'s','c','r','o','l','l',0};
static const WCHAR solidW[] = {'s','o','l','i','d',0};
static const WCHAR underlineW[] = {'u','n','d','e','r','l','i','n','e',0};
static const WCHAR visibleW[] = {'v','i','s','i','b','l','e',0};
static const WCHAR style100W[] = {'1','0','0',0};
static const WCHAR style200W[] = {'2','0','0',0};
static const WCHAR style300W[] = {'3','0','0',0};
static const WCHAR style400W[] = {'4','0','0',0};
static const WCHAR style500W[] = {'5','0','0',0};
static const WCHAR style600W[] = {'6','0','0',0};
static const WCHAR style700W[] = {'7','0','0',0};
static const WCHAR style800W[] = {'8','0','0',0};
static const WCHAR style900W[] = {'9','0','0',0};
static const WCHAR *font_style_values[] = {
italicW,
normalW,
obliqueW,
NULL
};
static const WCHAR *font_variant_values[] = {
capsW,
normalW,
NULL
};
static const WCHAR *font_weight_values[] = {
style100W,
style200W,
style300W,
style400W,
style500W,
style600W,
style700W,
style800W,
style900W,
boldW,
bolderW,
lighterW,
normalW,
NULL
};
static const WCHAR *background_repeat_values[] = {
no_repeatW,
repeatW,
repeat_xW,
repeat_yW,
NULL
};
static const WCHAR *text_decoration_values[] = {
blinkW,
line_throughW,
noneW,
overlineW,
underlineW,
NULL
};
static const WCHAR *border_style_values[] = {
dashedW,
dottedW,
doubleW,
grooveW,
insetW,
noneW,
outsetW,
ridgeW,
solidW,
NULL
};
static const WCHAR *overflow_values[] = {
autoW,
hiddenW,
scrollW,
visibleW,
NULL
};
#define ATTR_FIX_PX 0x0001
#define ATTR_FIX_URL 0x0002
#define ATTR_STR_TO_INT 0x0004
#define ATTR_HEX_INT 0x0008
#define ATTR_REMOVE_COMMA 0x0010
#define ATTR_NO_NULL 0x0020
static const WCHAR pxW[] = {'p','x',0};
typedef struct {
const WCHAR *name;
DISPID dispid;
DISPID compat_dispid;
unsigned flags;
const WCHAR **allowed_values;
} style_tbl_entry_t;
static const style_tbl_entry_t style_tbl[] = {
{
backgroundW,
DISPID_IHTMLCSSSTYLEDECLARATION_BACKGROUND,
DISPID_IHTMLSTYLE_BACKGROUND
},
{
background_attachmentW,
DISPID_IHTMLCSSSTYLEDECLARATION_BACKGROUNDATTACHMENT,
DISPID_IHTMLSTYLE_BACKGROUNDATTACHMENT
},
{
background_clipW,
DISPID_IHTMLCSSSTYLEDECLARATION_BACKGROUNDCLIP,
DISPID_UNKNOWN
},
{
background_colorW,
DISPID_IHTMLCSSSTYLEDECLARATION_BACKGROUNDCOLOR,
DISPID_IHTMLSTYLE_BACKGROUNDCOLOR,
ATTR_HEX_INT
},
{
background_imageW,
DISPID_IHTMLCSSSTYLEDECLARATION_BACKGROUNDIMAGE,
DISPID_IHTMLSTYLE_BACKGROUNDIMAGE,
ATTR_FIX_URL
},
{
background_positionW,
DISPID_IHTMLCSSSTYLEDECLARATION_BACKGROUNDPOSITION,
DISPID_IHTMLSTYLE_BACKGROUNDPOSITION
},
{
background_position_xW,
DISPID_IHTMLCSSSTYLEDECLARATION_BACKGROUNDPOSITIONX,
DISPID_IHTMLSTYLE_BACKGROUNDPOSITIONX,
ATTR_FIX_PX
},
{
background_position_yW,
DISPID_IHTMLCSSSTYLEDECLARATION_BACKGROUNDPOSITIONY,
DISPID_IHTMLSTYLE_BACKGROUNDPOSITIONY,
ATTR_FIX_PX
},
{
background_repeatW,
DISPID_IHTMLCSSSTYLEDECLARATION_BACKGROUNDREPEAT,
DISPID_IHTMLSTYLE_BACKGROUNDREPEAT,
0, background_repeat_values
},
{
borderW,
DISPID_IHTMLCSSSTYLEDECLARATION_BORDER,
DISPID_IHTMLSTYLE_BORDER
},
{
border_bottomW,
DISPID_IHTMLCSSSTYLEDECLARATION_BORDERBOTTOM,
DISPID_IHTMLSTYLE_BORDERBOTTOM,
ATTR_FIX_PX
},
{
border_bottom_colorW,
DISPID_IHTMLCSSSTYLEDECLARATION_BORDERBOTTOMCOLOR,
DISPID_IHTMLSTYLE_BORDERBOTTOMCOLOR,
ATTR_HEX_INT
},
{
border_bottom_styleW,
DISPID_IHTMLCSSSTYLEDECLARATION_BORDERBOTTOMSTYLE,
DISPID_IHTMLSTYLE_BORDERBOTTOMSTYLE,
0, border_style_values
},
{
border_bottom_widthW,
DISPID_IHTMLCSSSTYLEDECLARATION_BORDERBOTTOMWIDTH,
DISPID_IHTMLSTYLE_BORDERBOTTOMWIDTH,
ATTR_FIX_PX
},
{
border_colorW,
DISPID_IHTMLCSSSTYLEDECLARATION_BORDERCOLOR,
DISPID_IHTMLSTYLE_BORDERCOLOR
},
{
border_leftW,
DISPID_IHTMLCSSSTYLEDECLARATION_BORDERLEFT,
DISPID_IHTMLSTYLE_BORDERLEFT,
ATTR_FIX_PX
},
{
border_left_colorW,
DISPID_IHTMLCSSSTYLEDECLARATION_BORDERLEFTCOLOR,
DISPID_IHTMLSTYLE_BORDERLEFTCOLOR,
ATTR_HEX_INT
},
{
border_left_styleW,
DISPID_IHTMLCSSSTYLEDECLARATION_BORDERLEFTSTYLE,
DISPID_IHTMLSTYLE_BORDERLEFTSTYLE,
0, border_style_values
},
{
border_left_widthW,
DISPID_IHTMLCSSSTYLEDECLARATION_BORDERLEFTWIDTH,
DISPID_IHTMLSTYLE_BORDERLEFTWIDTH,
ATTR_FIX_PX
},
{
border_rightW,
DISPID_IHTMLCSSSTYLEDECLARATION_BORDERRIGHT,
DISPID_IHTMLSTYLE_BORDERRIGHT,
ATTR_FIX_PX
},
{
border_right_colorW,
DISPID_IHTMLCSSSTYLEDECLARATION_BORDERRIGHTCOLOR,
DISPID_IHTMLSTYLE_BORDERRIGHTCOLOR,
ATTR_HEX_INT
},
{
border_right_styleW,
DISPID_IHTMLCSSSTYLEDECLARATION_BORDERRIGHTSTYLE,
DISPID_IHTMLSTYLE_BORDERRIGHTSTYLE,
0, border_style_values
},
{
border_right_widthW,
DISPID_IHTMLCSSSTYLEDECLARATION_BORDERRIGHTWIDTH,
DISPID_IHTMLSTYLE_BORDERRIGHTWIDTH,
ATTR_FIX_PX
},
{
border_styleW,
DISPID_IHTMLCSSSTYLEDECLARATION_BORDERSTYLE,
DISPID_IHTMLSTYLE_BORDERSTYLE
},
{
border_topW,
DISPID_IHTMLCSSSTYLEDECLARATION_BORDERTOP,
DISPID_IHTMLSTYLE_BORDERTOP,
ATTR_FIX_PX
},
{
border_top_colorW,
DISPID_IHTMLCSSSTYLEDECLARATION_BORDERTOPCOLOR,
DISPID_IHTMLSTYLE_BORDERTOPCOLOR,
ATTR_HEX_INT
},
{
border_top_styleW,
DISPID_IHTMLCSSSTYLEDECLARATION_BORDERTOPSTYLE,
DISPID_IHTMLSTYLE_BORDERTOPSTYLE,
0, border_style_values
},
{
border_top_widthW,
DISPID_IHTMLCSSSTYLEDECLARATION_BORDERTOPWIDTH,
DISPID_IHTMLSTYLE_BORDERTOPWIDTH
},
{
border_widthW,
DISPID_IHTMLCSSSTYLEDECLARATION_BORDERWIDTH,
DISPID_IHTMLSTYLE_BORDERWIDTH
},
{
bottomW,
DISPID_IHTMLCSSSTYLEDECLARATION_BOTTOM,
DISPID_IHTMLSTYLE2_BOTTOM,
ATTR_FIX_PX
},
{
box_sizingW,
DISPID_IHTMLCSSSTYLEDECLARATION_BOXSIZING,
DISPID_IHTMLSTYLE6_BOXSIZING
},
{
clearW,
DISPID_IHTMLCSSSTYLEDECLARATION_CLEAR,
DISPID_IHTMLSTYLE_CLEAR
},
{
clipW,
DISPID_IHTMLCSSSTYLEDECLARATION_CLIP,
DISPID_IHTMLSTYLE_CLIP,
ATTR_REMOVE_COMMA
},
{
colorW,
DISPID_IHTMLCSSSTYLEDECLARATION_COLOR,
DISPID_IHTMLSTYLE_COLOR,
ATTR_HEX_INT
},
{
cursorW,
DISPID_IHTMLCSSSTYLEDECLARATION_CURSOR,
DISPID_IHTMLSTYLE_CURSOR
},
{
directionW,
DISPID_IHTMLCSSSTYLEDECLARATION_DIRECTION,
DISPID_IHTMLSTYLE2_DIRECTION
},
{
displayW,
DISPID_IHTMLCSSSTYLEDECLARATION_DISPLAY,
DISPID_IHTMLSTYLE_DISPLAY
},
{
filterW,
DISPID_IHTMLCSSSTYLEDECLARATION_FILTER,
DISPID_IHTMLSTYLE_FILTER
},
{
floatW,
DISPID_IHTMLCSSSTYLEDECLARATION_CSSFLOAT,
DISPID_IHTMLSTYLE_STYLEFLOAT
},
{
font_familyW,
DISPID_IHTMLCSSSTYLEDECLARATION_FONTFAMILY,
DISPID_IHTMLSTYLE_FONTFAMILY
},
{
font_sizeW,
DISPID_IHTMLCSSSTYLEDECLARATION_FONTSIZE,
DISPID_IHTMLSTYLE_FONTSIZE,
ATTR_FIX_PX
},
{
font_styleW,
DISPID_IHTMLCSSSTYLEDECLARATION_FONTSTYLE,
DISPID_IHTMLSTYLE_FONTSTYLE,
0, font_style_values
},
{
font_variantW,
DISPID_IHTMLCSSSTYLEDECLARATION_FONTVARIANT,
DISPID_IHTMLSTYLE_FONTVARIANT,
0, font_variant_values
},
{
font_weightW,
DISPID_IHTMLCSSSTYLEDECLARATION_FONTWEIGHT,
DISPID_IHTMLSTYLE_FONTWEIGHT,
ATTR_STR_TO_INT, font_weight_values
},
{
heightW,
DISPID_IHTMLCSSSTYLEDECLARATION_HEIGHT,
DISPID_IHTMLSTYLE_HEIGHT,
ATTR_FIX_PX
},
{
leftW,
DISPID_IHTMLCSSSTYLEDECLARATION_LEFT,
DISPID_IHTMLSTYLE_LEFT
},
{
letter_spacingW,
DISPID_IHTMLCSSSTYLEDECLARATION_LETTERSPACING,
DISPID_IHTMLSTYLE_LETTERSPACING
},
{
line_heightW,
DISPID_IHTMLCSSSTYLEDECLARATION_LINEHEIGHT,
DISPID_IHTMLSTYLE_LINEHEIGHT
},
{
list_styleW,
DISPID_IHTMLCSSSTYLEDECLARATION_LISTSTYLE,
DISPID_IHTMLSTYLE_LISTSTYLE
},
{
list_style_positionW,
DISPID_IHTMLCSSSTYLEDECLARATION_LISTSTYLEPOSITION,
DISPID_IHTMLSTYLE_LISTSTYLEPOSITION
},
{
list_style_typeW,
DISPID_IHTMLCSSSTYLEDECLARATION_LISTSTYLETYPE,
DISPID_IHTMLSTYLE_LISTSTYLETYPE
},
{
marginW,
DISPID_IHTMLCSSSTYLEDECLARATION_MARGIN,
DISPID_IHTMLSTYLE_MARGIN
},
{
margin_bottomW,
DISPID_IHTMLCSSSTYLEDECLARATION_MARGINBOTTOM,
DISPID_IHTMLSTYLE_MARGINBOTTOM,
ATTR_FIX_PX
},
{
margin_leftW,
DISPID_IHTMLCSSSTYLEDECLARATION_MARGINLEFT,
DISPID_IHTMLSTYLE_MARGINLEFT,
ATTR_FIX_PX
},
{
margin_rightW,
DISPID_IHTMLCSSSTYLEDECLARATION_MARGINRIGHT,
DISPID_IHTMLSTYLE_MARGINRIGHT,
ATTR_FIX_PX
},
{
margin_topW,
DISPID_IHTMLCSSSTYLEDECLARATION_MARGINTOP,
DISPID_IHTMLSTYLE_MARGINTOP,
ATTR_FIX_PX
},
{
max_heightW,
DISPID_IHTMLCSSSTYLEDECLARATION_MAXHEIGHT,
DISPID_IHTMLSTYLE5_MAXHEIGHT,
ATTR_FIX_PX
},
{
max_widthW,
DISPID_IHTMLCSSSTYLEDECLARATION_MAXWIDTH,
DISPID_IHTMLSTYLE5_MAXWIDTH,
ATTR_FIX_PX
},
{
min_heightW,
DISPID_IHTMLCSSSTYLEDECLARATION_MINHEIGHT,
DISPID_IHTMLSTYLE4_MINHEIGHT
},
{
min_widthW,
DISPID_IHTMLCSSSTYLEDECLARATION_MINWIDTH,
DISPID_IHTMLSTYLE5_MINWIDTH,
ATTR_FIX_PX
},
{
opacityW,
DISPID_IHTMLCSSSTYLEDECLARATION_OPACITY,
DISPID_UNKNOWN
},
{
outlineW,
DISPID_IHTMLCSSSTYLEDECLARATION_OUTLINE,
DISPID_IHTMLSTYLE6_OUTLINE,
ATTR_NO_NULL
},
{
overflowW,
DISPID_IHTMLCSSSTYLEDECLARATION_OVERFLOW,
DISPID_IHTMLSTYLE_OVERFLOW,
0, overflow_values
},
{
overflow_xW,
DISPID_IHTMLCSSSTYLEDECLARATION_OVERFLOWX,
DISPID_IHTMLSTYLE2_OVERFLOWX
},
{
overflow_yW,
DISPID_IHTMLCSSSTYLEDECLARATION_OVERFLOWY,
DISPID_IHTMLSTYLE2_OVERFLOWY
},
{
paddingW,
DISPID_IHTMLCSSSTYLEDECLARATION_PADDING,
DISPID_IHTMLSTYLE_PADDING
},
{
padding_bottomW,
DISPID_IHTMLCSSSTYLEDECLARATION_PADDINGBOTTOM,
DISPID_IHTMLSTYLE_PADDINGBOTTOM,
ATTR_FIX_PX
},
{
padding_leftW,
DISPID_IHTMLCSSSTYLEDECLARATION_PADDINGLEFT,
DISPID_IHTMLSTYLE_PADDINGLEFT,
ATTR_FIX_PX
},
{
padding_rightW,
DISPID_IHTMLCSSSTYLEDECLARATION_PADDINGRIGHT,
DISPID_IHTMLSTYLE_PADDINGRIGHT,
ATTR_FIX_PX
},
{
padding_topW,
DISPID_IHTMLCSSSTYLEDECLARATION_PADDINGTOP,
DISPID_IHTMLSTYLE_PADDINGTOP,
ATTR_FIX_PX
},
{
page_break_afterW,
DISPID_IHTMLCSSSTYLEDECLARATION_PAGEBREAKAFTER,
DISPID_IHTMLSTYLE_PAGEBREAKAFTER
},
{
page_break_beforeW,
DISPID_IHTMLCSSSTYLEDECLARATION_PAGEBREAKBEFORE,
DISPID_IHTMLSTYLE_PAGEBREAKBEFORE
},
{
positionW,
DISPID_IHTMLCSSSTYLEDECLARATION_POSITION,
DISPID_IHTMLSTYLE2_POSITION
},
{
rightW,
DISPID_IHTMLCSSSTYLEDECLARATION_RIGHT,
DISPID_IHTMLSTYLE2_RIGHT
},
{
table_layoutW,
DISPID_IHTMLCSSSTYLEDECLARATION_TABLELAYOUT,
DISPID_IHTMLSTYLE2_TABLELAYOUT
},
{
text_alignW,
DISPID_IHTMLCSSSTYLEDECLARATION_TEXTALIGN,
DISPID_IHTMLSTYLE_TEXTALIGN
},
{
text_decorationW,
DISPID_IHTMLCSSSTYLEDECLARATION_TEXTDECORATION,
DISPID_IHTMLSTYLE_TEXTDECORATION,
0, text_decoration_values
},
{
text_indentW,
DISPID_IHTMLCSSSTYLEDECLARATION_TEXTINDENT,
DISPID_IHTMLSTYLE_TEXTINDENT,
ATTR_FIX_PX
},
{
text_transformW,
DISPID_IHTMLCSSSTYLEDECLARATION_TEXTTRANSFORM,
DISPID_IHTMLSTYLE_TEXTTRANSFORM
},
{
topW,
DISPID_IHTMLCSSSTYLEDECLARATION_TOP,
DISPID_IHTMLSTYLE_TOP
},
{
vertical_alignW,
DISPID_IHTMLCSSSTYLEDECLARATION_VERTICALALIGN,
DISPID_IHTMLSTYLE_VERTICALALIGN,
ATTR_FIX_PX
},
{
visibilityW,
DISPID_IHTMLCSSSTYLEDECLARATION_VISIBILITY,
DISPID_IHTMLSTYLE_VISIBILITY
},
{
white_spaceW,
DISPID_IHTMLCSSSTYLEDECLARATION_WHITESPACE,
DISPID_IHTMLSTYLE_WHITESPACE
},
{
widthW,
DISPID_IHTMLCSSSTYLEDECLARATION_WIDTH,
DISPID_IHTMLSTYLE_WIDTH,
ATTR_FIX_PX
},
{
word_spacingW,
DISPID_IHTMLCSSSTYLEDECLARATION_WORDSPACING,
DISPID_IHTMLSTYLE_WORDSPACING
},
{
word_wrapW,
DISPID_IHTMLCSSSTYLEDECLARATION_WORDWRAP,
DISPID_IHTMLSTYLE3_WORDWRAP
},
{
z_indexW,
DISPID_IHTMLCSSSTYLEDECLARATION_ZINDEX,
DISPID_IHTMLSTYLE_ZINDEX,
ATTR_STR_TO_INT
}
};
C_ASSERT(ARRAY_SIZE(style_tbl) == STYLEID_MAX_VALUE);
static const WCHAR px_formatW[] = {'%','d','p','x',0};
static const WCHAR emptyW[] = {0};
static const style_tbl_entry_t *lookup_style_tbl(const WCHAR *name)
{
int c, i, min = 0, max = ARRAY_SIZE(style_tbl)-1;
while(min <= max) {
i = (min+max)/2;
c = strcmpW(style_tbl[i].name, name);
if(!c)
return style_tbl+i;
if(c > 0)
max = i-1;
else
min = i+1;
}
return NULL;
}
static LPWSTR fix_px_value(LPCWSTR val)
{
LPCWSTR ptr = val;
while(*ptr) {
while(*ptr && isspaceW(*ptr))
ptr++;
if(!*ptr)
break;
while(*ptr && isdigitW(*ptr))
ptr++;
if(!*ptr || isspaceW(*ptr)) {
LPWSTR ret, p;
int len = strlenW(val)+1;
ret = heap_alloc((len+2)*sizeof(WCHAR));
memcpy(ret, val, (ptr-val)*sizeof(WCHAR));
p = ret + (ptr-val);
*p++ = 'p';
*p++ = 'x';
strcpyW(p, ptr);
TRACE("fixed %s -> %s\n", debugstr_w(val), debugstr_w(ret));
return ret;
}
while(*ptr && !isspaceW(*ptr))
ptr++;
}
return NULL;
}
static LPWSTR fix_url_value(LPCWSTR val)
{
WCHAR *ret, *ptr;
static const WCHAR urlW[] = {'u','r','l','('};
if(strncmpW(val, urlW, ARRAY_SIZE(urlW)) || !strchrW(val, '\\'))
return NULL;
ret = heap_strdupW(val);
for(ptr = ret; *ptr; ptr++) {
if(*ptr == '\\')
*ptr = '/';
}
return ret;
}
static HRESULT set_nsstyle_property(nsIDOMCSSStyleDeclaration *nsstyle, styleid_t sid, const WCHAR *value)
{
nsAString str_name, str_value, str_empty;
nsresult nsres;
nsAString_InitDepend(&str_name, style_tbl[sid].name);
nsAString_InitDepend(&str_value, value);
nsAString_InitDepend(&str_empty, emptyW);
nsres = nsIDOMCSSStyleDeclaration_SetProperty(nsstyle, &str_name, &str_value, &str_empty);
if(NS_FAILED(nsres))
ERR("SetProperty failed: %08x\n", nsres);
nsAString_Finish(&str_name);
nsAString_Finish(&str_value);
nsAString_Finish(&str_empty);
return S_OK;
}
static HRESULT var_to_styleval(HTMLStyle *style, const VARIANT *v, styleid_t sid, WCHAR *buf, const WCHAR **ret)
{
switch(V_VT(v)) {
case VT_NULL:
*ret = emptyW;
return S_OK;
case VT_BSTR:
*ret = V_BSTR(v);
return S_OK;
case VT_BSTR|VT_BYREF:
*ret = *V_BSTRREF(v);
return S_OK;
case VT_I4: {
unsigned flags = dispex_compat_mode(&style->dispex) < COMPAT_MODE_IE9 ? style_tbl[sid].flags : 0;
static const WCHAR formatW[] = {'%','d',0};
static const WCHAR hex_formatW[] = {'#','%','0','6','x',0};
if(flags & ATTR_HEX_INT)
wsprintfW(buf, hex_formatW, V_I4(v));
else if(flags & ATTR_FIX_PX)
wsprintfW(buf, px_formatW, V_I4(v));
else
wsprintfW(buf, formatW, V_I4(v));
*ret = buf;
return S_OK;
}
default:
FIXME("not implemented for %s\n", debugstr_variant(v));
return E_NOTIMPL;
}
}
static inline HRESULT set_style_property(HTMLStyle *style, styleid_t sid, const WCHAR *value)
{
WCHAR *val = NULL;
HRESULT hres;
if(value && *value && dispex_compat_mode(&style->dispex) < COMPAT_MODE_IE9) {
unsigned flags = style_tbl[sid].flags;
if(style_tbl[sid].allowed_values) {
const WCHAR **iter;
for(iter = style_tbl[sid].allowed_values; *iter; iter++) {
if(!strcmpiW(*iter, value))
break;
}
if(!*iter) {
WARN("invalid value %s\n", debugstr_w(value));
set_nsstyle_property(style->nsstyle, sid, emptyW);
return E_INVALIDARG;
}
}
if(flags & ATTR_FIX_PX)
val = fix_px_value(value);
else if(flags & ATTR_FIX_URL)
val = fix_url_value(value);
}
hres = set_nsstyle_property(style->nsstyle, sid, val ? val : value);
heap_free(val);
return hres;
}
static HRESULT set_style_property_var(HTMLStyle *style, styleid_t sid, VARIANT *value)
{
const WCHAR *val;
WCHAR buf[14];
HRESULT hres;
hres = var_to_styleval(style, value, sid, buf, &val);
if(FAILED(hres))
return hres;
return set_style_property(style, sid, val);
}
static HRESULT get_nsstyle_attr_nsval(nsIDOMCSSStyleDeclaration *nsstyle, styleid_t sid, nsAString *value)
{
nsAString str_name;
nsresult nsres;
nsAString_InitDepend(&str_name, style_tbl[sid].name);
nsres = nsIDOMCSSStyleDeclaration_GetPropertyValue(nsstyle, &str_name, value);
nsAString_Finish(&str_name);
if(NS_FAILED(nsres)) {
ERR("SetProperty failed: %08x\n", nsres);
return E_FAIL;
}
return S_OK;
}
static HRESULT nsstyle_to_bstr(const WCHAR *val, DWORD flags, BSTR *p)
{
BSTR ret;
DWORD len;
if(!*val) {
*p = (flags & ATTR_NO_NULL) ? SysAllocStringLen(NULL, 0) : NULL;
return S_OK;
}
ret = SysAllocString(val);
if(!ret)
return E_OUTOFMEMORY;
len = SysStringLen(ret);
if(flags & ATTR_REMOVE_COMMA) {
DWORD new_len = len;
WCHAR *ptr, *ptr2;
for(ptr = ret; (ptr = strchrW(ptr, ',')); ptr++)
new_len--;
if(new_len != len) {
BSTR new_ret;
new_ret = SysAllocStringLen(NULL, new_len);
if(!new_ret) {
SysFreeString(ret);
return E_OUTOFMEMORY;
}
for(ptr2 = new_ret, ptr = ret; *ptr; ptr++) {
if(*ptr != ',')
*ptr2++ = *ptr;
}
SysFreeString(ret);
ret = new_ret;
}
}
*p = ret;
return S_OK;
}
HRESULT get_nsstyle_property(nsIDOMCSSStyleDeclaration *nsstyle, styleid_t sid, compat_mode_t compat_mode, BSTR *p)
{
nsAString str_value;
const PRUnichar *value;
HRESULT hres;
nsAString_Init(&str_value, NULL);
get_nsstyle_attr_nsval(nsstyle, sid, &str_value);
nsAString_GetData(&str_value, &value);
hres = nsstyle_to_bstr(value, compat_mode < COMPAT_MODE_IE9 ? style_tbl[sid].flags : 0, p);
nsAString_Finish(&str_value);
TRACE("%s -> %s\n", debugstr_w(style_tbl[sid].name), debugstr_w(*p));
return hres;
}
HRESULT get_nsstyle_property_var(nsIDOMCSSStyleDeclaration *nsstyle, styleid_t sid, compat_mode_t compat_mode, VARIANT *p)
{
unsigned flags = style_tbl[sid].flags;
nsAString str_value;
const PRUnichar *value;
BOOL set = FALSE;
HRESULT hres = S_OK;
nsAString_Init(&str_value, NULL);
get_nsstyle_attr_nsval(nsstyle, sid, &str_value);
nsAString_GetData(&str_value, &value);
if((flags & ATTR_STR_TO_INT) && (*value || compat_mode < COMPAT_MODE_IE9)) {
const PRUnichar *ptr = value;
BOOL neg = FALSE;
INT i = 0;
if(*ptr == '-') {
neg = TRUE;
ptr++;
}
while(isdigitW(*ptr))
i = i*10 + (*ptr++ - '0');
if(!*ptr) {
V_VT(p) = VT_I4;
V_I4(p) = neg ? -i : i;
set = TRUE;
}
}
if(!set) {
BSTR str;
hres = nsstyle_to_bstr(value, compat_mode < COMPAT_MODE_IE9 ? flags : 0, &str);
if(SUCCEEDED(hres)) {
V_VT(p) = VT_BSTR;
V_BSTR(p) = str;
}
}
nsAString_Finish(&str_value);
TRACE("%s -> %s\n", debugstr_w(style_tbl[sid].name), debugstr_variant(p));
return S_OK;
}
static inline HRESULT get_style_property(HTMLStyle *This, styleid_t sid, BSTR *p)
{
return get_nsstyle_property(This->nsstyle, sid, dispex_compat_mode(&This->dispex), p);
}
static inline HRESULT get_style_property_var(HTMLStyle *This, styleid_t sid, VARIANT *v)
{
return get_nsstyle_property_var(This->nsstyle, sid, dispex_compat_mode(&This->dispex), v);
}
static HRESULT check_style_attr_value(HTMLStyle *This, styleid_t sid, LPCWSTR exval, VARIANT_BOOL *p)
{
nsAString str_value;
const PRUnichar *value;
nsAString_Init(&str_value, NULL);
get_nsstyle_attr_nsval(This->nsstyle, sid, &str_value);
nsAString_GetData(&str_value, &value);
*p = variant_bool(!strcmpW(value, exval));
nsAString_Finish(&str_value);
TRACE("%s -> %x\n", debugstr_w(style_tbl[sid].name), *p);
return S_OK;
}
static inline HRESULT set_style_pos(HTMLStyle *This, styleid_t sid, float value)
{
WCHAR szValue[25];
WCHAR szFormat[] = {'%','.','0','f','p','x',0};
value = floor(value);
sprintfW(szValue, szFormat, value);
return set_style_property(This, sid, szValue);
}
static HRESULT set_style_pxattr(HTMLStyle *style, styleid_t sid, LONG value)
{
WCHAR value_str[16];
sprintfW(value_str, px_formatW, value);
return set_style_property(style, sid, value_str);
}
static HRESULT get_nsstyle_pos(HTMLStyle *This, styleid_t sid, float *p)
{
nsAString str_value;
HRESULT hres;
TRACE("%p %d %p\n", This, sid, p);
*p = 0.0f;
nsAString_Init(&str_value, NULL);
hres = get_nsstyle_attr_nsval(This->nsstyle, sid, &str_value);
if(hres == S_OK)
{
WCHAR *ptr;
const PRUnichar *value;
nsAString_GetData(&str_value, &value);
if(value)
{
*p = strtolW(value, &ptr, 10);
if(*ptr && strcmpW(ptr, pxW))
{
nsAString_Finish(&str_value);
FIXME("only px values are currently supported\n");
hres = E_FAIL;
}
}
}
TRACE("ret %f\n", *p);
nsAString_Finish(&str_value);
return hres;
}
static HRESULT get_nsstyle_pixel_val(HTMLStyle *This, styleid_t sid, LONG *p)
{
nsAString str_value;
HRESULT hres;
if(!p)
return E_POINTER;
nsAString_Init(&str_value, NULL);
hres = get_nsstyle_attr_nsval(This->nsstyle, sid, &str_value);
if(hres == S_OK) {
WCHAR *ptr = NULL;
const PRUnichar *value;
nsAString_GetData(&str_value, &value);
if(value) {
*p = strtolW(value, &ptr, 10);
if(*ptr == '.') {
/* Skip all digits. We have tests showing that we should not round the value. */
while(isdigitW(*++ptr));
}
}
if(!ptr || (*ptr && strcmpW(ptr, pxW)))
*p = 0;
}
nsAString_Finish(&str_value);
return hres;
}
static BOOL is_valid_border_style(BSTR v)
{
return !v || strcmpiW(v, noneW) == 0 || strcmpiW(v, dottedW) == 0 ||
strcmpiW(v, dashedW) == 0 || strcmpiW(v, solidW) == 0 ||
strcmpiW(v, doubleW) == 0 || strcmpiW(v, grooveW) == 0 ||
strcmpiW(v, ridgeW) == 0 || strcmpiW(v, insetW) == 0 ||
strcmpiW(v, outsetW) == 0;
}
static inline HTMLStyle *impl_from_IHTMLStyle(IHTMLStyle *iface)
{
return CONTAINING_RECORD(iface, HTMLStyle, IHTMLStyle_iface);
}
static HRESULT WINAPI HTMLStyle_QueryInterface(IHTMLStyle *iface, REFIID riid, void **ppv)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s %p)\n", This, debugstr_mshtml_guid(riid), ppv);
if(IsEqualGUID(&IID_IUnknown, riid)) {
*ppv = &This->IHTMLStyle_iface;
}else if(IsEqualGUID(&IID_IHTMLCSSStyleDeclaration, riid)) {
*ppv = &This->IHTMLCSSStyleDeclaration_iface;
}else if(IsEqualGUID(&IID_IHTMLCSSStyleDeclaration2, riid)) {
*ppv = &This->IHTMLCSSStyleDeclaration2_iface;
}else if(IsEqualGUID(&IID_IHTMLStyle, riid)) {
*ppv = &This->IHTMLStyle_iface;
}else if(IsEqualGUID(&IID_IHTMLStyle2, riid)) {
*ppv = &This->IHTMLStyle2_iface;
}else if(IsEqualGUID(&IID_IHTMLStyle3, riid)) {
*ppv = &This->IHTMLStyle3_iface;
}else if(IsEqualGUID(&IID_IHTMLStyle4, riid)) {
*ppv = &This->IHTMLStyle4_iface;
}else if(IsEqualGUID(&IID_IHTMLStyle5, riid)) {
*ppv = &This->IHTMLStyle5_iface;
}else if(IsEqualGUID(&IID_IHTMLStyle6, riid)) {
*ppv = &This->IHTMLStyle6_iface;
}else if(dispex_query_interface(&This->dispex, riid, ppv)) {
return *ppv ? S_OK : E_NOINTERFACE;
}else {
*ppv = NULL;
WARN("unsupported iface %s\n", debugstr_mshtml_guid(riid));
return E_NOINTERFACE;
}
IUnknown_AddRef((IUnknown*)*ppv);
return S_OK;
}
static ULONG WINAPI HTMLStyle_AddRef(IHTMLStyle *iface)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
LONG ref = InterlockedIncrement(&This->ref);
TRACE("(%p) ref=%d\n", This, ref);
return ref;
}
static ULONG WINAPI HTMLStyle_Release(IHTMLStyle *iface)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
LONG ref = InterlockedDecrement(&This->ref);
TRACE("(%p) ref=%d\n", This, ref);
if(!ref) {
assert(!This->elem);
if(This->nsstyle)
nsIDOMCSSStyleDeclaration_Release(This->nsstyle);
release_dispex(&This->dispex);
heap_free(This);
}
return ref;
}
static HRESULT WINAPI HTMLStyle_GetTypeInfoCount(IHTMLStyle *iface, UINT *pctinfo)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
return IDispatchEx_GetTypeInfoCount(&This->dispex.IDispatchEx_iface, pctinfo);
}
static HRESULT WINAPI HTMLStyle_GetTypeInfo(IHTMLStyle *iface, UINT iTInfo,
LCID lcid, ITypeInfo **ppTInfo)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
return IDispatchEx_GetTypeInfo(&This->dispex.IDispatchEx_iface, iTInfo, lcid, ppTInfo);
}
static HRESULT WINAPI HTMLStyle_GetIDsOfNames(IHTMLStyle *iface, REFIID riid,
LPOLESTR *rgszNames, UINT cNames,
LCID lcid, DISPID *rgDispId)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
return IDispatchEx_GetIDsOfNames(&This->dispex.IDispatchEx_iface, riid, rgszNames, cNames,
lcid, rgDispId);
}
static HRESULT WINAPI HTMLStyle_Invoke(IHTMLStyle *iface, DISPID dispIdMember,
REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams,
VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
return IDispatchEx_Invoke(&This->dispex.IDispatchEx_iface, dispIdMember, riid, lcid,
wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr);
}
static HRESULT WINAPI HTMLStyle_put_fontFamily(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_FONT_FAMILY, v);
}
static HRESULT WINAPI HTMLStyle_get_fontFamily(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_FONT_FAMILY, p);
}
static HRESULT WINAPI HTMLStyle_put_fontStyle(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_FONT_STYLE, v);
}
static HRESULT WINAPI HTMLStyle_get_fontStyle(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_FONT_STYLE, p);
}
static HRESULT WINAPI HTMLStyle_put_fontVariant(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_FONT_VARIANT, v);
}
static HRESULT WINAPI HTMLStyle_get_fontVariant(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
if(!p)
return E_INVALIDARG;
return get_style_property(This, STYLEID_FONT_VARIANT, p);
}
static HRESULT WINAPI HTMLStyle_put_fontWeight(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_FONT_WEIGHT, v);
}
static HRESULT WINAPI HTMLStyle_get_fontWeight(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_FONT_WEIGHT, p);
}
static HRESULT WINAPI HTMLStyle_put_fontSize(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_FONT_SIZE, &v);
}
static HRESULT WINAPI HTMLStyle_get_fontSize(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_FONT_SIZE, p);
}
static HRESULT WINAPI HTMLStyle_put_font(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle_get_font(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle_put_color(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_COLOR, &v);
}
static HRESULT WINAPI HTMLStyle_get_color(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_COLOR, p);
}
static HRESULT WINAPI HTMLStyle_put_background(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BACKGROUND, v);
}
static HRESULT WINAPI HTMLStyle_get_background(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BACKGROUND, p);
}
static HRESULT WINAPI HTMLStyle_put_backgroundColor(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_BACKGROUND_COLOR, &v);
}
static HRESULT WINAPI HTMLStyle_get_backgroundColor(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_BACKGROUND_COLOR, p);
}
static HRESULT WINAPI HTMLStyle_put_backgroundImage(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BACKGROUND_IMAGE, v);
}
static HRESULT WINAPI HTMLStyle_get_backgroundImage(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BACKGROUND_IMAGE, p);
}
static HRESULT WINAPI HTMLStyle_put_backgroundRepeat(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BACKGROUND_REPEAT , v);
}
static HRESULT WINAPI HTMLStyle_get_backgroundRepeat(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BACKGROUND_REPEAT, p);
}
static HRESULT WINAPI HTMLStyle_put_backgroundAttachment(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BACKGROUND_ATTACHMENT, v);
}
static HRESULT WINAPI HTMLStyle_get_backgroundAttachment(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BACKGROUND_ATTACHMENT, p);
}
static HRESULT WINAPI HTMLStyle_put_backgroundPosition(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BACKGROUND_POSITION, v);
}
static HRESULT WINAPI HTMLStyle_get_backgroundPosition(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BACKGROUND_POSITION, p);
}
static HRESULT WINAPI HTMLStyle_put_backgroundPositionX(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
WCHAR buf[14], *pos_val;
nsAString pos_str;
const WCHAR *val;
DWORD val_len;
HRESULT hres;
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
hres = var_to_styleval(This, &v, STYLEID_BACKGROUND_POSITION_X, buf, &val);
if(FAILED(hres))
return hres;
val_len = val ? strlenW(val) : 0;
nsAString_Init(&pos_str, NULL);
hres = get_nsstyle_attr_nsval(This->nsstyle, STYLEID_BACKGROUND_POSITION, &pos_str);
if(SUCCEEDED(hres)) {
const PRUnichar *pos, *posy;
DWORD posy_len;
nsAString_GetData(&pos_str, &pos);
posy = strchrW(pos, ' ');
if(!posy) {
static const WCHAR zero_pxW[] = {' ','0','p','x',0};
TRACE("no space in %s\n", debugstr_w(pos));
posy = zero_pxW;
}
posy_len = strlenW(posy);
pos_val = heap_alloc((val_len+posy_len+1)*sizeof(WCHAR));
if(pos_val) {
if(val_len)
memcpy(pos_val, val, val_len*sizeof(WCHAR));
if(posy_len)
memcpy(pos_val+val_len, posy, posy_len*sizeof(WCHAR));
pos_val[val_len+posy_len] = 0;
}else {
hres = E_OUTOFMEMORY;
}
}
nsAString_Finish(&pos_str);
if(FAILED(hres))
return hres;
TRACE("setting position to %s\n", debugstr_w(pos_val));
hres = set_style_property(This, STYLEID_BACKGROUND_POSITION, pos_val);
heap_free(pos_val);
return hres;
}
static HRESULT WINAPI HTMLStyle_get_backgroundPositionX(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
nsAString pos_str;
BSTR ret;
HRESULT hres;
TRACE("(%p)->(%p)\n", This, p);
nsAString_Init(&pos_str, NULL);
hres = get_nsstyle_attr_nsval(This->nsstyle, STYLEID_BACKGROUND_POSITION, &pos_str);
if(SUCCEEDED(hres)) {
const PRUnichar *pos, *space;
nsAString_GetData(&pos_str, &pos);
space = strchrW(pos, ' ');
if(!space) {
WARN("no space in %s\n", debugstr_w(pos));
space = pos + strlenW(pos);
}
if(space != pos) {
ret = SysAllocStringLen(pos, space-pos);
if(!ret)
hres = E_OUTOFMEMORY;
}else {
ret = NULL;
}
}
nsAString_Finish(&pos_str);
if(FAILED(hres))
return hres;
TRACE("returning %s\n", debugstr_w(ret));
V_VT(p) = VT_BSTR;
V_BSTR(p) = ret;
return S_OK;
}
static HRESULT WINAPI HTMLStyle_put_backgroundPositionY(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
WCHAR buf[14], *pos_val;
nsAString pos_str;
const WCHAR *val;
DWORD val_len;
HRESULT hres;
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
hres = var_to_styleval(This, &v, STYLEID_BACKGROUND_POSITION, buf, &val);
if(FAILED(hres))
return hres;
val_len = val ? strlenW(val) : 0;
nsAString_Init(&pos_str, NULL);
hres = get_nsstyle_attr_nsval(This->nsstyle, STYLEID_BACKGROUND_POSITION, &pos_str);
if(SUCCEEDED(hres)) {
const PRUnichar *pos, *space;
DWORD posx_len;
nsAString_GetData(&pos_str, &pos);
space = strchrW(pos, ' ');
if(space) {
space++;
}else {
static const WCHAR zero_pxW[] = {'0','p','x',' ',0};
TRACE("no space in %s\n", debugstr_w(pos));
pos = zero_pxW;
space = pos + ARRAY_SIZE(zero_pxW)-1;
}
posx_len = space-pos;
pos_val = heap_alloc((posx_len+val_len+1)*sizeof(WCHAR));
if(pos_val) {
memcpy(pos_val, pos, posx_len*sizeof(WCHAR));
if(val_len)
memcpy(pos_val+posx_len, val, val_len*sizeof(WCHAR));
pos_val[posx_len+val_len] = 0;
}else {
hres = E_OUTOFMEMORY;
}
}
nsAString_Finish(&pos_str);
if(FAILED(hres))
return hres;
TRACE("setting position to %s\n", debugstr_w(pos_val));
hres = set_style_property(This, STYLEID_BACKGROUND_POSITION, pos_val);
heap_free(pos_val);
return hres;
}
static HRESULT WINAPI HTMLStyle_get_backgroundPositionY(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
nsAString pos_str;
BSTR ret;
HRESULT hres;
TRACE("(%p)->(%p)\n", This, p);
nsAString_Init(&pos_str, NULL);
hres = get_nsstyle_attr_nsval(This->nsstyle, STYLEID_BACKGROUND_POSITION, &pos_str);
if(SUCCEEDED(hres)) {
const PRUnichar *pos, *posy;
nsAString_GetData(&pos_str, &pos);
posy = strchrW(pos, ' ');
if(posy) {
ret = SysAllocString(posy+1);
if(!ret)
hres = E_OUTOFMEMORY;
}else {
ret = NULL;
}
}
nsAString_Finish(&pos_str);
if(FAILED(hres))
return hres;
TRACE("returning %s\n", debugstr_w(ret));
V_VT(p) = VT_BSTR;
V_BSTR(p) = ret;
return S_OK;
}
static HRESULT WINAPI HTMLStyle_put_wordSpacing(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_WORD_SPACING, &v);
}
static HRESULT WINAPI HTMLStyle_get_wordSpacing(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_WORD_SPACING, p);
}
static HRESULT WINAPI HTMLStyle_put_letterSpacing(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_LETTER_SPACING, &v);
}
static HRESULT WINAPI HTMLStyle_get_letterSpacing(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_LETTER_SPACING, p);
}
static HRESULT WINAPI HTMLStyle_put_textDecoration(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_TEXT_DECORATION , v);
}
static HRESULT WINAPI HTMLStyle_get_textDecoration(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_TEXT_DECORATION, p);
}
static HRESULT WINAPI HTMLStyle_put_textDecorationNone(IHTMLStyle *iface, VARIANT_BOOL v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%x)\n", This, v);
return set_style_property(This, STYLEID_TEXT_DECORATION, v ? noneW : emptyW);
}
static HRESULT WINAPI HTMLStyle_get_textDecorationNone(IHTMLStyle *iface, VARIANT_BOOL *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return check_style_attr_value(This, STYLEID_TEXT_DECORATION, noneW, p);
}
static HRESULT WINAPI HTMLStyle_put_textDecorationUnderline(IHTMLStyle *iface, VARIANT_BOOL v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%x)\n", This, v);
return set_style_property(This, STYLEID_TEXT_DECORATION, v ? underlineW : emptyW);
}
static HRESULT WINAPI HTMLStyle_get_textDecorationUnderline(IHTMLStyle *iface, VARIANT_BOOL *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return check_style_attr_value(This, STYLEID_TEXT_DECORATION, underlineW, p);
}
static HRESULT WINAPI HTMLStyle_put_textDecorationOverline(IHTMLStyle *iface, VARIANT_BOOL v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%x)\n", This, v);
return set_style_property(This, STYLEID_TEXT_DECORATION, v ? overlineW : emptyW);
}
static HRESULT WINAPI HTMLStyle_get_textDecorationOverline(IHTMLStyle *iface, VARIANT_BOOL *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return check_style_attr_value(This, STYLEID_TEXT_DECORATION, overlineW, p);
}
static HRESULT WINAPI HTMLStyle_put_textDecorationLineThrough(IHTMLStyle *iface, VARIANT_BOOL v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%x)\n", This, v);
return set_style_property(This, STYLEID_TEXT_DECORATION, v ? line_throughW : emptyW);
}
static HRESULT WINAPI HTMLStyle_get_textDecorationLineThrough(IHTMLStyle *iface, VARIANT_BOOL *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return check_style_attr_value(This, STYLEID_TEXT_DECORATION, line_throughW, p);
}
static HRESULT WINAPI HTMLStyle_put_textDecorationBlink(IHTMLStyle *iface, VARIANT_BOOL v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%x)\n", This, v);
return set_style_property(This, STYLEID_TEXT_DECORATION, v ? blinkW : emptyW);
}
static HRESULT WINAPI HTMLStyle_get_textDecorationBlink(IHTMLStyle *iface, VARIANT_BOOL *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return check_style_attr_value(This, STYLEID_TEXT_DECORATION, blinkW, p);
}
static HRESULT WINAPI HTMLStyle_put_verticalAlign(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_VERTICAL_ALIGN, &v);
}
static HRESULT WINAPI HTMLStyle_get_verticalAlign(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_VERTICAL_ALIGN, p);
}
static HRESULT WINAPI HTMLStyle_put_textTransform(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_TEXT_TRANSFORM, v);
}
static HRESULT WINAPI HTMLStyle_get_textTransform(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_TEXT_TRANSFORM, p);
}
static HRESULT WINAPI HTMLStyle_put_textAlign(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_TEXT_ALIGN, v);
}
static HRESULT WINAPI HTMLStyle_get_textAlign(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_TEXT_ALIGN, p);
}
static HRESULT WINAPI HTMLStyle_put_textIndent(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_TEXT_INDENT, &v);
}
static HRESULT WINAPI HTMLStyle_get_textIndent(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_TEXT_INDENT, p);
}
static HRESULT WINAPI HTMLStyle_put_lineHeight(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_LINE_HEIGHT, &v);
}
static HRESULT WINAPI HTMLStyle_get_lineHeight(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_LINE_HEIGHT, p);
}
static HRESULT WINAPI HTMLStyle_put_marginTop(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_MARGIN_TOP, &v);
}
static HRESULT WINAPI HTMLStyle_get_marginTop(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_MARGIN_TOP, p);
}
static HRESULT WINAPI HTMLStyle_put_marginRight(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_MARGIN_RIGHT, &v);
}
static HRESULT WINAPI HTMLStyle_get_marginRight(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_MARGIN_RIGHT, p);
}
static HRESULT WINAPI HTMLStyle_put_marginBottom(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_MARGIN_BOTTOM, &v);
}
static HRESULT WINAPI HTMLStyle_get_marginBottom(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_MARGIN_BOTTOM, p);
}
static HRESULT WINAPI HTMLStyle_put_marginLeft(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_MARGIN_LEFT, &v);
}
static HRESULT WINAPI HTMLStyle_put_margin(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_MARGIN, v);
}
static HRESULT WINAPI HTMLStyle_get_margin(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_MARGIN, p);
}
static HRESULT WINAPI HTMLStyle_get_marginLeft(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_MARGIN_LEFT, p);
}
static HRESULT WINAPI HTMLStyle_put_paddingTop(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_PADDING_TOP, &v);
}
static HRESULT WINAPI HTMLStyle_get_paddingTop(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_PADDING_TOP, p);
}
static HRESULT WINAPI HTMLStyle_put_paddingRight(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_PADDING_RIGHT, &v);
}
static HRESULT WINAPI HTMLStyle_get_paddingRight(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_PADDING_RIGHT, p);
}
static HRESULT WINAPI HTMLStyle_put_paddingBottom(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_PADDING_BOTTOM, &v);
}
static HRESULT WINAPI HTMLStyle_get_paddingBottom(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_PADDING_BOTTOM, p);
}
static HRESULT WINAPI HTMLStyle_put_paddingLeft(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_PADDING_LEFT, &v);
}
static HRESULT WINAPI HTMLStyle_get_paddingLeft(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_PADDING_LEFT, p);
}
static HRESULT WINAPI HTMLStyle_put_padding(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_PADDING, v);
}
static HRESULT WINAPI HTMLStyle_get_padding(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_PADDING, p);
}
static HRESULT WINAPI HTMLStyle_put_border(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BORDER, v);
}
static HRESULT WINAPI HTMLStyle_get_border(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BORDER, p);
}
static HRESULT WINAPI HTMLStyle_put_borderTop(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BORDER_TOP, v);
}
static HRESULT WINAPI HTMLStyle_get_borderTop(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BORDER_TOP, p);
}
static HRESULT WINAPI HTMLStyle_put_borderRight(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BORDER_RIGHT, v);
}
static HRESULT WINAPI HTMLStyle_get_borderRight(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BORDER_RIGHT, p);
}
static HRESULT WINAPI HTMLStyle_put_borderBottom(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BORDER_BOTTOM, v);
}
static HRESULT WINAPI HTMLStyle_get_borderBottom(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BORDER_BOTTOM, p);
}
static HRESULT WINAPI HTMLStyle_put_borderLeft(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BORDER_LEFT, v);
}
static HRESULT WINAPI HTMLStyle_get_borderLeft(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BORDER_LEFT, p);
}
static HRESULT WINAPI HTMLStyle_put_borderColor(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BORDER_COLOR, v);
}
static HRESULT WINAPI HTMLStyle_get_borderColor(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BORDER_COLOR, p);
}
static HRESULT WINAPI HTMLStyle_put_borderTopColor(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_BORDER_TOP_COLOR, &v);
}
static HRESULT WINAPI HTMLStyle_get_borderTopColor(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_BORDER_TOP_COLOR, p);
}
static HRESULT WINAPI HTMLStyle_put_borderRightColor(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_BORDER_RIGHT_COLOR, &v);
}
static HRESULT WINAPI HTMLStyle_get_borderRightColor(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_BORDER_RIGHT_COLOR, p);
}
static HRESULT WINAPI HTMLStyle_put_borderBottomColor(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_BORDER_BOTTOM_COLOR, &v);
}
static HRESULT WINAPI HTMLStyle_get_borderBottomColor(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_BORDER_BOTTOM_COLOR, p);
}
static HRESULT WINAPI HTMLStyle_put_borderLeftColor(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_BORDER_LEFT_COLOR, &v);
}
static HRESULT WINAPI HTMLStyle_get_borderLeftColor(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_BORDER_LEFT_COLOR, p);
}
static HRESULT WINAPI HTMLStyle_put_borderWidth(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BORDER_WIDTH, v);
}
static HRESULT WINAPI HTMLStyle_get_borderWidth(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BORDER_WIDTH, p);
}
static HRESULT WINAPI HTMLStyle_put_borderTopWidth(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_BORDER_TOP_WIDTH, &v);
}
static HRESULT WINAPI HTMLStyle_get_borderTopWidth(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_BORDER_TOP_WIDTH, p);
}
static HRESULT WINAPI HTMLStyle_put_borderRightWidth(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_BORDER_RIGHT_WIDTH, &v);
}
static HRESULT WINAPI HTMLStyle_get_borderRightWidth(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_BORDER_RIGHT_WIDTH, p);
}
static HRESULT WINAPI HTMLStyle_put_borderBottomWidth(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_BORDER_BOTTOM_WIDTH, &v);
}
static HRESULT WINAPI HTMLStyle_get_borderBottomWidth(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_BORDER_BOTTOM_WIDTH, p);
}
static HRESULT WINAPI HTMLStyle_put_borderLeftWidth(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_BORDER_LEFT_WIDTH, &v);
}
static HRESULT WINAPI HTMLStyle_get_borderLeftWidth(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_BORDER_LEFT_WIDTH, p);
}
static HRESULT WINAPI HTMLStyle_put_borderStyle(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
static const WCHAR styleWindowInset[] = {'w','i','n','d','o','w','-','i','n','s','e','t',0};
HRESULT hres = S_OK;
BSTR pstyle;
int i=0;
int last = 0;
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
while(v[i] && hres == S_OK)
{
if(v[i] == (WCHAR)' ')
{
pstyle = SysAllocStringLen(&v[last], (i-last));
if( !(is_valid_border_style(pstyle) || strcmpiW(styleWindowInset, pstyle) == 0))
{
TRACE("1. Invalid style (%s)\n", debugstr_w(pstyle));
hres = E_INVALIDARG;
}
SysFreeString(pstyle);
last = i+1;
}
i++;
}
if(hres == S_OK)
{
pstyle = SysAllocStringLen(&v[last], i-last);
if( !(is_valid_border_style(pstyle) || strcmpiW(styleWindowInset, pstyle) == 0))
{
TRACE("2. Invalid style (%s)\n", debugstr_w(pstyle));
hres = E_INVALIDARG;
}
SysFreeString(pstyle);
}
if(hres == S_OK)
hres = set_style_property(This, STYLEID_BORDER_STYLE, v);
return hres;
}
static HRESULT WINAPI HTMLStyle_get_borderStyle(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BORDER_STYLE, p);
}
static HRESULT WINAPI HTMLStyle_put_borderTopStyle(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BORDER_TOP_STYLE, v);
}
static HRESULT WINAPI HTMLStyle_get_borderTopStyle(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BORDER_TOP_STYLE, p);
}
static HRESULT WINAPI HTMLStyle_put_borderRightStyle(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BORDER_RIGHT_STYLE, v);
}
static HRESULT WINAPI HTMLStyle_get_borderRightStyle(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BORDER_RIGHT_STYLE, p);
}
static HRESULT WINAPI HTMLStyle_put_borderBottomStyle(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BORDER_BOTTOM_STYLE, v);
}
static HRESULT WINAPI HTMLStyle_get_borderBottomStyle(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BORDER_BOTTOM_STYLE, p);
}
static HRESULT WINAPI HTMLStyle_put_borderLeftStyle(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BORDER_LEFT_STYLE, v);
}
static HRESULT WINAPI HTMLStyle_get_borderLeftStyle(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BORDER_LEFT_STYLE, p);
}
static HRESULT WINAPI HTMLStyle_put_width(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_WIDTH, &v);
}
static HRESULT WINAPI HTMLStyle_get_width(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_WIDTH, p);
}
static HRESULT WINAPI HTMLStyle_put_height(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_HEIGHT, &v);
}
static HRESULT WINAPI HTMLStyle_get_height(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_HEIGHT, p);
}
static HRESULT WINAPI HTMLStyle_put_styleFloat(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_FLOAT, v);
}
static HRESULT WINAPI HTMLStyle_get_styleFloat(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_FLOAT, p);
}
static HRESULT WINAPI HTMLStyle_put_clear(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_CLEAR, v);
}
static HRESULT WINAPI HTMLStyle_get_clear(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_CLEAR, p);
}
static HRESULT WINAPI HTMLStyle_put_display(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_DISPLAY, v);
}
static HRESULT WINAPI HTMLStyle_get_display(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_DISPLAY, p);
}
static HRESULT WINAPI HTMLStyle_put_visibility(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_VISIBILITY, v);
}
static HRESULT WINAPI HTMLStyle_get_visibility(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_VISIBILITY, p);
}
static HRESULT WINAPI HTMLStyle_put_listStyleType(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_LISTSTYLETYPE, v);
}
static HRESULT WINAPI HTMLStyle_get_listStyleType(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_LISTSTYLETYPE, p);
}
static HRESULT WINAPI HTMLStyle_put_listStylePosition(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_LISTSTYLEPOSITION, v);
}
static HRESULT WINAPI HTMLStyle_get_listStylePosition(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_LISTSTYLEPOSITION, p);
}
static HRESULT WINAPI HTMLStyle_put_listStyleImage(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle_get_listStyleImage(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle_put_listStyle(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_LIST_STYLE, v);
}
static HRESULT WINAPI HTMLStyle_get_listStyle(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_LIST_STYLE, p);
}
static HRESULT WINAPI HTMLStyle_put_whiteSpace(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_WHITE_SPACE, v);
}
static HRESULT WINAPI HTMLStyle_get_whiteSpace(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_WHITE_SPACE, p);
}
static HRESULT WINAPI HTMLStyle_put_top(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_TOP, &v);
}
static HRESULT WINAPI HTMLStyle_get_top(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_TOP, p);
}
static HRESULT WINAPI HTMLStyle_put_left(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_LEFT, &v);
}
static HRESULT WINAPI HTMLStyle_get_left(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_LEFT, p);
}
static HRESULT WINAPI HTMLStyle_get_position(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return IHTMLStyle2_get_position(&This->IHTMLStyle2_iface, p);
}
static HRESULT WINAPI HTMLStyle_put_zIndex(IHTMLStyle *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_Z_INDEX, &v);
}
static HRESULT WINAPI HTMLStyle_get_zIndex(IHTMLStyle *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_Z_INDEX, p);
}
static HRESULT WINAPI HTMLStyle_put_overflow(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_OVERFLOW, v);
}
static HRESULT WINAPI HTMLStyle_get_overflow(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
if(!p)
return E_INVALIDARG;
return get_style_property(This, STYLEID_OVERFLOW, p);
}
static HRESULT WINAPI HTMLStyle_put_pageBreakBefore(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_PAGE_BREAK_BEFORE, v);
}
static HRESULT WINAPI HTMLStyle_get_pageBreakBefore(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_PAGE_BREAK_BEFORE, p);
}
static HRESULT WINAPI HTMLStyle_put_pageBreakAfter(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_PAGE_BREAK_AFTER, v);
}
static HRESULT WINAPI HTMLStyle_get_pageBreakAfter(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_PAGE_BREAK_AFTER, p);
}
static HRESULT WINAPI HTMLStyle_put_cssText(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return IHTMLCSSStyleDeclaration_put_cssText(&This->IHTMLCSSStyleDeclaration_iface, v);
}
static HRESULT WINAPI HTMLStyle_get_cssText(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return IHTMLCSSStyleDeclaration_get_cssText(&This->IHTMLCSSStyleDeclaration_iface, p);
}
static HRESULT WINAPI HTMLStyle_put_pixelTop(IHTMLStyle *iface, LONG v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%d)\n", This, v);
return set_style_pxattr(This, STYLEID_TOP, v);
}
static HRESULT WINAPI HTMLStyle_get_pixelTop(IHTMLStyle *iface, LONG *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_nsstyle_pixel_val(This, STYLEID_TOP, p);
}
static HRESULT WINAPI HTMLStyle_put_pixelLeft(IHTMLStyle *iface, LONG v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%d)\n", This, v);
return set_style_pxattr(This, STYLEID_LEFT, v);
}
static HRESULT WINAPI HTMLStyle_get_pixelLeft(IHTMLStyle *iface, LONG *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_nsstyle_pixel_val(This, STYLEID_LEFT, p);
}
static HRESULT WINAPI HTMLStyle_put_pixelWidth(IHTMLStyle *iface, LONG v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->()\n", This);
return set_style_pxattr(This, STYLEID_WIDTH, v);
}
static HRESULT WINAPI HTMLStyle_get_pixelWidth(IHTMLStyle *iface, LONG *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_nsstyle_pixel_val(This, STYLEID_WIDTH, p);
}
static HRESULT WINAPI HTMLStyle_put_pixelHeight(IHTMLStyle *iface, LONG v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%d)\n", This, v);
return set_style_pxattr(This, STYLEID_HEIGHT, v);
}
static HRESULT WINAPI HTMLStyle_get_pixelHeight(IHTMLStyle *iface, LONG *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_nsstyle_pixel_val(This, STYLEID_HEIGHT, p);
}
static HRESULT WINAPI HTMLStyle_put_posTop(IHTMLStyle *iface, float v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%f)\n", This, v);
return set_style_pos(This, STYLEID_TOP, v);
}
static HRESULT WINAPI HTMLStyle_get_posTop(IHTMLStyle *iface, float *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
if(!p)
return E_POINTER;
return get_nsstyle_pos(This, STYLEID_TOP, p);
}
static HRESULT WINAPI HTMLStyle_put_posLeft(IHTMLStyle *iface, float v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%f)\n", This, v);
return set_style_pos(This, STYLEID_LEFT, v);
}
static HRESULT WINAPI HTMLStyle_get_posLeft(IHTMLStyle *iface, float *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
if(!p)
return E_POINTER;
return get_nsstyle_pos(This, STYLEID_LEFT, p);
}
static HRESULT WINAPI HTMLStyle_put_posWidth(IHTMLStyle *iface, float v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%f)\n", This, v);
return set_style_pos(This, STYLEID_WIDTH, v);
}
static HRESULT WINAPI HTMLStyle_get_posWidth(IHTMLStyle *iface, float *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
if(!p)
return E_POINTER;
if(get_nsstyle_pos(This, STYLEID_WIDTH, p) != S_OK)
*p = 0.0f;
return S_OK;
}
static HRESULT WINAPI HTMLStyle_put_posHeight(IHTMLStyle *iface, float v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%f)\n", This, v);
return set_style_pos(This, STYLEID_HEIGHT, v);
}
static HRESULT WINAPI HTMLStyle_get_posHeight(IHTMLStyle *iface, float *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
if(!p)
return E_POINTER;
if(get_nsstyle_pos(This, STYLEID_HEIGHT, p) != S_OK)
*p = 0.0f;
return S_OK;
}
static HRESULT WINAPI HTMLStyle_put_cursor(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_CURSOR, v);
}
static HRESULT WINAPI HTMLStyle_get_cursor(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_CURSOR, p);
}
static HRESULT WINAPI HTMLStyle_put_clip(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_CLIP, v);
}
static HRESULT WINAPI HTMLStyle_get_clip(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_CLIP, p);
}
static void set_opacity(HTMLStyle *This, const WCHAR *val)
{
nsAString name_str, val_str, empty_str;
nsresult nsres;
static const WCHAR opacityW[] = {'o','p','a','c','i','t','y',0};
TRACE("%s\n", debugstr_w(val));
nsAString_InitDepend(&name_str, opacityW);
nsAString_InitDepend(&val_str, val);
nsAString_InitDepend(&empty_str, emptyW);
nsres = nsIDOMCSSStyleDeclaration_SetProperty(This->nsstyle, &name_str, &val_str, &empty_str);
if(NS_FAILED(nsres))
ERR("SetProperty failed: %08x\n", nsres);
nsAString_Finish(&name_str);
nsAString_Finish(&val_str);
nsAString_Finish(&empty_str);
}
static void update_filter(HTMLStyle *This)
{
const WCHAR *ptr, *ptr2;
static const WCHAR alphaW[] = {'a','l','p','h','a'};
if(dispex_compat_mode(&This->dispex) >= COMPAT_MODE_IE10)
return;
ptr = This->elem->filter;
TRACE("%s\n", debugstr_w(ptr));
if(!ptr) {
set_opacity(This, emptyW);
return;
}
while(1) {
while(isspaceW(*ptr))
ptr++;
if(!*ptr)
break;
ptr2 = ptr;
while(isalnumW(*ptr))
ptr++;
if(ptr == ptr2) {
WARN("unexpected char '%c'\n", *ptr);
break;
}
if(*ptr != '(') {
WARN("expected '('\n");
continue;
}
if(ptr2 + ARRAY_SIZE(alphaW) == ptr && !memcmp(ptr2, alphaW, sizeof(alphaW))) {
static const WCHAR formatW[] = {'%','f',0};
static const WCHAR opacityW[] = {'o','p','a','c','i','t','y','='};
ptr++;
do {
while(isspaceW(*ptr))
ptr++;
ptr2 = ptr;
while(*ptr && *ptr != ',' && *ptr != ')')
ptr++;
if(!*ptr) {
WARN("unexpected end of string\n");
break;
}
if(ptr-ptr2 > ARRAY_SIZE(opacityW) && !memcmp(ptr2, opacityW, sizeof(opacityW))) {
float fval = 0.0f, e = 0.1f;
WCHAR buf[32];
ptr2 += ARRAY_SIZE(opacityW);
while(isdigitW(*ptr2))
fval = fval*10.0f + (float)(*ptr2++ - '0');
if(*ptr2 == '.') {
while(isdigitW(*++ptr2)) {
fval += e * (float)(*ptr2++ - '0');
e *= 0.1f;
}
}
sprintfW(buf, formatW, fval * 0.01f);
set_opacity(This, buf);
}else {
FIXME("unknown param %s\n", debugstr_wn(ptr2, ptr-ptr2));
}
if(*ptr == ',')
ptr++;
}while(*ptr != ')');
}else {
FIXME("unknown filter %s\n", debugstr_wn(ptr2, ptr-ptr2));
ptr = strchrW(ptr, ')');
if(!ptr)
break;
ptr++;
}
}
}
static HRESULT WINAPI HTMLStyle_put_filter(IHTMLStyle *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
WCHAR *new_filter = NULL;
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
if(!This->elem) {
FIXME("Element already destroyed\n");
return E_UNEXPECTED;
}
if(v) {
new_filter = heap_strdupW(v);
if(!new_filter)
return E_OUTOFMEMORY;
}
heap_free(This->elem->filter);
This->elem->filter = new_filter;
update_filter(This);
return S_OK;
}
static HRESULT WINAPI HTMLStyle_get_filter(IHTMLStyle *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
TRACE("(%p)->(%p)\n", This, p);
if(!This->elem) {
FIXME("Element already destroyed\n");
return E_UNEXPECTED;
}
if(This->elem->filter) {
*p = SysAllocString(This->elem->filter);
if(!*p)
return E_OUTOFMEMORY;
}else {
*p = NULL;
}
return S_OK;
}
static HRESULT WINAPI HTMLStyle_setAttribute(IHTMLStyle *iface, BSTR strAttributeName,
VARIANT AttributeValue, LONG lFlags)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
HRESULT hres;
DISPID dispid;
TRACE("(%p)->(%s %s %08x)\n", This, debugstr_w(strAttributeName),
debugstr_variant(&AttributeValue), lFlags);
if(!strAttributeName)
return E_INVALIDARG;
if(lFlags == 1)
FIXME("Parameter lFlags ignored\n");
hres = HTMLStyle_GetIDsOfNames(iface, &IID_NULL, &strAttributeName, 1,
LOCALE_USER_DEFAULT, &dispid);
if(hres == S_OK)
{
VARIANT ret;
DISPID dispidNamed = DISPID_PROPERTYPUT;
DISPPARAMS params;
params.cArgs = 1;
params.rgvarg = &AttributeValue;
params.cNamedArgs = 1;
params.rgdispidNamedArgs = &dispidNamed;
hres = HTMLStyle_Invoke(iface, dispid, &IID_NULL, LOCALE_SYSTEM_DEFAULT,
DISPATCH_PROPERTYPUT, ¶ms, &ret, NULL, NULL);
}
else
{
FIXME("Custom attributes not supported.\n");
}
TRACE("ret: %08x\n", hres);
return hres;
}
static HRESULT WINAPI HTMLStyle_getAttribute(IHTMLStyle *iface, BSTR strAttributeName,
LONG lFlags, VARIANT *AttributeValue)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
HRESULT hres;
DISPID dispid;
TRACE("(%p)->(%s v%p %08x)\n", This, debugstr_w(strAttributeName),
AttributeValue, lFlags);
if(!AttributeValue || !strAttributeName)
return E_INVALIDARG;
if(lFlags == 1)
FIXME("Parameter lFlags ignored\n");
hres = HTMLStyle_GetIDsOfNames(iface, &IID_NULL, &strAttributeName, 1,
LOCALE_USER_DEFAULT, &dispid);
if(hres == S_OK)
{
DISPPARAMS params = {NULL, NULL, 0, 0 };
hres = HTMLStyle_Invoke(iface, dispid, &IID_NULL, LOCALE_SYSTEM_DEFAULT,
DISPATCH_PROPERTYGET, ¶ms, AttributeValue, NULL, NULL);
}
else
{
FIXME("Custom attributes not supported.\n");
}
return hres;
}
static HRESULT WINAPI HTMLStyle_removeAttribute(IHTMLStyle *iface, BSTR strAttributeName,
LONG lFlags, VARIANT_BOOL *pfSuccess)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
const style_tbl_entry_t *style_entry;
nsAString name_str, ret_str;
nsresult nsres;
HRESULT hres;
TRACE("(%p)->(%s %08x %p)\n", This, debugstr_w(strAttributeName), lFlags, pfSuccess);
style_entry = lookup_style_tbl(strAttributeName);
if(!style_entry) {
compat_mode_t compat_mode = dispex_compat_mode(&This->dispex);
DISPID dispid;
unsigned i;
hres = IDispatchEx_GetDispID(&This->dispex.IDispatchEx_iface, strAttributeName,
(lFlags&1) ? fdexNameCaseSensitive : fdexNameCaseInsensitive, &dispid);
if(hres != S_OK) {
*pfSuccess = VARIANT_FALSE;
return S_OK;
}
for(i=0; i < ARRAY_SIZE(style_tbl); i++) {
if(dispid == (compat_mode >= COMPAT_MODE_IE9
? style_tbl[i].dispid : style_tbl[i].compat_dispid))
break;
}
if(i == ARRAY_SIZE(style_tbl))
return remove_attribute(&This->dispex, dispid, pfSuccess);
style_entry = style_tbl+i;
}
/* filter property is a special case */
if(style_entry->compat_dispid == DISPID_IHTMLSTYLE_FILTER) {
*pfSuccess = variant_bool(This->elem->filter && *This->elem->filter);
heap_free(This->elem->filter);
This->elem->filter = NULL;
update_filter(This);
return S_OK;
}
nsAString_InitDepend(&name_str, style_entry->name);
nsAString_Init(&ret_str, NULL);
nsres = nsIDOMCSSStyleDeclaration_RemoveProperty(This->nsstyle, &name_str, &ret_str);
if(NS_SUCCEEDED(nsres)) {
const PRUnichar *ret;
nsAString_GetData(&ret_str, &ret);
*pfSuccess = variant_bool(*ret);
}else {
ERR("RemoveProperty failed: %08x\n", nsres);
}
nsAString_Finish(&name_str);
nsAString_Finish(&ret_str);
return NS_SUCCEEDED(nsres) ? S_OK : E_FAIL;
}
static HRESULT WINAPI HTMLStyle_toString(IHTMLStyle *iface, BSTR *String)
{
HTMLStyle *This = impl_from_IHTMLStyle(iface);
FIXME("(%p)->(%p)\n", This, String);
return E_NOTIMPL;
}
static const IHTMLStyleVtbl HTMLStyleVtbl = {
HTMLStyle_QueryInterface,
HTMLStyle_AddRef,
HTMLStyle_Release,
HTMLStyle_GetTypeInfoCount,
HTMLStyle_GetTypeInfo,
HTMLStyle_GetIDsOfNames,
HTMLStyle_Invoke,
HTMLStyle_put_fontFamily,
HTMLStyle_get_fontFamily,
HTMLStyle_put_fontStyle,
HTMLStyle_get_fontStyle,
HTMLStyle_put_fontVariant,
HTMLStyle_get_fontVariant,
HTMLStyle_put_fontWeight,
HTMLStyle_get_fontWeight,
HTMLStyle_put_fontSize,
HTMLStyle_get_fontSize,
HTMLStyle_put_font,
HTMLStyle_get_font,
HTMLStyle_put_color,
HTMLStyle_get_color,
HTMLStyle_put_background,
HTMLStyle_get_background,
HTMLStyle_put_backgroundColor,
HTMLStyle_get_backgroundColor,
HTMLStyle_put_backgroundImage,
HTMLStyle_get_backgroundImage,
HTMLStyle_put_backgroundRepeat,
HTMLStyle_get_backgroundRepeat,
HTMLStyle_put_backgroundAttachment,
HTMLStyle_get_backgroundAttachment,
HTMLStyle_put_backgroundPosition,
HTMLStyle_get_backgroundPosition,
HTMLStyle_put_backgroundPositionX,
HTMLStyle_get_backgroundPositionX,
HTMLStyle_put_backgroundPositionY,
HTMLStyle_get_backgroundPositionY,
HTMLStyle_put_wordSpacing,
HTMLStyle_get_wordSpacing,
HTMLStyle_put_letterSpacing,
HTMLStyle_get_letterSpacing,
HTMLStyle_put_textDecoration,
HTMLStyle_get_textDecoration,
HTMLStyle_put_textDecorationNone,
HTMLStyle_get_textDecorationNone,
HTMLStyle_put_textDecorationUnderline,
HTMLStyle_get_textDecorationUnderline,
HTMLStyle_put_textDecorationOverline,
HTMLStyle_get_textDecorationOverline,
HTMLStyle_put_textDecorationLineThrough,
HTMLStyle_get_textDecorationLineThrough,
HTMLStyle_put_textDecorationBlink,
HTMLStyle_get_textDecorationBlink,
HTMLStyle_put_verticalAlign,
HTMLStyle_get_verticalAlign,
HTMLStyle_put_textTransform,
HTMLStyle_get_textTransform,
HTMLStyle_put_textAlign,
HTMLStyle_get_textAlign,
HTMLStyle_put_textIndent,
HTMLStyle_get_textIndent,
HTMLStyle_put_lineHeight,
HTMLStyle_get_lineHeight,
HTMLStyle_put_marginTop,
HTMLStyle_get_marginTop,
HTMLStyle_put_marginRight,
HTMLStyle_get_marginRight,
HTMLStyle_put_marginBottom,
HTMLStyle_get_marginBottom,
HTMLStyle_put_marginLeft,
HTMLStyle_get_marginLeft,
HTMLStyle_put_margin,
HTMLStyle_get_margin,
HTMLStyle_put_paddingTop,
HTMLStyle_get_paddingTop,
HTMLStyle_put_paddingRight,
HTMLStyle_get_paddingRight,
HTMLStyle_put_paddingBottom,
HTMLStyle_get_paddingBottom,
HTMLStyle_put_paddingLeft,
HTMLStyle_get_paddingLeft,
HTMLStyle_put_padding,
HTMLStyle_get_padding,
HTMLStyle_put_border,
HTMLStyle_get_border,
HTMLStyle_put_borderTop,
HTMLStyle_get_borderTop,
HTMLStyle_put_borderRight,
HTMLStyle_get_borderRight,
HTMLStyle_put_borderBottom,
HTMLStyle_get_borderBottom,
HTMLStyle_put_borderLeft,
HTMLStyle_get_borderLeft,
HTMLStyle_put_borderColor,
HTMLStyle_get_borderColor,
HTMLStyle_put_borderTopColor,
HTMLStyle_get_borderTopColor,
HTMLStyle_put_borderRightColor,
HTMLStyle_get_borderRightColor,
HTMLStyle_put_borderBottomColor,
HTMLStyle_get_borderBottomColor,
HTMLStyle_put_borderLeftColor,
HTMLStyle_get_borderLeftColor,
HTMLStyle_put_borderWidth,
HTMLStyle_get_borderWidth,
HTMLStyle_put_borderTopWidth,
HTMLStyle_get_borderTopWidth,
HTMLStyle_put_borderRightWidth,
HTMLStyle_get_borderRightWidth,
HTMLStyle_put_borderBottomWidth,
HTMLStyle_get_borderBottomWidth,
HTMLStyle_put_borderLeftWidth,
HTMLStyle_get_borderLeftWidth,
HTMLStyle_put_borderStyle,
HTMLStyle_get_borderStyle,
HTMLStyle_put_borderTopStyle,
HTMLStyle_get_borderTopStyle,
HTMLStyle_put_borderRightStyle,
HTMLStyle_get_borderRightStyle,
HTMLStyle_put_borderBottomStyle,
HTMLStyle_get_borderBottomStyle,
HTMLStyle_put_borderLeftStyle,
HTMLStyle_get_borderLeftStyle,
HTMLStyle_put_width,
HTMLStyle_get_width,
HTMLStyle_put_height,
HTMLStyle_get_height,
HTMLStyle_put_styleFloat,
HTMLStyle_get_styleFloat,
HTMLStyle_put_clear,
HTMLStyle_get_clear,
HTMLStyle_put_display,
HTMLStyle_get_display,
HTMLStyle_put_visibility,
HTMLStyle_get_visibility,
HTMLStyle_put_listStyleType,
HTMLStyle_get_listStyleType,
HTMLStyle_put_listStylePosition,
HTMLStyle_get_listStylePosition,
HTMLStyle_put_listStyleImage,
HTMLStyle_get_listStyleImage,
HTMLStyle_put_listStyle,
HTMLStyle_get_listStyle,
HTMLStyle_put_whiteSpace,
HTMLStyle_get_whiteSpace,
HTMLStyle_put_top,
HTMLStyle_get_top,
HTMLStyle_put_left,
HTMLStyle_get_left,
HTMLStyle_get_position,
HTMLStyle_put_zIndex,
HTMLStyle_get_zIndex,
HTMLStyle_put_overflow,
HTMLStyle_get_overflow,
HTMLStyle_put_pageBreakBefore,
HTMLStyle_get_pageBreakBefore,
HTMLStyle_put_pageBreakAfter,
HTMLStyle_get_pageBreakAfter,
HTMLStyle_put_cssText,
HTMLStyle_get_cssText,
HTMLStyle_put_pixelTop,
HTMLStyle_get_pixelTop,
HTMLStyle_put_pixelLeft,
HTMLStyle_get_pixelLeft,
HTMLStyle_put_pixelWidth,
HTMLStyle_get_pixelWidth,
HTMLStyle_put_pixelHeight,
HTMLStyle_get_pixelHeight,
HTMLStyle_put_posTop,
HTMLStyle_get_posTop,
HTMLStyle_put_posLeft,
HTMLStyle_get_posLeft,
HTMLStyle_put_posWidth,
HTMLStyle_get_posWidth,
HTMLStyle_put_posHeight,
HTMLStyle_get_posHeight,
HTMLStyle_put_cursor,
HTMLStyle_get_cursor,
HTMLStyle_put_clip,
HTMLStyle_get_clip,
HTMLStyle_put_filter,
HTMLStyle_get_filter,
HTMLStyle_setAttribute,
HTMLStyle_getAttribute,
HTMLStyle_removeAttribute,
HTMLStyle_toString
};
static inline HTMLStyle *impl_from_IHTMLStyle2(IHTMLStyle2 *iface)
{
return CONTAINING_RECORD(iface, HTMLStyle, IHTMLStyle2_iface);
}
static HRESULT WINAPI HTMLStyle2_QueryInterface(IHTMLStyle2 *iface, REFIID riid, void **ppv)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
return IHTMLStyle_QueryInterface(&This->IHTMLStyle_iface, riid, ppv);
}
static ULONG WINAPI HTMLStyle2_AddRef(IHTMLStyle2 *iface)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
return IHTMLStyle_AddRef(&This->IHTMLStyle_iface);
}
static ULONG WINAPI HTMLStyle2_Release(IHTMLStyle2 *iface)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
return IHTMLStyle_Release(&This->IHTMLStyle_iface);
}
static HRESULT WINAPI HTMLStyle2_GetTypeInfoCount(IHTMLStyle2 *iface, UINT *pctinfo)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
return IDispatchEx_GetTypeInfoCount(&This->dispex.IDispatchEx_iface, pctinfo);
}
static HRESULT WINAPI HTMLStyle2_GetTypeInfo(IHTMLStyle2 *iface, UINT iTInfo,
LCID lcid, ITypeInfo **ppTInfo)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
return IDispatchEx_GetTypeInfo(&This->dispex.IDispatchEx_iface, iTInfo, lcid, ppTInfo);
}
static HRESULT WINAPI HTMLStyle2_GetIDsOfNames(IHTMLStyle2 *iface, REFIID riid,
LPOLESTR *rgszNames, UINT cNames,
LCID lcid, DISPID *rgDispId)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
return IDispatchEx_GetIDsOfNames(&This->dispex.IDispatchEx_iface, riid, rgszNames, cNames,
lcid, rgDispId);
}
static HRESULT WINAPI HTMLStyle2_Invoke(IHTMLStyle2 *iface, DISPID dispIdMember,
REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams,
VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
return IDispatchEx_Invoke(&This->dispex.IDispatchEx_iface, dispIdMember, riid, lcid,
wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr);
}
static HRESULT WINAPI HTMLStyle2_put_tableLayout(IHTMLStyle2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_TABLE_LAYOUT, v);
}
static HRESULT WINAPI HTMLStyle2_get_tableLayout(IHTMLStyle2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_TABLE_LAYOUT, p);
}
static HRESULT WINAPI HTMLStyle2_put_borderCollapse(IHTMLStyle2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_get_borderCollapse(IHTMLStyle2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_put_direction(IHTMLStyle2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_DIRECTION, v);
}
static HRESULT WINAPI HTMLStyle2_get_direction(IHTMLStyle2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_DIRECTION, p);
}
static HRESULT WINAPI HTMLStyle2_put_behavior(IHTMLStyle2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return S_OK;
}
static HRESULT WINAPI HTMLStyle2_get_behavior(IHTMLStyle2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_setExpression(IHTMLStyle2 *iface, BSTR propname, BSTR expression, BSTR language)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%s %s %s)\n", This, debugstr_w(propname), debugstr_w(expression), debugstr_w(language));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_getExpression(IHTMLStyle2 *iface, BSTR propname, VARIANT *expression)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%s %p)\n", This, debugstr_w(propname), expression);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_removeExpression(IHTMLStyle2 *iface, BSTR propname, VARIANT_BOOL *pfSuccess)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%s %p)\n", This, debugstr_w(propname), pfSuccess);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_put_position(IHTMLStyle2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_POSITION, v);
}
static HRESULT WINAPI HTMLStyle2_get_position(IHTMLStyle2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_POSITION, p);
}
static HRESULT WINAPI HTMLStyle2_put_unicodeBidi(IHTMLStyle2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_get_unicodeBidi(IHTMLStyle2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_put_bottom(IHTMLStyle2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_BOTTOM, &v);
}
static HRESULT WINAPI HTMLStyle2_get_bottom(IHTMLStyle2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_BOTTOM, p);
}
static HRESULT WINAPI HTMLStyle2_put_right(IHTMLStyle2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_RIGHT, &v);
}
static HRESULT WINAPI HTMLStyle2_get_right(IHTMLStyle2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_RIGHT, p);
}
static HRESULT WINAPI HTMLStyle2_put_pixelBottom(IHTMLStyle2 *iface, LONG v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%d)\n", This, v);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_get_pixelBottom(IHTMLStyle2 *iface, LONG *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_put_pixelRight(IHTMLStyle2 *iface, LONG v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%d)\n", This, v);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_get_pixelRight(IHTMLStyle2 *iface, LONG *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_put_posBottom(IHTMLStyle2 *iface, float v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%f)\n", This, v);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_get_posBottom(IHTMLStyle2 *iface, float *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_put_posRight(IHTMLStyle2 *iface, float v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%f)\n", This, v);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_get_posRight(IHTMLStyle2 *iface, float *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_put_imeMode(IHTMLStyle2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_get_imeMode(IHTMLStyle2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_put_rubyAlign(IHTMLStyle2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_get_rubyAlign(IHTMLStyle2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_put_rubyPosition(IHTMLStyle2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_get_rubyPosition(IHTMLStyle2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_put_rubyOverhang(IHTMLStyle2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_get_rubyOverhang(IHTMLStyle2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_put_layoutGridChar(IHTMLStyle2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_get_layoutGridChar(IHTMLStyle2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_put_layoutGridLine(IHTMLStyle2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_get_layoutGridLine(IHTMLStyle2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_put_layoutGridMode(IHTMLStyle2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_get_layoutGridMode(IHTMLStyle2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_put_layoutGridType(IHTMLStyle2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_get_layoutGridType(IHTMLStyle2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_put_layoutGrid(IHTMLStyle2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_get_layoutGrid(IHTMLStyle2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_put_wordBreak(IHTMLStyle2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_get_wordBreak(IHTMLStyle2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_put_lineBreak(IHTMLStyle2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_get_lineBreak(IHTMLStyle2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_put_textJustify(IHTMLStyle2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_get_textJustify(IHTMLStyle2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_put_textJustifyTrim(IHTMLStyle2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_get_textJustifyTrim(IHTMLStyle2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_put_textKashida(IHTMLStyle2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_get_textKashida(IHTMLStyle2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_put_textAutospace(IHTMLStyle2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_get_textAutospace(IHTMLStyle2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_put_overflowX(IHTMLStyle2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_OVERFLOW_X, v);
}
static HRESULT WINAPI HTMLStyle2_get_overflowX(IHTMLStyle2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_OVERFLOW_X, p);
}
static HRESULT WINAPI HTMLStyle2_put_overflowY(IHTMLStyle2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_OVERFLOW_Y, v);
}
static HRESULT WINAPI HTMLStyle2_get_overflowY(IHTMLStyle2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_OVERFLOW_Y, p);
}
static HRESULT WINAPI HTMLStyle2_put_accelerator(IHTMLStyle2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle2_get_accelerator(IHTMLStyle2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static const IHTMLStyle2Vtbl HTMLStyle2Vtbl = {
HTMLStyle2_QueryInterface,
HTMLStyle2_AddRef,
HTMLStyle2_Release,
HTMLStyle2_GetTypeInfoCount,
HTMLStyle2_GetTypeInfo,
HTMLStyle2_GetIDsOfNames,
HTMLStyle2_Invoke,
HTMLStyle2_put_tableLayout,
HTMLStyle2_get_tableLayout,
HTMLStyle2_put_borderCollapse,
HTMLStyle2_get_borderCollapse,
HTMLStyle2_put_direction,
HTMLStyle2_get_direction,
HTMLStyle2_put_behavior,
HTMLStyle2_get_behavior,
HTMLStyle2_setExpression,
HTMLStyle2_getExpression,
HTMLStyle2_removeExpression,
HTMLStyle2_put_position,
HTMLStyle2_get_position,
HTMLStyle2_put_unicodeBidi,
HTMLStyle2_get_unicodeBidi,
HTMLStyle2_put_bottom,
HTMLStyle2_get_bottom,
HTMLStyle2_put_right,
HTMLStyle2_get_right,
HTMLStyle2_put_pixelBottom,
HTMLStyle2_get_pixelBottom,
HTMLStyle2_put_pixelRight,
HTMLStyle2_get_pixelRight,
HTMLStyle2_put_posBottom,
HTMLStyle2_get_posBottom,
HTMLStyle2_put_posRight,
HTMLStyle2_get_posRight,
HTMLStyle2_put_imeMode,
HTMLStyle2_get_imeMode,
HTMLStyle2_put_rubyAlign,
HTMLStyle2_get_rubyAlign,
HTMLStyle2_put_rubyPosition,
HTMLStyle2_get_rubyPosition,
HTMLStyle2_put_rubyOverhang,
HTMLStyle2_get_rubyOverhang,
HTMLStyle2_put_layoutGridChar,
HTMLStyle2_get_layoutGridChar,
HTMLStyle2_put_layoutGridLine,
HTMLStyle2_get_layoutGridLine,
HTMLStyle2_put_layoutGridMode,
HTMLStyle2_get_layoutGridMode,
HTMLStyle2_put_layoutGridType,
HTMLStyle2_get_layoutGridType,
HTMLStyle2_put_layoutGrid,
HTMLStyle2_get_layoutGrid,
HTMLStyle2_put_wordBreak,
HTMLStyle2_get_wordBreak,
HTMLStyle2_put_lineBreak,
HTMLStyle2_get_lineBreak,
HTMLStyle2_put_textJustify,
HTMLStyle2_get_textJustify,
HTMLStyle2_put_textJustifyTrim,
HTMLStyle2_get_textJustifyTrim,
HTMLStyle2_put_textKashida,
HTMLStyle2_get_textKashida,
HTMLStyle2_put_textAutospace,
HTMLStyle2_get_textAutospace,
HTMLStyle2_put_overflowX,
HTMLStyle2_get_overflowX,
HTMLStyle2_put_overflowY,
HTMLStyle2_get_overflowY,
HTMLStyle2_put_accelerator,
HTMLStyle2_get_accelerator
};
static inline HTMLStyle *impl_from_IHTMLStyle3(IHTMLStyle3 *iface)
{
return CONTAINING_RECORD(iface, HTMLStyle, IHTMLStyle3_iface);
}
static HRESULT WINAPI HTMLStyle3_QueryInterface(IHTMLStyle3 *iface, REFIID riid, void **ppv)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
return IHTMLStyle_QueryInterface(&This->IHTMLStyle_iface, riid, ppv);
}
static ULONG WINAPI HTMLStyle3_AddRef(IHTMLStyle3 *iface)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
return IHTMLStyle_AddRef(&This->IHTMLStyle_iface);
}
static ULONG WINAPI HTMLStyle3_Release(IHTMLStyle3 *iface)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
return IHTMLStyle_Release(&This->IHTMLStyle_iface);
}
static HRESULT WINAPI HTMLStyle3_GetTypeInfoCount(IHTMLStyle3 *iface, UINT *pctinfo)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
return IDispatchEx_GetTypeInfoCount(&This->dispex.IDispatchEx_iface, pctinfo);
}
static HRESULT WINAPI HTMLStyle3_GetTypeInfo(IHTMLStyle3 *iface, UINT iTInfo,
LCID lcid, ITypeInfo **ppTInfo)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
return IDispatchEx_GetTypeInfo(&This->dispex.IDispatchEx_iface, iTInfo, lcid, ppTInfo);
}
static HRESULT WINAPI HTMLStyle3_GetIDsOfNames(IHTMLStyle3 *iface, REFIID riid,
LPOLESTR *rgszNames, UINT cNames,
LCID lcid, DISPID *rgDispId)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
return IDispatchEx_GetIDsOfNames(&This->dispex.IDispatchEx_iface, riid, rgszNames, cNames,
lcid, rgDispId);
}
static HRESULT WINAPI HTMLStyle3_Invoke(IHTMLStyle3 *iface, DISPID dispIdMember,
REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams,
VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
return IDispatchEx_Invoke(&This->dispex.IDispatchEx_iface, dispIdMember, riid, lcid,
wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr);
}
static HRESULT WINAPI HTMLStyle3_put_layoutFlow(IHTMLStyle3 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle3_get_layoutFlow(IHTMLStyle3 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static const WCHAR zoomW[] = {'z','o','o','m',0};
static HRESULT WINAPI HTMLStyle3_put_zoom(IHTMLStyle3 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
VARIANT *var;
HRESULT hres;
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
/* zoom property is IE CSS extension that is mostly used as a hack to workaround IE bugs.
* The value is set to 1 then. We can safely ignore setting zoom to 1. */
if(V_VT(&v) != VT_I4 || V_I4(&v) != 1)
WARN("stub for %s\n", debugstr_variant(&v));
hres = dispex_get_dprop_ref(&This->dispex, zoomW, TRUE, &var);
if(FAILED(hres))
return hres;
return VariantChangeType(var, &v, 0, VT_BSTR);
}
static HRESULT WINAPI HTMLStyle3_get_zoom(IHTMLStyle3 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
VARIANT *var;
HRESULT hres;
TRACE("(%p)->(%p)\n", This, p);
hres = dispex_get_dprop_ref(&This->dispex, zoomW, FALSE, &var);
if(hres == DISP_E_UNKNOWNNAME) {
V_VT(p) = VT_BSTR;
V_BSTR(p) = NULL;
return S_OK;
}
if(FAILED(hres))
return hres;
return VariantCopy(p, var);
}
static HRESULT WINAPI HTMLStyle3_put_wordWrap(IHTMLStyle3 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_WORD_WRAP, v);
}
static HRESULT WINAPI HTMLStyle3_get_wordWrap(IHTMLStyle3 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_WORD_WRAP, p);
}
static HRESULT WINAPI HTMLStyle3_put_textUnderlinePosition(IHTMLStyle3 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle3_get_textUnderlinePosition(IHTMLStyle3 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle3_put_scrollbarBaseColor(IHTMLStyle3 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle3_get_scrollbarBaseColor(IHTMLStyle3 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle3_put_scrollbarFaceColor(IHTMLStyle3 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle3_get_scrollbarFaceColor(IHTMLStyle3 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle3_put_scrollbar3dLightColor(IHTMLStyle3 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle3_get_scrollbar3dLightColor(IHTMLStyle3 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle3_put_scrollbarShadowColor(IHTMLStyle3 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle3_get_scrollbarShadowColor(IHTMLStyle3 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle3_put_scrollbarHighlightColor(IHTMLStyle3 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle3_get_scrollbarHighlightColor(IHTMLStyle3 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle3_put_scrollbarDarkShadowColor(IHTMLStyle3 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle3_get_scrollbarDarkShadowColor(IHTMLStyle3 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle3_put_scrollbarArrowColor(IHTMLStyle3 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle3_get_scrollbarArrowColor(IHTMLStyle3 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle3_put_scrollbarTrackColor(IHTMLStyle3 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle3_get_scrollbarTrackColor(IHTMLStyle3 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle3_put_writingMode(IHTMLStyle3 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle3_get_writingMode(IHTMLStyle3 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle3_put_textAlignLast(IHTMLStyle3 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle3_get_textAlignLast(IHTMLStyle3 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle3_put_textKashidaSpace(IHTMLStyle3 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle3_get_textKashidaSpace(IHTMLStyle3 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle3(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static const IHTMLStyle3Vtbl HTMLStyle3Vtbl = {
HTMLStyle3_QueryInterface,
HTMLStyle3_AddRef,
HTMLStyle3_Release,
HTMLStyle3_GetTypeInfoCount,
HTMLStyle3_GetTypeInfo,
HTMLStyle3_GetIDsOfNames,
HTMLStyle3_Invoke,
HTMLStyle3_put_layoutFlow,
HTMLStyle3_get_layoutFlow,
HTMLStyle3_put_zoom,
HTMLStyle3_get_zoom,
HTMLStyle3_put_wordWrap,
HTMLStyle3_get_wordWrap,
HTMLStyle3_put_textUnderlinePosition,
HTMLStyle3_get_textUnderlinePosition,
HTMLStyle3_put_scrollbarBaseColor,
HTMLStyle3_get_scrollbarBaseColor,
HTMLStyle3_put_scrollbarFaceColor,
HTMLStyle3_get_scrollbarFaceColor,
HTMLStyle3_put_scrollbar3dLightColor,
HTMLStyle3_get_scrollbar3dLightColor,
HTMLStyle3_put_scrollbarShadowColor,
HTMLStyle3_get_scrollbarShadowColor,
HTMLStyle3_put_scrollbarHighlightColor,
HTMLStyle3_get_scrollbarHighlightColor,
HTMLStyle3_put_scrollbarDarkShadowColor,
HTMLStyle3_get_scrollbarDarkShadowColor,
HTMLStyle3_put_scrollbarArrowColor,
HTMLStyle3_get_scrollbarArrowColor,
HTMLStyle3_put_scrollbarTrackColor,
HTMLStyle3_get_scrollbarTrackColor,
HTMLStyle3_put_writingMode,
HTMLStyle3_get_writingMode,
HTMLStyle3_put_textAlignLast,
HTMLStyle3_get_textAlignLast,
HTMLStyle3_put_textKashidaSpace,
HTMLStyle3_get_textKashidaSpace
};
/*
* IHTMLStyle4 Interface
*/
static inline HTMLStyle *impl_from_IHTMLStyle4(IHTMLStyle4 *iface)
{
return CONTAINING_RECORD(iface, HTMLStyle, IHTMLStyle4_iface);
}
static HRESULT WINAPI HTMLStyle4_QueryInterface(IHTMLStyle4 *iface, REFIID riid, void **ppv)
{
HTMLStyle *This = impl_from_IHTMLStyle4(iface);
return IHTMLStyle_QueryInterface(&This->IHTMLStyle_iface, riid, ppv);
}
static ULONG WINAPI HTMLStyle4_AddRef(IHTMLStyle4 *iface)
{
HTMLStyle *This = impl_from_IHTMLStyle4(iface);
return IHTMLStyle_AddRef(&This->IHTMLStyle_iface);
}
static ULONG WINAPI HTMLStyle4_Release(IHTMLStyle4 *iface)
{
HTMLStyle *This = impl_from_IHTMLStyle4(iface);
return IHTMLStyle_Release(&This->IHTMLStyle_iface);
}
static HRESULT WINAPI HTMLStyle4_GetTypeInfoCount(IHTMLStyle4 *iface, UINT *pctinfo)
{
HTMLStyle *This = impl_from_IHTMLStyle4(iface);
return IDispatchEx_GetTypeInfoCount(&This->dispex.IDispatchEx_iface, pctinfo);
}
static HRESULT WINAPI HTMLStyle4_GetTypeInfo(IHTMLStyle4 *iface, UINT iTInfo,
LCID lcid, ITypeInfo **ppTInfo)
{
HTMLStyle *This = impl_from_IHTMLStyle4(iface);
return IDispatchEx_GetTypeInfo(&This->dispex.IDispatchEx_iface, iTInfo, lcid, ppTInfo);
}
static HRESULT WINAPI HTMLStyle4_GetIDsOfNames(IHTMLStyle4 *iface, REFIID riid,
LPOLESTR *rgszNames, UINT cNames,
LCID lcid, DISPID *rgDispId)
{
HTMLStyle *This = impl_from_IHTMLStyle4(iface);
return IDispatchEx_GetIDsOfNames(&This->dispex.IDispatchEx_iface, riid, rgszNames, cNames,
lcid, rgDispId);
}
static HRESULT WINAPI HTMLStyle4_Invoke(IHTMLStyle4 *iface, DISPID dispIdMember,
REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams,
VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr)
{
HTMLStyle *This = impl_from_IHTMLStyle4(iface);
return IDispatchEx_Invoke(&This->dispex.IDispatchEx_iface, dispIdMember, riid, lcid,
wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr);
}
static HRESULT WINAPI HTMLStyle4_put_textOverflow(IHTMLStyle4 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle4(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle4_get_textOverflow(IHTMLStyle4 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle4(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle4_put_minHeight(IHTMLStyle4 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle4(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_MIN_HEIGHT, &v);
}
static HRESULT WINAPI HTMLStyle4_get_minHeight(IHTMLStyle4 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle4(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_MIN_HEIGHT, p);
}
static const IHTMLStyle4Vtbl HTMLStyle4Vtbl = {
HTMLStyle4_QueryInterface,
HTMLStyle4_AddRef,
HTMLStyle4_Release,
HTMLStyle4_GetTypeInfoCount,
HTMLStyle4_GetTypeInfo,
HTMLStyle4_GetIDsOfNames,
HTMLStyle4_Invoke,
HTMLStyle4_put_textOverflow,
HTMLStyle4_get_textOverflow,
HTMLStyle4_put_minHeight,
HTMLStyle4_get_minHeight
};
static inline HTMLStyle *impl_from_IHTMLStyle5(IHTMLStyle5 *iface)
{
return CONTAINING_RECORD(iface, HTMLStyle, IHTMLStyle5_iface);
}
static HRESULT WINAPI HTMLStyle5_QueryInterface(IHTMLStyle5 *iface, REFIID riid, void **ppv)
{
HTMLStyle *This = impl_from_IHTMLStyle5(iface);
return IHTMLStyle_QueryInterface(&This->IHTMLStyle_iface, riid, ppv);
}
static ULONG WINAPI HTMLStyle5_AddRef(IHTMLStyle5 *iface)
{
HTMLStyle *This = impl_from_IHTMLStyle5(iface);
return IHTMLStyle_AddRef(&This->IHTMLStyle_iface);
}
static ULONG WINAPI HTMLStyle5_Release(IHTMLStyle5 *iface)
{
HTMLStyle *This = impl_from_IHTMLStyle5(iface);
return IHTMLStyle_Release(&This->IHTMLStyle_iface);
}
static HRESULT WINAPI HTMLStyle5_GetTypeInfoCount(IHTMLStyle5 *iface, UINT *pctinfo)
{
HTMLStyle *This = impl_from_IHTMLStyle5(iface);
return IDispatchEx_GetTypeInfoCount(&This->dispex.IDispatchEx_iface, pctinfo);
}
static HRESULT WINAPI HTMLStyle5_GetTypeInfo(IHTMLStyle5 *iface, UINT iTInfo,
LCID lcid, ITypeInfo **ppTInfo)
{
HTMLStyle *This = impl_from_IHTMLStyle5(iface);
return IDispatchEx_GetTypeInfo(&This->dispex.IDispatchEx_iface, iTInfo, lcid, ppTInfo);
}
static HRESULT WINAPI HTMLStyle5_GetIDsOfNames(IHTMLStyle5 *iface, REFIID riid,
LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId)
{
HTMLStyle *This = impl_from_IHTMLStyle5(iface);
return IDispatchEx_GetIDsOfNames(&This->dispex.IDispatchEx_iface, riid, rgszNames, cNames,
lcid, rgDispId);
}
static HRESULT WINAPI HTMLStyle5_Invoke(IHTMLStyle5 *iface, DISPID dispIdMember,
REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams,
VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr)
{
HTMLStyle *This = impl_from_IHTMLStyle5(iface);
return IDispatchEx_Invoke(&This->dispex.IDispatchEx_iface, dispIdMember, riid, lcid,
wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr);
}
static HRESULT WINAPI HTMLStyle5_put_msInterpolationMode(IHTMLStyle5 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle5(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle5_get_msInterpolationMode(IHTMLStyle5 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle5(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle5_put_maxHeight(IHTMLStyle5 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle5(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_MAX_HEIGHT, &v);
}
static HRESULT WINAPI HTMLStyle5_get_maxHeight(IHTMLStyle5 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle5(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(p));
return get_style_property_var(This, STYLEID_MAX_HEIGHT, p);
}
static HRESULT WINAPI HTMLStyle5_put_minWidth(IHTMLStyle5 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle5(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_MIN_WIDTH, &v);
}
static HRESULT WINAPI HTMLStyle5_get_minWidth(IHTMLStyle5 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle5(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_MIN_WIDTH, p);
}
static HRESULT WINAPI HTMLStyle5_put_maxWidth(IHTMLStyle5 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle5(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_MAX_WIDTH, &v);
}
static HRESULT WINAPI HTMLStyle5_get_maxWidth(IHTMLStyle5 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle5(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_MAX_WIDTH, p);
}
static const IHTMLStyle5Vtbl HTMLStyle5Vtbl = {
HTMLStyle5_QueryInterface,
HTMLStyle5_AddRef,
HTMLStyle5_Release,
HTMLStyle5_GetTypeInfoCount,
HTMLStyle5_GetTypeInfo,
HTMLStyle5_GetIDsOfNames,
HTMLStyle5_Invoke,
HTMLStyle5_put_msInterpolationMode,
HTMLStyle5_get_msInterpolationMode,
HTMLStyle5_put_maxHeight,
HTMLStyle5_get_maxHeight,
HTMLStyle5_put_minWidth,
HTMLStyle5_get_minWidth,
HTMLStyle5_put_maxWidth,
HTMLStyle5_get_maxWidth
};
static inline HTMLStyle *impl_from_IHTMLStyle6(IHTMLStyle6 *iface)
{
return CONTAINING_RECORD(iface, HTMLStyle, IHTMLStyle6_iface);
}
static HRESULT WINAPI HTMLStyle6_QueryInterface(IHTMLStyle6 *iface, REFIID riid, void **ppv)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
return IHTMLStyle_QueryInterface(&This->IHTMLStyle_iface, riid, ppv);
}
static ULONG WINAPI HTMLStyle6_AddRef(IHTMLStyle6 *iface)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
return IHTMLStyle_AddRef(&This->IHTMLStyle_iface);
}
static ULONG WINAPI HTMLStyle6_Release(IHTMLStyle6 *iface)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
return IHTMLStyle_Release(&This->IHTMLStyle_iface);
}
static HRESULT WINAPI HTMLStyle6_GetTypeInfoCount(IHTMLStyle6 *iface, UINT *pctinfo)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
return IDispatchEx_GetTypeInfoCount(&This->dispex.IDispatchEx_iface, pctinfo);
}
static HRESULT WINAPI HTMLStyle6_GetTypeInfo(IHTMLStyle6 *iface, UINT iTInfo,
LCID lcid, ITypeInfo **ppTInfo)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
return IDispatchEx_GetTypeInfo(&This->dispex.IDispatchEx_iface, iTInfo, lcid, ppTInfo);
}
static HRESULT WINAPI HTMLStyle6_GetIDsOfNames(IHTMLStyle6 *iface, REFIID riid,
LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
return IDispatchEx_GetIDsOfNames(&This->dispex.IDispatchEx_iface, riid, rgszNames, cNames,
lcid, rgDispId);
}
static HRESULT WINAPI HTMLStyle6_Invoke(IHTMLStyle6 *iface, DISPID dispIdMember,
REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams,
VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
return IDispatchEx_Invoke(&This->dispex.IDispatchEx_iface, dispIdMember, riid, lcid,
wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr);
}
static HRESULT WINAPI HTMLStyle6_put_content(IHTMLStyle6 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle6_get_content(IHTMLStyle6 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle6_put_contentSide(IHTMLStyle6 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle6_get_contentSide(IHTMLStyle6 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle6_put_counterIncrement(IHTMLStyle6 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle6_get_counterIncrement(IHTMLStyle6 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle6_put_counterReset(IHTMLStyle6 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle6_get_counterReset(IHTMLStyle6 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle6_put_outline(IHTMLStyle6 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_OUTLINE, v);
}
static HRESULT WINAPI HTMLStyle6_get_outline(IHTMLStyle6 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_OUTLINE, p);
}
static HRESULT WINAPI HTMLStyle6_put_outlineWidth(IHTMLStyle6 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle6_get_outlineWidth(IHTMLStyle6 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle6_put_outlineStyle(IHTMLStyle6 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle6_get_outlineStyle(IHTMLStyle6 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle6_put_outlineColor(IHTMLStyle6 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle6_get_outlineColor(IHTMLStyle6 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle6_put_boxSizing(IHTMLStyle6 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BOX_SIZING, v);
}
static HRESULT WINAPI HTMLStyle6_get_boxSizing(IHTMLStyle6 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BOX_SIZING, p);
}
static HRESULT WINAPI HTMLStyle6_put_boxSpacing(IHTMLStyle6 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle6_get_boxSpacing(IHTMLStyle6 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle6_put_orphans(IHTMLStyle6 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle6_get_orphans(IHTMLStyle6 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle6_put_windows(IHTMLStyle6 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle6_get_windows(IHTMLStyle6 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle6_put_pageBreakInside(IHTMLStyle6 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle6_get_pageBreakInside(IHTMLStyle6 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle6_put_emptyCells(IHTMLStyle6 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle6_get_emptyCells(IHTMLStyle6 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle6_put_msBlockProgression(IHTMLStyle6 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle6_get_msBlockProgression(IHTMLStyle6 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle6_put_quotes(IHTMLStyle6 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLStyle6_get_quotes(IHTMLStyle6 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLStyle6(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static const IHTMLStyle6Vtbl HTMLStyle6Vtbl = {
HTMLStyle6_QueryInterface,
HTMLStyle6_AddRef,
HTMLStyle6_Release,
HTMLStyle6_GetTypeInfoCount,
HTMLStyle6_GetTypeInfo,
HTMLStyle6_GetIDsOfNames,
HTMLStyle6_Invoke,
HTMLStyle6_put_content,
HTMLStyle6_get_content,
HTMLStyle6_put_contentSide,
HTMLStyle6_get_contentSide,
HTMLStyle6_put_counterIncrement,
HTMLStyle6_get_counterIncrement,
HTMLStyle6_put_counterReset,
HTMLStyle6_get_counterReset,
HTMLStyle6_put_outline,
HTMLStyle6_get_outline,
HTMLStyle6_put_outlineWidth,
HTMLStyle6_get_outlineWidth,
HTMLStyle6_put_outlineStyle,
HTMLStyle6_get_outlineStyle,
HTMLStyle6_put_outlineColor,
HTMLStyle6_get_outlineColor,
HTMLStyle6_put_boxSizing,
HTMLStyle6_get_boxSizing,
HTMLStyle6_put_boxSpacing,
HTMLStyle6_get_boxSpacing,
HTMLStyle6_put_orphans,
HTMLStyle6_get_orphans,
HTMLStyle6_put_windows,
HTMLStyle6_get_windows,
HTMLStyle6_put_pageBreakInside,
HTMLStyle6_get_pageBreakInside,
HTMLStyle6_put_emptyCells,
HTMLStyle6_get_emptyCells,
HTMLStyle6_put_msBlockProgression,
HTMLStyle6_get_msBlockProgression,
HTMLStyle6_put_quotes,
HTMLStyle6_get_quotes
};
static inline HTMLStyle *impl_from_IHTMLCSSStyleDeclaration(IHTMLCSSStyleDeclaration *iface)
{
return CONTAINING_RECORD(iface, HTMLStyle, IHTMLCSSStyleDeclaration_iface);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_QueryInterface(IHTMLCSSStyleDeclaration *iface,
REFIID riid, void **ppv)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
return IHTMLStyle_QueryInterface(&This->IHTMLStyle_iface, riid, ppv);
}
static ULONG WINAPI HTMLCSSStyleDeclaration_AddRef(IHTMLCSSStyleDeclaration *iface)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
return IHTMLStyle_AddRef(&This->IHTMLStyle_iface);
}
static ULONG WINAPI HTMLCSSStyleDeclaration_Release(IHTMLCSSStyleDeclaration *iface)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
return IHTMLStyle_Release(&This->IHTMLStyle_iface);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_GetTypeInfoCount(IHTMLCSSStyleDeclaration *iface,
UINT *pctinfo)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, pctinfo);
return IDispatchEx_GetTypeInfoCount(&This->dispex.IDispatchEx_iface, pctinfo);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_GetTypeInfo(IHTMLCSSStyleDeclaration *iface,
UINT iTInfo, LCID lcid, ITypeInfo **ppTInfo)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%u %u %p)\n", This, iTInfo, lcid, ppTInfo);
return IDispatchEx_GetTypeInfo(&This->dispex.IDispatchEx_iface, iTInfo, lcid, ppTInfo);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_GetIDsOfNames(IHTMLCSSStyleDeclaration *iface,
REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p %p %u %u %p)\n", This, riid, rgszNames, cNames, lcid, rgDispId);
return IDispatchEx_GetIDsOfNames(&This->dispex.IDispatchEx_iface, riid, rgszNames,
cNames, lcid, rgDispId);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_Invoke(IHTMLCSSStyleDeclaration *iface,
DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams,
VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%d %p %u %u %p %p %p %p)\n", This, dispIdMember, riid, lcid, wFlags,
pDispParams, pVarResult, pExcepInfo, puArgErr);
return IDispatchEx_Invoke(&This->dispex.IDispatchEx_iface, dispIdMember, riid, lcid,
wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_length(IHTMLCSSStyleDeclaration *iface, LONG *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_parentRule(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_getPropertyValue(IHTMLCSSStyleDeclaration *iface, BSTR bstrPropertyName, BSTR *pbstrPropertyValue)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s %p)\n", This, debugstr_w(bstrPropertyName), pbstrPropertyValue);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_getPropertyPriority(IHTMLCSSStyleDeclaration *iface, BSTR bstrPropertyName, BSTR *pbstrPropertyPriority)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s %p)\n", This, debugstr_w(bstrPropertyName), pbstrPropertyPriority);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_removeProperty(IHTMLCSSStyleDeclaration *iface, BSTR bstrPropertyName, BSTR *pbstrPropertyValue)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
const style_tbl_entry_t *style_entry;
nsAString name_str, ret_str;
nsresult nsres;
TRACE("(%p)->(%s %p)\n", This, debugstr_w(bstrPropertyName), pbstrPropertyValue);
style_entry = lookup_style_tbl(bstrPropertyName);
nsAString_InitDepend(&name_str, style_entry ? style_entry->name : bstrPropertyName);
nsAString_Init(&ret_str, NULL);
nsres = nsIDOMCSSStyleDeclaration_RemoveProperty(This->nsstyle, &name_str, &ret_str);
nsAString_Finish(&name_str);
return return_nsstr(nsres, &ret_str, pbstrPropertyValue);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_setProperty(IHTMLCSSStyleDeclaration *iface, BSTR bstrPropertyName, VARIANT *pvarPropertyValue, VARIANT *pvarPropertyPriority)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s %p %p)\n", This, debugstr_w(bstrPropertyName), pvarPropertyValue, pvarPropertyPriority);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_item(IHTMLCSSStyleDeclaration *iface, LONG index, BSTR *pbstrPropertyName)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%d %p)\n", This, index, pbstrPropertyName);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_fontFamily(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_FONT_FAMILY, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_fontFamily(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_FONT_FAMILY, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_fontStyle(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_FONT_STYLE, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_fontStyle(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_FONT_STYLE, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_fontVariant(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_FONT_VARIANT, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_fontVariant(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_FONT_VARIANT, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_fontWeight(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_FONT_WEIGHT, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_fontWeight(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_FONT_WEIGHT, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_fontSize(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_FONT_SIZE, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_fontSize(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_FONT_SIZE, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_font(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_font(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_color(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_COLOR, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_color(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_COLOR, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_background(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BACKGROUND, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_background(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BACKGROUND, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_backgroundColor(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_BACKGROUND_COLOR, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_backgroundColor(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_BACKGROUND_COLOR, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_backgroundImage(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BACKGROUND_IMAGE, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_backgroundImage(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BACKGROUND_IMAGE, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_backgroundRepeat(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BACKGROUND_REPEAT, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_backgroundRepeat(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BACKGROUND_REPEAT, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_backgroundAttachment(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BACKGROUND_ATTACHMENT, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_backgroundAttachment(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BACKGROUND_ATTACHMENT, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_backgroundPosition(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BACKGROUND_POSITION, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_backgroundPosition(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BACKGROUND_POSITION, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_backgroundPositionX(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return IHTMLStyle_put_backgroundPositionX(&This->IHTMLStyle_iface, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_backgroundPositionX(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return IHTMLStyle_get_backgroundPositionX(&This->IHTMLStyle_iface, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_backgroundPositionY(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return IHTMLStyle_put_backgroundPositionY(&This->IHTMLStyle_iface, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_backgroundPositionY(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return IHTMLStyle_get_backgroundPositionY(&This->IHTMLStyle_iface, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_wordSpacing(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_WORD_SPACING, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_wordSpacing(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_WORD_SPACING, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_letterSpacing(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_LETTER_SPACING, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_letterSpacing(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_LETTER_SPACING, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_textDecoration(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_TEXT_DECORATION, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_textDecoration(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_TEXT_DECORATION, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_verticalAlign(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_VERTICAL_ALIGN, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_verticalAlign(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_VERTICAL_ALIGN, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_textTransform(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_TEXT_TRANSFORM, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_textTransform(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_TEXT_TRANSFORM, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_textAlign(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_TEXT_ALIGN, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_textAlign(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_TEXT_ALIGN, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_textIndent(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_TEXT_INDENT, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_textIndent(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_TEXT_INDENT, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_lineHeight(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_LINE_HEIGHT, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_lineHeight(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_LINE_HEIGHT, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_marginTop(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_MARGIN_TOP, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_marginTop(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_MARGIN_TOP, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_marginRight(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_MARGIN_RIGHT, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_marginRight(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_MARGIN_RIGHT, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_marginBottom(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_MARGIN_BOTTOM, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_marginBottom(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_MARGIN_BOTTOM, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_marginLeft(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_MARGIN_LEFT, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_marginLeft(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_MARGIN_LEFT, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_margin(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_MARGIN, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_margin(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_MARGIN, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_paddingTop(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_PADDING_TOP, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_paddingTop(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_PADDING_TOP, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_paddingRight(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_PADDING_RIGHT, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_paddingRight(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_PADDING_RIGHT, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_paddingBottom(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_PADDING_BOTTOM, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_paddingBottom(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_PADDING_BOTTOM, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_paddingLeft(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_PADDING_LEFT, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_paddingLeft(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_PADDING_LEFT, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_padding(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_PADDING, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_padding(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_PADDING, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_border(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BORDER, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_border(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BORDER, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_borderTop(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BORDER_TOP, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_borderTop(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BORDER_TOP, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_borderRight(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BORDER_RIGHT, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_borderRight(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BORDER_RIGHT, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_borderBottom(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BORDER_BOTTOM, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_borderBottom(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BORDER_BOTTOM, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_borderLeft(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BORDER_LEFT, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_borderLeft(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BORDER_LEFT, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_borderColor(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BORDER_COLOR, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_borderColor(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BORDER_COLOR, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_borderTopColor(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_BORDER_TOP_COLOR, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_borderTopColor(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_BORDER_TOP_COLOR, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_borderRightColor(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_BORDER_RIGHT_COLOR, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_borderRightColor(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_BORDER_RIGHT_COLOR, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_borderBottomColor(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_BORDER_BOTTOM_COLOR, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_borderBottomColor(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_BORDER_BOTTOM_COLOR, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_borderLeftColor(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_BORDER_LEFT_COLOR, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_borderLeftColor(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_BORDER_LEFT_COLOR, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_borderWidth(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BORDER_WIDTH, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_borderWidth(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BORDER_WIDTH, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_borderTopWidth(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_BORDER_TOP_WIDTH, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_borderTopWidth(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_BORDER_TOP_WIDTH, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_borderRightWidth(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_BORDER_RIGHT_WIDTH, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_borderRightWidth(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_BORDER_RIGHT_WIDTH, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_borderBottomWidth(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_BORDER_BOTTOM_WIDTH, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_borderBottomWidth(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_BORDER_BOTTOM_WIDTH, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_borderLeftWidth(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_BORDER_LEFT_WIDTH, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_borderLeftWidth(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_BORDER_LEFT_WIDTH, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_borderStyle(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BORDER_STYLE, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_borderStyle(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BORDER_STYLE, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_borderTopStyle(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BORDER_TOP_STYLE, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_borderTopStyle(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BORDER_TOP_STYLE, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_borderRightStyle(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BORDER_RIGHT_STYLE, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_borderRightStyle(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BORDER_RIGHT_STYLE, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_borderBottomStyle(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BORDER_BOTTOM_STYLE, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_borderBottomStyle(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BORDER_BOTTOM_STYLE, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_borderLeftStyle(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BORDER_LEFT_STYLE, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_borderLeftStyle(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BORDER_LEFT_STYLE, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_width(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_WIDTH, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_width(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_WIDTH, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_height(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_HEIGHT, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_height(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_HEIGHT, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_styleFloat(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_FLOAT, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_styleFloat(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_FLOAT, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_clear(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_CLEAR, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_clear(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_CLEAR, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_display(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_DISPLAY, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_display(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_DISPLAY, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_visibility(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_VISIBILITY, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_visibility(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_VISIBILITY, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_listStyleType(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_listStyleType(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_listStylePosition(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_listStylePosition(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_listStyleImage(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_listStyleImage(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_listStyle(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_LIST_STYLE, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_listStyle(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_LIST_STYLE, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_whiteSpace(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_WHITE_SPACE, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_whiteSpace(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_WHITE_SPACE, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_top(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_TOP, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_top(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_TOP, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_left(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_LEFT, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_left(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_LEFT, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_zIndex(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_Z_INDEX, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_zIndex(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_Z_INDEX, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_overflow(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_OVERFLOW, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_overflow(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_OVERFLOW, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_pageBreakBefore(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_PAGE_BREAK_BEFORE, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_pageBreakBefore(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_PAGE_BREAK_BEFORE, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_pageBreakAfter(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_PAGE_BREAK_AFTER, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_pageBreakAfter(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_PAGE_BREAK_AFTER, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_cssText(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
nsAString text_str;
nsresult nsres;
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
nsAString_InitDepend(&text_str, v);
nsres = nsIDOMCSSStyleDeclaration_SetCssText(This->nsstyle, &text_str);
nsAString_Finish(&text_str);
if(NS_FAILED(nsres)) {
FIXME("SetCssStyle failed: %08x\n", nsres);
return E_FAIL;
}
return S_OK;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_cssText(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
nsAString text_str;
nsresult nsres;
TRACE("(%p)->(%p)\n", This, p);
/* NOTE: Quicks mode should use different formatting (uppercase, no ';' at the end of rule). */
nsAString_Init(&text_str, NULL);
nsres = nsIDOMCSSStyleDeclaration_GetCssText(This->nsstyle, &text_str);
return return_nsstr(nsres, &text_str, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_cursor(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_CURSOR, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_cursor(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_CURSOR, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_clip(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_CLIP, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_clip(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_CLIP, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_filter(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_FILTER, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_filter(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_FILTER, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_tableLayout(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_TABLE_LAYOUT, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_tableLayout(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_TABLE_LAYOUT, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_borderCollapse(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_borderCollapse(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_direction(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_DIRECTION, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_direction(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_DIRECTION, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_behavior(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_behavior(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_position(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_POSITION, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_position(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_POSITION, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_unicodeBidi(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_unicodeBidi(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_bottom(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_BOTTOM, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_bottom(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_BOTTOM, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_right(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_RIGHT, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_right(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_RIGHT, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_imeMode(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_imeMode(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_rubyAlign(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_rubyAlign(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_rubyPosition(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_rubyPosition(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_rubyOverhang(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_rubyOverhang(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_layoutGridChar(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_layoutGridChar(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_layoutGridLine(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_layoutGridLine(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_layoutGridMode(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_layoutGridMode(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_layoutGridType(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_layoutGridType(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_layoutGrid(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_layoutGrid(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_textAutospace(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_textAutospace(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_wordBreak(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_wordBreak(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_lineBreak(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_lineBreak(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_textJustify(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_textJustify(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_textJustifyTrim(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_textJustifyTrim(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_textKashida(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_textKashida(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_overflowX(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_OVERFLOW_X, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_overflowX(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_OVERFLOW_X, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_overflowY(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_OVERFLOW_Y, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_overflowY(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_OVERFLOW_Y, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_accelerator(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_accelerator(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_layoutFlow(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_layoutFlow(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_zoom(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return IHTMLStyle3_put_zoom(&This->IHTMLStyle3_iface, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_zoom(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return IHTMLStyle3_get_zoom(&This->IHTMLStyle3_iface, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_wordWrap(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_WORD_WRAP, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_wordWrap(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_WORD_WRAP, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_textUnderlinePosition(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_textUnderlinePosition(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_scrollbarBaseColor(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_scrollbarBaseColor(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_scrollbarFaceColor(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_scrollbarFaceColor(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_scrollbar3dLightColor(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_scrollbar3dLightColor(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_scrollbarShadowColor(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_scrollbarShadowColor(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_scrollbarHighlightColor(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_scrollbarHighlightColor(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_scrollbarDarkShadowColor(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_scrollbarDarkShadowColor(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_scrollbarArrowColor(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_scrollbarArrowColor(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_scrollbarTrackColor(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_scrollbarTrackColor(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_writingMode(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_writingMode(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_textAlignLast(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_textAlignLast(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_textKashidaSpace(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_textKashidaSpace(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_textOverflow(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_textOverflow(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_minHeight(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_MIN_HEIGHT, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_minHeight(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_MIN_HEIGHT, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_msInterpolationMode(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_msInterpolationMode(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_maxHeight(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_MAX_HEIGHT, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_maxHeight(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_MAX_HEIGHT, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_minWidth(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_MIN_WIDTH, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_minWidth(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_MIN_WIDTH, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_maxWidth(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_MAX_WIDTH, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_maxWidth(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_MAX_WIDTH, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_content(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_content(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_captionSide(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_captionSide(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_counterIncrement(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_counterIncrement(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_counterReset(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_counterReset(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_outline(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_OUTLINE, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_outline(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_OUTLINE, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_outlineWidth(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_outlineWidth(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_outlineStyle(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_outlineStyle(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_outlineColor(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_outlineColor(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_boxSizing(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BOX_SIZING, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_boxSizing(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BOX_SIZING, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_borderSpacing(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_borderSpacing(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_orphans(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_orphans(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_widows(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_widows(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_pageBreakInside(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_pageBreakInside(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_emptyCells(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_emptyCells(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_msBlockProgression(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_msBlockProgression(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_quotes(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_quotes(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_alignmentBaseline(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_alignmentBaseline(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_baselineShift(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_baselineShift(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_dominantBaseline(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_dominantBaseline(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_fontSizeAdjust(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_fontSizeAdjust(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_fontStretch(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_fontStretch(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_opacity(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_variant(&v));
return set_style_property_var(This, STYLEID_OPACITY, &v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_opacity(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property_var(This, STYLEID_OPACITY, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_clipPath(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_clipPath(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_clipRule(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_clipRule(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_fill(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_fill(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_fillOpacity(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_fillOpacity(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_fillRule(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_fillRule(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_kerning(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_kerning(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_marker(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_marker(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_markerEnd(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_markerEnd(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_markerMid(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_markerMid(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_markerStart(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_markerStart(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_mask(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_mask(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_pointerEvents(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_pointerEvents(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_stopColor(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_stopColor(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_stopOpacity(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_stopOpacity(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_stroke(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_stroke(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_strokeDasharray(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_strokeDasharray(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_strokeDashoffset(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_strokeDashoffset(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_strokeLinecap(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_strokeLinecap(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_strokeLinejoin(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_strokeLinejoin(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_strokeMiterlimit(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_strokeMiterlimit(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_strokeOpacity(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_strokeOpacity(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_strokeWidth(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_strokeWidth(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_textAnchor(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_textAnchor(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_glyphOrientationHorizontal(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_glyphOrientationHorizontal(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_glyphOrientationVertical(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_glyphOrientationVertical(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_borderRadius(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_borderRadius(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_borderTopLeftRadius(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_borderTopLeftRadius(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_borderTopRightRadius(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_borderTopRightRadius(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_borderBottomRightRadius(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_borderBottomRightRadius(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_borderBottomLeftRadius(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_borderBottomLeftRadius(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_clipTop(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_clipTop(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_clipRight(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_clipRight(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_clipBottom(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_clipLeft(IHTMLCSSStyleDeclaration *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_clipLeft(IHTMLCSSStyleDeclaration *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_cssFloat(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_FLOAT, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_cssFloat(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_FLOAT, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_backgroundClip(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%s)\n", This, debugstr_w(v));
return set_style_property(This, STYLEID_BACKGROUND_CLIP, v);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_backgroundClip(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
TRACE("(%p)->(%p)\n", This, p);
return get_style_property(This, STYLEID_BACKGROUND_CLIP, p);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_backgroundOrigin(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_backgroundOrigin(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_backgroundSize(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_backgroundSize(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_boxShadow(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_boxShadow(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_msTransform(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_msTransform(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_put_msTransformOrigin(IHTMLCSSStyleDeclaration *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration_get_msTransformOrigin(IHTMLCSSStyleDeclaration *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static const IHTMLCSSStyleDeclarationVtbl HTMLCSSStyleDeclarationVtbl = {
HTMLCSSStyleDeclaration_QueryInterface,
HTMLCSSStyleDeclaration_AddRef,
HTMLCSSStyleDeclaration_Release,
HTMLCSSStyleDeclaration_GetTypeInfoCount,
HTMLCSSStyleDeclaration_GetTypeInfo,
HTMLCSSStyleDeclaration_GetIDsOfNames,
HTMLCSSStyleDeclaration_Invoke,
HTMLCSSStyleDeclaration_get_length,
HTMLCSSStyleDeclaration_get_parentRule,
HTMLCSSStyleDeclaration_getPropertyValue,
HTMLCSSStyleDeclaration_getPropertyPriority,
HTMLCSSStyleDeclaration_removeProperty,
HTMLCSSStyleDeclaration_setProperty,
HTMLCSSStyleDeclaration_item,
HTMLCSSStyleDeclaration_put_fontFamily,
HTMLCSSStyleDeclaration_get_fontFamily,
HTMLCSSStyleDeclaration_put_fontStyle,
HTMLCSSStyleDeclaration_get_fontStyle,
HTMLCSSStyleDeclaration_put_fontVariant,
HTMLCSSStyleDeclaration_get_fontVariant,
HTMLCSSStyleDeclaration_put_fontWeight,
HTMLCSSStyleDeclaration_get_fontWeight,
HTMLCSSStyleDeclaration_put_fontSize,
HTMLCSSStyleDeclaration_get_fontSize,
HTMLCSSStyleDeclaration_put_font,
HTMLCSSStyleDeclaration_get_font,
HTMLCSSStyleDeclaration_put_color,
HTMLCSSStyleDeclaration_get_color,
HTMLCSSStyleDeclaration_put_background,
HTMLCSSStyleDeclaration_get_background,
HTMLCSSStyleDeclaration_put_backgroundColor,
HTMLCSSStyleDeclaration_get_backgroundColor,
HTMLCSSStyleDeclaration_put_backgroundImage,
HTMLCSSStyleDeclaration_get_backgroundImage,
HTMLCSSStyleDeclaration_put_backgroundRepeat,
HTMLCSSStyleDeclaration_get_backgroundRepeat,
HTMLCSSStyleDeclaration_put_backgroundAttachment,
HTMLCSSStyleDeclaration_get_backgroundAttachment,
HTMLCSSStyleDeclaration_put_backgroundPosition,
HTMLCSSStyleDeclaration_get_backgroundPosition,
HTMLCSSStyleDeclaration_put_backgroundPositionX,
HTMLCSSStyleDeclaration_get_backgroundPositionX,
HTMLCSSStyleDeclaration_put_backgroundPositionY,
HTMLCSSStyleDeclaration_get_backgroundPositionY,
HTMLCSSStyleDeclaration_put_wordSpacing,
HTMLCSSStyleDeclaration_get_wordSpacing,
HTMLCSSStyleDeclaration_put_letterSpacing,
HTMLCSSStyleDeclaration_get_letterSpacing,
HTMLCSSStyleDeclaration_put_textDecoration,
HTMLCSSStyleDeclaration_get_textDecoration,
HTMLCSSStyleDeclaration_put_verticalAlign,
HTMLCSSStyleDeclaration_get_verticalAlign,
HTMLCSSStyleDeclaration_put_textTransform,
HTMLCSSStyleDeclaration_get_textTransform,
HTMLCSSStyleDeclaration_put_textAlign,
HTMLCSSStyleDeclaration_get_textAlign,
HTMLCSSStyleDeclaration_put_textIndent,
HTMLCSSStyleDeclaration_get_textIndent,
HTMLCSSStyleDeclaration_put_lineHeight,
HTMLCSSStyleDeclaration_get_lineHeight,
HTMLCSSStyleDeclaration_put_marginTop,
HTMLCSSStyleDeclaration_get_marginTop,
HTMLCSSStyleDeclaration_put_marginRight,
HTMLCSSStyleDeclaration_get_marginRight,
HTMLCSSStyleDeclaration_put_marginBottom,
HTMLCSSStyleDeclaration_get_marginBottom,
HTMLCSSStyleDeclaration_put_marginLeft,
HTMLCSSStyleDeclaration_get_marginLeft,
HTMLCSSStyleDeclaration_put_margin,
HTMLCSSStyleDeclaration_get_margin,
HTMLCSSStyleDeclaration_put_paddingTop,
HTMLCSSStyleDeclaration_get_paddingTop,
HTMLCSSStyleDeclaration_put_paddingRight,
HTMLCSSStyleDeclaration_get_paddingRight,
HTMLCSSStyleDeclaration_put_paddingBottom,
HTMLCSSStyleDeclaration_get_paddingBottom,
HTMLCSSStyleDeclaration_put_paddingLeft,
HTMLCSSStyleDeclaration_get_paddingLeft,
HTMLCSSStyleDeclaration_put_padding,
HTMLCSSStyleDeclaration_get_padding,
HTMLCSSStyleDeclaration_put_border,
HTMLCSSStyleDeclaration_get_border,
HTMLCSSStyleDeclaration_put_borderTop,
HTMLCSSStyleDeclaration_get_borderTop,
HTMLCSSStyleDeclaration_put_borderRight,
HTMLCSSStyleDeclaration_get_borderRight,
HTMLCSSStyleDeclaration_put_borderBottom,
HTMLCSSStyleDeclaration_get_borderBottom,
HTMLCSSStyleDeclaration_put_borderLeft,
HTMLCSSStyleDeclaration_get_borderLeft,
HTMLCSSStyleDeclaration_put_borderColor,
HTMLCSSStyleDeclaration_get_borderColor,
HTMLCSSStyleDeclaration_put_borderTopColor,
HTMLCSSStyleDeclaration_get_borderTopColor,
HTMLCSSStyleDeclaration_put_borderRightColor,
HTMLCSSStyleDeclaration_get_borderRightColor,
HTMLCSSStyleDeclaration_put_borderBottomColor,
HTMLCSSStyleDeclaration_get_borderBottomColor,
HTMLCSSStyleDeclaration_put_borderLeftColor,
HTMLCSSStyleDeclaration_get_borderLeftColor,
HTMLCSSStyleDeclaration_put_borderWidth,
HTMLCSSStyleDeclaration_get_borderWidth,
HTMLCSSStyleDeclaration_put_borderTopWidth,
HTMLCSSStyleDeclaration_get_borderTopWidth,
HTMLCSSStyleDeclaration_put_borderRightWidth,
HTMLCSSStyleDeclaration_get_borderRightWidth,
HTMLCSSStyleDeclaration_put_borderBottomWidth,
HTMLCSSStyleDeclaration_get_borderBottomWidth,
HTMLCSSStyleDeclaration_put_borderLeftWidth,
HTMLCSSStyleDeclaration_get_borderLeftWidth,
HTMLCSSStyleDeclaration_put_borderStyle,
HTMLCSSStyleDeclaration_get_borderStyle,
HTMLCSSStyleDeclaration_put_borderTopStyle,
HTMLCSSStyleDeclaration_get_borderTopStyle,
HTMLCSSStyleDeclaration_put_borderRightStyle,
HTMLCSSStyleDeclaration_get_borderRightStyle,
HTMLCSSStyleDeclaration_put_borderBottomStyle,
HTMLCSSStyleDeclaration_get_borderBottomStyle,
HTMLCSSStyleDeclaration_put_borderLeftStyle,
HTMLCSSStyleDeclaration_get_borderLeftStyle,
HTMLCSSStyleDeclaration_put_width,
HTMLCSSStyleDeclaration_get_width,
HTMLCSSStyleDeclaration_put_height,
HTMLCSSStyleDeclaration_get_height,
HTMLCSSStyleDeclaration_put_styleFloat,
HTMLCSSStyleDeclaration_get_styleFloat,
HTMLCSSStyleDeclaration_put_clear,
HTMLCSSStyleDeclaration_get_clear,
HTMLCSSStyleDeclaration_put_display,
HTMLCSSStyleDeclaration_get_display,
HTMLCSSStyleDeclaration_put_visibility,
HTMLCSSStyleDeclaration_get_visibility,
HTMLCSSStyleDeclaration_put_listStyleType,
HTMLCSSStyleDeclaration_get_listStyleType,
HTMLCSSStyleDeclaration_put_listStylePosition,
HTMLCSSStyleDeclaration_get_listStylePosition,
HTMLCSSStyleDeclaration_put_listStyleImage,
HTMLCSSStyleDeclaration_get_listStyleImage,
HTMLCSSStyleDeclaration_put_listStyle,
HTMLCSSStyleDeclaration_get_listStyle,
HTMLCSSStyleDeclaration_put_whiteSpace,
HTMLCSSStyleDeclaration_get_whiteSpace,
HTMLCSSStyleDeclaration_put_top,
HTMLCSSStyleDeclaration_get_top,
HTMLCSSStyleDeclaration_put_left,
HTMLCSSStyleDeclaration_get_left,
HTMLCSSStyleDeclaration_put_zIndex,
HTMLCSSStyleDeclaration_get_zIndex,
HTMLCSSStyleDeclaration_put_overflow,
HTMLCSSStyleDeclaration_get_overflow,
HTMLCSSStyleDeclaration_put_pageBreakBefore,
HTMLCSSStyleDeclaration_get_pageBreakBefore,
HTMLCSSStyleDeclaration_put_pageBreakAfter,
HTMLCSSStyleDeclaration_get_pageBreakAfter,
HTMLCSSStyleDeclaration_put_cssText,
HTMLCSSStyleDeclaration_get_cssText,
HTMLCSSStyleDeclaration_put_cursor,
HTMLCSSStyleDeclaration_get_cursor,
HTMLCSSStyleDeclaration_put_clip,
HTMLCSSStyleDeclaration_get_clip,
HTMLCSSStyleDeclaration_put_filter,
HTMLCSSStyleDeclaration_get_filter,
HTMLCSSStyleDeclaration_put_tableLayout,
HTMLCSSStyleDeclaration_get_tableLayout,
HTMLCSSStyleDeclaration_put_borderCollapse,
HTMLCSSStyleDeclaration_get_borderCollapse,
HTMLCSSStyleDeclaration_put_direction,
HTMLCSSStyleDeclaration_get_direction,
HTMLCSSStyleDeclaration_put_behavior,
HTMLCSSStyleDeclaration_get_behavior,
HTMLCSSStyleDeclaration_put_position,
HTMLCSSStyleDeclaration_get_position,
HTMLCSSStyleDeclaration_put_unicodeBidi,
HTMLCSSStyleDeclaration_get_unicodeBidi,
HTMLCSSStyleDeclaration_put_bottom,
HTMLCSSStyleDeclaration_get_bottom,
HTMLCSSStyleDeclaration_put_right,
HTMLCSSStyleDeclaration_get_right,
HTMLCSSStyleDeclaration_put_imeMode,
HTMLCSSStyleDeclaration_get_imeMode,
HTMLCSSStyleDeclaration_put_rubyAlign,
HTMLCSSStyleDeclaration_get_rubyAlign,
HTMLCSSStyleDeclaration_put_rubyPosition,
HTMLCSSStyleDeclaration_get_rubyPosition,
HTMLCSSStyleDeclaration_put_rubyOverhang,
HTMLCSSStyleDeclaration_get_rubyOverhang,
HTMLCSSStyleDeclaration_put_layoutGridChar,
HTMLCSSStyleDeclaration_get_layoutGridChar,
HTMLCSSStyleDeclaration_put_layoutGridLine,
HTMLCSSStyleDeclaration_get_layoutGridLine,
HTMLCSSStyleDeclaration_put_layoutGridMode,
HTMLCSSStyleDeclaration_get_layoutGridMode,
HTMLCSSStyleDeclaration_put_layoutGridType,
HTMLCSSStyleDeclaration_get_layoutGridType,
HTMLCSSStyleDeclaration_put_layoutGrid,
HTMLCSSStyleDeclaration_get_layoutGrid,
HTMLCSSStyleDeclaration_put_textAutospace,
HTMLCSSStyleDeclaration_get_textAutospace,
HTMLCSSStyleDeclaration_put_wordBreak,
HTMLCSSStyleDeclaration_get_wordBreak,
HTMLCSSStyleDeclaration_put_lineBreak,
HTMLCSSStyleDeclaration_get_lineBreak,
HTMLCSSStyleDeclaration_put_textJustify,
HTMLCSSStyleDeclaration_get_textJustify,
HTMLCSSStyleDeclaration_put_textJustifyTrim,
HTMLCSSStyleDeclaration_get_textJustifyTrim,
HTMLCSSStyleDeclaration_put_textKashida,
HTMLCSSStyleDeclaration_get_textKashida,
HTMLCSSStyleDeclaration_put_overflowX,
HTMLCSSStyleDeclaration_get_overflowX,
HTMLCSSStyleDeclaration_put_overflowY,
HTMLCSSStyleDeclaration_get_overflowY,
HTMLCSSStyleDeclaration_put_accelerator,
HTMLCSSStyleDeclaration_get_accelerator,
HTMLCSSStyleDeclaration_put_layoutFlow,
HTMLCSSStyleDeclaration_get_layoutFlow,
HTMLCSSStyleDeclaration_put_zoom,
HTMLCSSStyleDeclaration_get_zoom,
HTMLCSSStyleDeclaration_put_wordWrap,
HTMLCSSStyleDeclaration_get_wordWrap,
HTMLCSSStyleDeclaration_put_textUnderlinePosition,
HTMLCSSStyleDeclaration_get_textUnderlinePosition,
HTMLCSSStyleDeclaration_put_scrollbarBaseColor,
HTMLCSSStyleDeclaration_get_scrollbarBaseColor,
HTMLCSSStyleDeclaration_put_scrollbarFaceColor,
HTMLCSSStyleDeclaration_get_scrollbarFaceColor,
HTMLCSSStyleDeclaration_put_scrollbar3dLightColor,
HTMLCSSStyleDeclaration_get_scrollbar3dLightColor,
HTMLCSSStyleDeclaration_put_scrollbarShadowColor,
HTMLCSSStyleDeclaration_get_scrollbarShadowColor,
HTMLCSSStyleDeclaration_put_scrollbarHighlightColor,
HTMLCSSStyleDeclaration_get_scrollbarHighlightColor,
HTMLCSSStyleDeclaration_put_scrollbarDarkShadowColor,
HTMLCSSStyleDeclaration_get_scrollbarDarkShadowColor,
HTMLCSSStyleDeclaration_put_scrollbarArrowColor,
HTMLCSSStyleDeclaration_get_scrollbarArrowColor,
HTMLCSSStyleDeclaration_put_scrollbarTrackColor,
HTMLCSSStyleDeclaration_get_scrollbarTrackColor,
HTMLCSSStyleDeclaration_put_writingMode,
HTMLCSSStyleDeclaration_get_writingMode,
HTMLCSSStyleDeclaration_put_textAlignLast,
HTMLCSSStyleDeclaration_get_textAlignLast,
HTMLCSSStyleDeclaration_put_textKashidaSpace,
HTMLCSSStyleDeclaration_get_textKashidaSpace,
HTMLCSSStyleDeclaration_put_textOverflow,
HTMLCSSStyleDeclaration_get_textOverflow,
HTMLCSSStyleDeclaration_put_minHeight,
HTMLCSSStyleDeclaration_get_minHeight,
HTMLCSSStyleDeclaration_put_msInterpolationMode,
HTMLCSSStyleDeclaration_get_msInterpolationMode,
HTMLCSSStyleDeclaration_put_maxHeight,
HTMLCSSStyleDeclaration_get_maxHeight,
HTMLCSSStyleDeclaration_put_minWidth,
HTMLCSSStyleDeclaration_get_minWidth,
HTMLCSSStyleDeclaration_put_maxWidth,
HTMLCSSStyleDeclaration_get_maxWidth,
HTMLCSSStyleDeclaration_put_content,
HTMLCSSStyleDeclaration_get_content,
HTMLCSSStyleDeclaration_put_captionSide,
HTMLCSSStyleDeclaration_get_captionSide,
HTMLCSSStyleDeclaration_put_counterIncrement,
HTMLCSSStyleDeclaration_get_counterIncrement,
HTMLCSSStyleDeclaration_put_counterReset,
HTMLCSSStyleDeclaration_get_counterReset,
HTMLCSSStyleDeclaration_put_outline,
HTMLCSSStyleDeclaration_get_outline,
HTMLCSSStyleDeclaration_put_outlineWidth,
HTMLCSSStyleDeclaration_get_outlineWidth,
HTMLCSSStyleDeclaration_put_outlineStyle,
HTMLCSSStyleDeclaration_get_outlineStyle,
HTMLCSSStyleDeclaration_put_outlineColor,
HTMLCSSStyleDeclaration_get_outlineColor,
HTMLCSSStyleDeclaration_put_boxSizing,
HTMLCSSStyleDeclaration_get_boxSizing,
HTMLCSSStyleDeclaration_put_borderSpacing,
HTMLCSSStyleDeclaration_get_borderSpacing,
HTMLCSSStyleDeclaration_put_orphans,
HTMLCSSStyleDeclaration_get_orphans,
HTMLCSSStyleDeclaration_put_widows,
HTMLCSSStyleDeclaration_get_widows,
HTMLCSSStyleDeclaration_put_pageBreakInside,
HTMLCSSStyleDeclaration_get_pageBreakInside,
HTMLCSSStyleDeclaration_put_emptyCells,
HTMLCSSStyleDeclaration_get_emptyCells,
HTMLCSSStyleDeclaration_put_msBlockProgression,
HTMLCSSStyleDeclaration_get_msBlockProgression,
HTMLCSSStyleDeclaration_put_quotes,
HTMLCSSStyleDeclaration_get_quotes,
HTMLCSSStyleDeclaration_put_alignmentBaseline,
HTMLCSSStyleDeclaration_get_alignmentBaseline,
HTMLCSSStyleDeclaration_put_baselineShift,
HTMLCSSStyleDeclaration_get_baselineShift,
HTMLCSSStyleDeclaration_put_dominantBaseline,
HTMLCSSStyleDeclaration_get_dominantBaseline,
HTMLCSSStyleDeclaration_put_fontSizeAdjust,
HTMLCSSStyleDeclaration_get_fontSizeAdjust,
HTMLCSSStyleDeclaration_put_fontStretch,
HTMLCSSStyleDeclaration_get_fontStretch,
HTMLCSSStyleDeclaration_put_opacity,
HTMLCSSStyleDeclaration_get_opacity,
HTMLCSSStyleDeclaration_put_clipPath,
HTMLCSSStyleDeclaration_get_clipPath,
HTMLCSSStyleDeclaration_put_clipRule,
HTMLCSSStyleDeclaration_get_clipRule,
HTMLCSSStyleDeclaration_put_fill,
HTMLCSSStyleDeclaration_get_fill,
HTMLCSSStyleDeclaration_put_fillOpacity,
HTMLCSSStyleDeclaration_get_fillOpacity,
HTMLCSSStyleDeclaration_put_fillRule,
HTMLCSSStyleDeclaration_get_fillRule,
HTMLCSSStyleDeclaration_put_kerning,
HTMLCSSStyleDeclaration_get_kerning,
HTMLCSSStyleDeclaration_put_marker,
HTMLCSSStyleDeclaration_get_marker,
HTMLCSSStyleDeclaration_put_markerEnd,
HTMLCSSStyleDeclaration_get_markerEnd,
HTMLCSSStyleDeclaration_put_markerMid,
HTMLCSSStyleDeclaration_get_markerMid,
HTMLCSSStyleDeclaration_put_markerStart,
HTMLCSSStyleDeclaration_get_markerStart,
HTMLCSSStyleDeclaration_put_mask,
HTMLCSSStyleDeclaration_get_mask,
HTMLCSSStyleDeclaration_put_pointerEvents,
HTMLCSSStyleDeclaration_get_pointerEvents,
HTMLCSSStyleDeclaration_put_stopColor,
HTMLCSSStyleDeclaration_get_stopColor,
HTMLCSSStyleDeclaration_put_stopOpacity,
HTMLCSSStyleDeclaration_get_stopOpacity,
HTMLCSSStyleDeclaration_put_stroke,
HTMLCSSStyleDeclaration_get_stroke,
HTMLCSSStyleDeclaration_put_strokeDasharray,
HTMLCSSStyleDeclaration_get_strokeDasharray,
HTMLCSSStyleDeclaration_put_strokeDashoffset,
HTMLCSSStyleDeclaration_get_strokeDashoffset,
HTMLCSSStyleDeclaration_put_strokeLinecap,
HTMLCSSStyleDeclaration_get_strokeLinecap,
HTMLCSSStyleDeclaration_put_strokeLinejoin,
HTMLCSSStyleDeclaration_get_strokeLinejoin,
HTMLCSSStyleDeclaration_put_strokeMiterlimit,
HTMLCSSStyleDeclaration_get_strokeMiterlimit,
HTMLCSSStyleDeclaration_put_strokeOpacity,
HTMLCSSStyleDeclaration_get_strokeOpacity,
HTMLCSSStyleDeclaration_put_strokeWidth,
HTMLCSSStyleDeclaration_get_strokeWidth,
HTMLCSSStyleDeclaration_put_textAnchor,
HTMLCSSStyleDeclaration_get_textAnchor,
HTMLCSSStyleDeclaration_put_glyphOrientationHorizontal,
HTMLCSSStyleDeclaration_get_glyphOrientationHorizontal,
HTMLCSSStyleDeclaration_put_glyphOrientationVertical,
HTMLCSSStyleDeclaration_get_glyphOrientationVertical,
HTMLCSSStyleDeclaration_put_borderRadius,
HTMLCSSStyleDeclaration_get_borderRadius,
HTMLCSSStyleDeclaration_put_borderTopLeftRadius,
HTMLCSSStyleDeclaration_get_borderTopLeftRadius,
HTMLCSSStyleDeclaration_put_borderTopRightRadius,
HTMLCSSStyleDeclaration_get_borderTopRightRadius,
HTMLCSSStyleDeclaration_put_borderBottomRightRadius,
HTMLCSSStyleDeclaration_get_borderBottomRightRadius,
HTMLCSSStyleDeclaration_put_borderBottomLeftRadius,
HTMLCSSStyleDeclaration_get_borderBottomLeftRadius,
HTMLCSSStyleDeclaration_put_clipTop,
HTMLCSSStyleDeclaration_get_clipTop,
HTMLCSSStyleDeclaration_put_clipRight,
HTMLCSSStyleDeclaration_get_clipRight,
HTMLCSSStyleDeclaration_get_clipBottom,
HTMLCSSStyleDeclaration_put_clipLeft,
HTMLCSSStyleDeclaration_get_clipLeft,
HTMLCSSStyleDeclaration_put_cssFloat,
HTMLCSSStyleDeclaration_get_cssFloat,
HTMLCSSStyleDeclaration_put_backgroundClip,
HTMLCSSStyleDeclaration_get_backgroundClip,
HTMLCSSStyleDeclaration_put_backgroundOrigin,
HTMLCSSStyleDeclaration_get_backgroundOrigin,
HTMLCSSStyleDeclaration_put_backgroundSize,
HTMLCSSStyleDeclaration_get_backgroundSize,
HTMLCSSStyleDeclaration_put_boxShadow,
HTMLCSSStyleDeclaration_get_boxShadow,
HTMLCSSStyleDeclaration_put_msTransform,
HTMLCSSStyleDeclaration_get_msTransform,
HTMLCSSStyleDeclaration_put_msTransformOrigin,
HTMLCSSStyleDeclaration_get_msTransformOrigin
};
static inline HTMLStyle *impl_from_IHTMLCSSStyleDeclaration2(IHTMLCSSStyleDeclaration2 *iface)
{
return CONTAINING_RECORD(iface, HTMLStyle, IHTMLCSSStyleDeclaration2_iface);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_QueryInterface(IHTMLCSSStyleDeclaration2 *iface,
REFIID riid, void **ppv)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
return IHTMLStyle_QueryInterface(&This->IHTMLStyle_iface, riid, ppv);
}
static ULONG WINAPI HTMLCSSStyleDeclaration2_AddRef(IHTMLCSSStyleDeclaration2 *iface)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
return IHTMLStyle_AddRef(&This->IHTMLStyle_iface);
}
static ULONG WINAPI HTMLCSSStyleDeclaration2_Release(IHTMLCSSStyleDeclaration2 *iface)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
return IHTMLStyle_Release(&This->IHTMLStyle_iface);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_GetTypeInfoCount(IHTMLCSSStyleDeclaration2 *iface,
UINT *pctinfo)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
TRACE("(%p)->(%p)\n", This, pctinfo);
return IDispatchEx_GetTypeInfoCount(&This->dispex.IDispatchEx_iface, pctinfo);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_GetTypeInfo(IHTMLCSSStyleDeclaration2 *iface,
UINT iTInfo, LCID lcid, ITypeInfo **ppTInfo)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
TRACE("(%p)->(%u %u %p)\n", This, iTInfo, lcid, ppTInfo);
return IDispatchEx_GetTypeInfo(&This->dispex.IDispatchEx_iface, iTInfo, lcid, ppTInfo);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_GetIDsOfNames(IHTMLCSSStyleDeclaration2 *iface,
REFIID riid, LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
TRACE("(%p)->(%p %p %u %u %p)\n", This, riid, rgszNames, cNames, lcid, rgDispId);
return IDispatchEx_GetIDsOfNames(&This->dispex.IDispatchEx_iface, riid, rgszNames,
cNames, lcid, rgDispId);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_Invoke(IHTMLCSSStyleDeclaration2 *iface,
DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams,
VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
TRACE("(%p)->(%d %p %u %u %p %p %p %p)\n", This, dispIdMember, riid, lcid, wFlags,
pDispParams, pVarResult, pExcepInfo, puArgErr);
return IDispatchEx_Invoke(&This->dispex.IDispatchEx_iface, dispIdMember, riid, lcid,
wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr);
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msScrollChaining(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msScrollChaining(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msContentZooming(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msContentZooming(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msContentZoomSnapType(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msContentZoomSnapType(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msScrollRails(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msScrollRails(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msContentZoomChaining(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msContentZoomChaining(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msScrollSnapType(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msScrollSnapType(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msContentZoomLimit(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msContentZoomLimit(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msContentZoomSnap(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msContentZoomSnap(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msContentZoomSnapPoints(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msContentZoomSnapPoints(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msContentZoomLimitMin(IHTMLCSSStyleDeclaration2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msContentZoomLimitMin(IHTMLCSSStyleDeclaration2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msContentZoomLimitMax(IHTMLCSSStyleDeclaration2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msContentZoomLimitMax(IHTMLCSSStyleDeclaration2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msScrollSnapX(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msScrollSnapX(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msScrollSnapY(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msScrollSnapY(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msScrollSnapPointsX(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msScrollSnapPointsX(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msScrollSnapPointsY(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msScrollSnapPointsY(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msGridColumn(IHTMLCSSStyleDeclaration2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msGridColumn(IHTMLCSSStyleDeclaration2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msGridColumnAlign(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msGridColumnAlign(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msGridColumns(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msGridColumns(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msGridColumnSpan(IHTMLCSSStyleDeclaration2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msGridColumnSpan(IHTMLCSSStyleDeclaration2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msGridRow(IHTMLCSSStyleDeclaration2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msGridRow(IHTMLCSSStyleDeclaration2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msGridRowAlign(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msGridRowAlign(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msGridRows(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msGridRows(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msGridRowSpan(IHTMLCSSStyleDeclaration2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msGridRowSpan(IHTMLCSSStyleDeclaration2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msWrapThrough(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msWrapThrough(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msWrapMargin(IHTMLCSSStyleDeclaration2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msWrapMargin(IHTMLCSSStyleDeclaration2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msWrapFlow(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msWrapFlow(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msAnimationName(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msAnimationName(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msAnimationDuration(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msAnimationDuration(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msAnimationTimingFunction(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msAnimationTimingFunction(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msAnimationDelay(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msAnimationDelay(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msAnimationDirection(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msAnimationDirection(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msAnimationPlayState(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msAnimationPlayState(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msAnimationIterationCount(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msAnimationIterationCount(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msAnimation(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msAnimation(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msAnimationFillMode(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msAnimationFillMode(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_colorInterpolationFilters(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_colorInterpolationFilters(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_columnCount(IHTMLCSSStyleDeclaration2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_columnCount(IHTMLCSSStyleDeclaration2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_columnWidth(IHTMLCSSStyleDeclaration2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_columnWidth(IHTMLCSSStyleDeclaration2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_columnGap(IHTMLCSSStyleDeclaration2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_columnGap(IHTMLCSSStyleDeclaration2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_columnFill(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_columnFill(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_columnSpan(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_columnSpan(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_columns(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_columns(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_columnRule(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_columnRule(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_columnRuleColor(IHTMLCSSStyleDeclaration2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_columnRuleColor(IHTMLCSSStyleDeclaration2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_columnRuleStyle(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_columnRuleStyle(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_columnRuleWidth(IHTMLCSSStyleDeclaration2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_columnRuleWidth(IHTMLCSSStyleDeclaration2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_breakBefore(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_breakBefore(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_breakAfter(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_breakAfter(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_breakInside(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_breakInside(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_floodColor(IHTMLCSSStyleDeclaration2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_floodColor(IHTMLCSSStyleDeclaration2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_floodOpacity(IHTMLCSSStyleDeclaration2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_floodOpacity(IHTMLCSSStyleDeclaration2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_lightingColor(IHTMLCSSStyleDeclaration2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_lightingColor(IHTMLCSSStyleDeclaration2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msScrollLimitXMin(IHTMLCSSStyleDeclaration2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msScrollLimitXMin(IHTMLCSSStyleDeclaration2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msScrollLimitYMin(IHTMLCSSStyleDeclaration2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msScrollLimitYMin(IHTMLCSSStyleDeclaration2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msScrollLimitXMax(IHTMLCSSStyleDeclaration2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msScrollLimitXMax(IHTMLCSSStyleDeclaration2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msScrollLimitYMax(IHTMLCSSStyleDeclaration2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msScrollLimitYMax(IHTMLCSSStyleDeclaration2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msScrollLimit(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msScrollLimit(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_textShadow(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_textShadow(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msFlowFrom(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msFlowFrom(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msFlowInto(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msFlowInto(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msHyphens(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msHyphens(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msHyphenateLimitZone(IHTMLCSSStyleDeclaration2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msHyphenateLimitZone(IHTMLCSSStyleDeclaration2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msHyphenateLimitChars(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msHyphenateLimitChars(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msHyphenateLimitLines(IHTMLCSSStyleDeclaration2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msHyphenateLimitLines(IHTMLCSSStyleDeclaration2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msHighContrastAdjust(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msHighContrastAdjust(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_enableBackground(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_enableBackground(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msFontFeatureSettings(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msFontFeatureSettings(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msUserSelect(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msUserSelect(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msOverflowStyle(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msOverflowStyle(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msTransformStyle(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msTransformStyle(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msBackfaceVisibility(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msBackfaceVisibility(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msPerspective(IHTMLCSSStyleDeclaration2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msPerspective(IHTMLCSSStyleDeclaration2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msPerspectiveOrigin(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msPerspectiveOrigin(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msTransitionProperty(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msTransitionProperty(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msTransitionDuration(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msTransitionDuration(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msTransitionTimingFunction(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msTransitionTimingFunction(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msTransitionDelay(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msTransitionDelay(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msTransition(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msTransition(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msTouchAction(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msTouchAction(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msScrollTranslation(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msScrollTranslation(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msFlex(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msFlex(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msFlexPositive(IHTMLCSSStyleDeclaration2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msFlexPositive(IHTMLCSSStyleDeclaration2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msFlexNegative(IHTMLCSSStyleDeclaration2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msFlexNegative(IHTMLCSSStyleDeclaration2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msFlexPreferredSize(IHTMLCSSStyleDeclaration2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msFlexPreferredSize(IHTMLCSSStyleDeclaration2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msFlexFlow(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msFlexFlow(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msFlexDirection(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msFlexDirection(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msFlexWrap(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msFlexWrap(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msFlexAlign(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msFlexAlign(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msFlexItemAlign(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msFlexItemAlign(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msFlexPack(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msFlexPack(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msFlexLinePack(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msFlexLinePack(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msFlexOrder(IHTMLCSSStyleDeclaration2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msFlexOrder(IHTMLCSSStyleDeclaration2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_msTouchSelect(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_msTouchSelect(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_transform(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_transform(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_transformOrigin(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_transformOrigin(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_transformStyle(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_transformStyle(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_backfaceVisibility(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_backfaceVisibility(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_perspective(IHTMLCSSStyleDeclaration2 *iface, VARIANT v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_variant(&v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_perspective(IHTMLCSSStyleDeclaration2 *iface, VARIANT *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_perspectiveOrigin(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_perspectiveOrigin(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_transitionProperty(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_transitionProperty(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_transitionDuration(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_transitionDuration(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_transitionTimingFunction(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_transitionTimingFunction(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_transitionDelay(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_transitionDelay(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_transition(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_transition(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_fontFeatureSettings(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_fontFeatureSettings(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_animationName(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_animationName(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_animationDuration(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_animationDuration(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_animationTimingFunction(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_animationTimingFunction(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_animationDelay(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_animationDelay(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_animationDirection(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_animationDirection(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_animationPlayState(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_animationPlayState(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_animationIterationCount(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_animationIterationCount(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_animation(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_animation(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_put_animationFillMode(IHTMLCSSStyleDeclaration2 *iface, BSTR v)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%s)\n", This, debugstr_w(v));
return E_NOTIMPL;
}
static HRESULT WINAPI HTMLCSSStyleDeclaration2_get_animationFillMode(IHTMLCSSStyleDeclaration2 *iface, BSTR *p)
{
HTMLStyle *This = impl_from_IHTMLCSSStyleDeclaration2(iface);
FIXME("(%p)->(%p)\n", This, p);
return E_NOTIMPL;
}
static const IHTMLCSSStyleDeclaration2Vtbl HTMLCSSStyleDeclaration2Vtbl = {
HTMLCSSStyleDeclaration2_QueryInterface,
HTMLCSSStyleDeclaration2_AddRef,
HTMLCSSStyleDeclaration2_Release,
HTMLCSSStyleDeclaration2_GetTypeInfoCount,
HTMLCSSStyleDeclaration2_GetTypeInfo,
HTMLCSSStyleDeclaration2_GetIDsOfNames,
HTMLCSSStyleDeclaration2_Invoke,
HTMLCSSStyleDeclaration2_put_msScrollChaining,
HTMLCSSStyleDeclaration2_get_msScrollChaining,
HTMLCSSStyleDeclaration2_put_msContentZooming,
HTMLCSSStyleDeclaration2_get_msContentZooming,
HTMLCSSStyleDeclaration2_put_msContentZoomSnapType,
HTMLCSSStyleDeclaration2_get_msContentZoomSnapType,
HTMLCSSStyleDeclaration2_put_msScrollRails,
HTMLCSSStyleDeclaration2_get_msScrollRails,
HTMLCSSStyleDeclaration2_put_msContentZoomChaining,
HTMLCSSStyleDeclaration2_get_msContentZoomChaining,
HTMLCSSStyleDeclaration2_put_msScrollSnapType,
HTMLCSSStyleDeclaration2_get_msScrollSnapType,
HTMLCSSStyleDeclaration2_put_msContentZoomLimit,
HTMLCSSStyleDeclaration2_get_msContentZoomLimit,
HTMLCSSStyleDeclaration2_put_msContentZoomSnap,
HTMLCSSStyleDeclaration2_get_msContentZoomSnap,
HTMLCSSStyleDeclaration2_put_msContentZoomSnapPoints,
HTMLCSSStyleDeclaration2_get_msContentZoomSnapPoints,
HTMLCSSStyleDeclaration2_put_msContentZoomLimitMin,
HTMLCSSStyleDeclaration2_get_msContentZoomLimitMin,
HTMLCSSStyleDeclaration2_put_msContentZoomLimitMax,
HTMLCSSStyleDeclaration2_get_msContentZoomLimitMax,
HTMLCSSStyleDeclaration2_put_msScrollSnapX,
HTMLCSSStyleDeclaration2_get_msScrollSnapX,
HTMLCSSStyleDeclaration2_put_msScrollSnapY,
HTMLCSSStyleDeclaration2_get_msScrollSnapY,
HTMLCSSStyleDeclaration2_put_msScrollSnapPointsX,
HTMLCSSStyleDeclaration2_get_msScrollSnapPointsX,
HTMLCSSStyleDeclaration2_put_msScrollSnapPointsY,
HTMLCSSStyleDeclaration2_get_msScrollSnapPointsY,
HTMLCSSStyleDeclaration2_put_msGridColumn,
HTMLCSSStyleDeclaration2_get_msGridColumn,
HTMLCSSStyleDeclaration2_put_msGridColumnAlign,
HTMLCSSStyleDeclaration2_get_msGridColumnAlign,
HTMLCSSStyleDeclaration2_put_msGridColumns,
HTMLCSSStyleDeclaration2_get_msGridColumns,
HTMLCSSStyleDeclaration2_put_msGridColumnSpan,
HTMLCSSStyleDeclaration2_get_msGridColumnSpan,
HTMLCSSStyleDeclaration2_put_msGridRow,
HTMLCSSStyleDeclaration2_get_msGridRow,
HTMLCSSStyleDeclaration2_put_msGridRowAlign,
HTMLCSSStyleDeclaration2_get_msGridRowAlign,
HTMLCSSStyleDeclaration2_put_msGridRows,
HTMLCSSStyleDeclaration2_get_msGridRows,
HTMLCSSStyleDeclaration2_put_msGridRowSpan,
HTMLCSSStyleDeclaration2_get_msGridRowSpan,
HTMLCSSStyleDeclaration2_put_msWrapThrough,
HTMLCSSStyleDeclaration2_get_msWrapThrough,
HTMLCSSStyleDeclaration2_put_msWrapMargin,
HTMLCSSStyleDeclaration2_get_msWrapMargin,
HTMLCSSStyleDeclaration2_put_msWrapFlow,
HTMLCSSStyleDeclaration2_get_msWrapFlow,
HTMLCSSStyleDeclaration2_put_msAnimationName,
HTMLCSSStyleDeclaration2_get_msAnimationName,
HTMLCSSStyleDeclaration2_put_msAnimationDuration,
HTMLCSSStyleDeclaration2_get_msAnimationDuration,
HTMLCSSStyleDeclaration2_put_msAnimationTimingFunction,
HTMLCSSStyleDeclaration2_get_msAnimationTimingFunction,
HTMLCSSStyleDeclaration2_put_msAnimationDelay,
HTMLCSSStyleDeclaration2_get_msAnimationDelay,
HTMLCSSStyleDeclaration2_put_msAnimationDirection,
HTMLCSSStyleDeclaration2_get_msAnimationDirection,
HTMLCSSStyleDeclaration2_put_msAnimationPlayState,
HTMLCSSStyleDeclaration2_get_msAnimationPlayState,
HTMLCSSStyleDeclaration2_put_msAnimationIterationCount,
HTMLCSSStyleDeclaration2_get_msAnimationIterationCount,
HTMLCSSStyleDeclaration2_put_msAnimation,
HTMLCSSStyleDeclaration2_get_msAnimation,
HTMLCSSStyleDeclaration2_put_msAnimationFillMode,
HTMLCSSStyleDeclaration2_get_msAnimationFillMode,
HTMLCSSStyleDeclaration2_put_colorInterpolationFilters,
HTMLCSSStyleDeclaration2_get_colorInterpolationFilters,
HTMLCSSStyleDeclaration2_put_columnCount,
HTMLCSSStyleDeclaration2_get_columnCount,
HTMLCSSStyleDeclaration2_put_columnWidth,
HTMLCSSStyleDeclaration2_get_columnWidth,
HTMLCSSStyleDeclaration2_put_columnGap,
HTMLCSSStyleDeclaration2_get_columnGap,
HTMLCSSStyleDeclaration2_put_columnFill,
HTMLCSSStyleDeclaration2_get_columnFill,
HTMLCSSStyleDeclaration2_put_columnSpan,
HTMLCSSStyleDeclaration2_get_columnSpan,
HTMLCSSStyleDeclaration2_put_columns,
HTMLCSSStyleDeclaration2_get_columns,
HTMLCSSStyleDeclaration2_put_columnRule,
HTMLCSSStyleDeclaration2_get_columnRule,
HTMLCSSStyleDeclaration2_put_columnRuleColor,
HTMLCSSStyleDeclaration2_get_columnRuleColor,
HTMLCSSStyleDeclaration2_put_columnRuleStyle,
HTMLCSSStyleDeclaration2_get_columnRuleStyle,
HTMLCSSStyleDeclaration2_put_columnRuleWidth,
HTMLCSSStyleDeclaration2_get_columnRuleWidth,
HTMLCSSStyleDeclaration2_put_breakBefore,
HTMLCSSStyleDeclaration2_get_breakBefore,
HTMLCSSStyleDeclaration2_put_breakAfter,
HTMLCSSStyleDeclaration2_get_breakAfter,
HTMLCSSStyleDeclaration2_put_breakInside,
HTMLCSSStyleDeclaration2_get_breakInside,
HTMLCSSStyleDeclaration2_put_floodColor,
HTMLCSSStyleDeclaration2_get_floodColor,
HTMLCSSStyleDeclaration2_put_floodOpacity,
HTMLCSSStyleDeclaration2_get_floodOpacity,
HTMLCSSStyleDeclaration2_put_lightingColor,
HTMLCSSStyleDeclaration2_get_lightingColor,
HTMLCSSStyleDeclaration2_put_msScrollLimitXMin,
HTMLCSSStyleDeclaration2_get_msScrollLimitXMin,
HTMLCSSStyleDeclaration2_put_msScrollLimitYMin,
HTMLCSSStyleDeclaration2_get_msScrollLimitYMin,
HTMLCSSStyleDeclaration2_put_msScrollLimitXMax,
HTMLCSSStyleDeclaration2_get_msScrollLimitXMax,
HTMLCSSStyleDeclaration2_put_msScrollLimitYMax,
HTMLCSSStyleDeclaration2_get_msScrollLimitYMax,
HTMLCSSStyleDeclaration2_put_msScrollLimit,
HTMLCSSStyleDeclaration2_get_msScrollLimit,
HTMLCSSStyleDeclaration2_put_textShadow,
HTMLCSSStyleDeclaration2_get_textShadow,
HTMLCSSStyleDeclaration2_put_msFlowFrom,
HTMLCSSStyleDeclaration2_get_msFlowFrom,
HTMLCSSStyleDeclaration2_put_msFlowInto,
HTMLCSSStyleDeclaration2_get_msFlowInto,
HTMLCSSStyleDeclaration2_put_msHyphens,
HTMLCSSStyleDeclaration2_get_msHyphens,
HTMLCSSStyleDeclaration2_put_msHyphenateLimitZone,
HTMLCSSStyleDeclaration2_get_msHyphenateLimitZone,
HTMLCSSStyleDeclaration2_put_msHyphenateLimitChars,
HTMLCSSStyleDeclaration2_get_msHyphenateLimitChars,
HTMLCSSStyleDeclaration2_put_msHyphenateLimitLines,
HTMLCSSStyleDeclaration2_get_msHyphenateLimitLines,
HTMLCSSStyleDeclaration2_put_msHighContrastAdjust,
HTMLCSSStyleDeclaration2_get_msHighContrastAdjust,
HTMLCSSStyleDeclaration2_put_enableBackground,
HTMLCSSStyleDeclaration2_get_enableBackground,
HTMLCSSStyleDeclaration2_put_msFontFeatureSettings,
HTMLCSSStyleDeclaration2_get_msFontFeatureSettings,
HTMLCSSStyleDeclaration2_put_msUserSelect,
HTMLCSSStyleDeclaration2_get_msUserSelect,
HTMLCSSStyleDeclaration2_put_msOverflowStyle,
HTMLCSSStyleDeclaration2_get_msOverflowStyle,
HTMLCSSStyleDeclaration2_put_msTransformStyle,
HTMLCSSStyleDeclaration2_get_msTransformStyle,
HTMLCSSStyleDeclaration2_put_msBackfaceVisibility,
HTMLCSSStyleDeclaration2_get_msBackfaceVisibility,
HTMLCSSStyleDeclaration2_put_msPerspective,
HTMLCSSStyleDeclaration2_get_msPerspective,
HTMLCSSStyleDeclaration2_put_msPerspectiveOrigin,
HTMLCSSStyleDeclaration2_get_msPerspectiveOrigin,
HTMLCSSStyleDeclaration2_put_msTransitionProperty,
HTMLCSSStyleDeclaration2_get_msTransitionProperty,
HTMLCSSStyleDeclaration2_put_msTransitionDuration,
HTMLCSSStyleDeclaration2_get_msTransitionDuration,
HTMLCSSStyleDeclaration2_put_msTransitionTimingFunction,
HTMLCSSStyleDeclaration2_get_msTransitionTimingFunction,
HTMLCSSStyleDeclaration2_put_msTransitionDelay,
HTMLCSSStyleDeclaration2_get_msTransitionDelay,
HTMLCSSStyleDeclaration2_put_msTransition,
HTMLCSSStyleDeclaration2_get_msTransition,
HTMLCSSStyleDeclaration2_put_msTouchAction,
HTMLCSSStyleDeclaration2_get_msTouchAction,
HTMLCSSStyleDeclaration2_put_msScrollTranslation,
HTMLCSSStyleDeclaration2_get_msScrollTranslation,
HTMLCSSStyleDeclaration2_put_msFlex,
HTMLCSSStyleDeclaration2_get_msFlex,
HTMLCSSStyleDeclaration2_put_msFlexPositive,
HTMLCSSStyleDeclaration2_get_msFlexPositive,
HTMLCSSStyleDeclaration2_put_msFlexNegative,
HTMLCSSStyleDeclaration2_get_msFlexNegative,
HTMLCSSStyleDeclaration2_put_msFlexPreferredSize,
HTMLCSSStyleDeclaration2_get_msFlexPreferredSize,
HTMLCSSStyleDeclaration2_put_msFlexFlow,
HTMLCSSStyleDeclaration2_get_msFlexFlow,
HTMLCSSStyleDeclaration2_put_msFlexDirection,
HTMLCSSStyleDeclaration2_get_msFlexDirection,
HTMLCSSStyleDeclaration2_put_msFlexWrap,
HTMLCSSStyleDeclaration2_get_msFlexWrap,
HTMLCSSStyleDeclaration2_put_msFlexAlign,
HTMLCSSStyleDeclaration2_get_msFlexAlign,
HTMLCSSStyleDeclaration2_put_msFlexItemAlign,
HTMLCSSStyleDeclaration2_get_msFlexItemAlign,
HTMLCSSStyleDeclaration2_put_msFlexPack,
HTMLCSSStyleDeclaration2_get_msFlexPack,
HTMLCSSStyleDeclaration2_put_msFlexLinePack,
HTMLCSSStyleDeclaration2_get_msFlexLinePack,
HTMLCSSStyleDeclaration2_put_msFlexOrder,
HTMLCSSStyleDeclaration2_get_msFlexOrder,
HTMLCSSStyleDeclaration2_put_msTouchSelect,
HTMLCSSStyleDeclaration2_get_msTouchSelect,
HTMLCSSStyleDeclaration2_put_transform,
HTMLCSSStyleDeclaration2_get_transform,
HTMLCSSStyleDeclaration2_put_transformOrigin,
HTMLCSSStyleDeclaration2_get_transformOrigin,
HTMLCSSStyleDeclaration2_put_transformStyle,
HTMLCSSStyleDeclaration2_get_transformStyle,
HTMLCSSStyleDeclaration2_put_backfaceVisibility,
HTMLCSSStyleDeclaration2_get_backfaceVisibility,
HTMLCSSStyleDeclaration2_put_perspective,
HTMLCSSStyleDeclaration2_get_perspective,
HTMLCSSStyleDeclaration2_put_perspectiveOrigin,
HTMLCSSStyleDeclaration2_get_perspectiveOrigin,
HTMLCSSStyleDeclaration2_put_transitionProperty,
HTMLCSSStyleDeclaration2_get_transitionProperty,
HTMLCSSStyleDeclaration2_put_transitionDuration,
HTMLCSSStyleDeclaration2_get_transitionDuration,
HTMLCSSStyleDeclaration2_put_transitionTimingFunction,
HTMLCSSStyleDeclaration2_get_transitionTimingFunction,
HTMLCSSStyleDeclaration2_put_transitionDelay,
HTMLCSSStyleDeclaration2_get_transitionDelay,
HTMLCSSStyleDeclaration2_put_transition,
HTMLCSSStyleDeclaration2_get_transition,
HTMLCSSStyleDeclaration2_put_fontFeatureSettings,
HTMLCSSStyleDeclaration2_get_fontFeatureSettings,
HTMLCSSStyleDeclaration2_put_animationName,
HTMLCSSStyleDeclaration2_get_animationName,
HTMLCSSStyleDeclaration2_put_animationDuration,
HTMLCSSStyleDeclaration2_get_animationDuration,
HTMLCSSStyleDeclaration2_put_animationTimingFunction,
HTMLCSSStyleDeclaration2_get_animationTimingFunction,
HTMLCSSStyleDeclaration2_put_animationDelay,
HTMLCSSStyleDeclaration2_get_animationDelay,
HTMLCSSStyleDeclaration2_put_animationDirection,
HTMLCSSStyleDeclaration2_get_animationDirection,
HTMLCSSStyleDeclaration2_put_animationPlayState,
HTMLCSSStyleDeclaration2_get_animationPlayState,
HTMLCSSStyleDeclaration2_put_animationIterationCount,
HTMLCSSStyleDeclaration2_get_animationIterationCount,
HTMLCSSStyleDeclaration2_put_animation,
HTMLCSSStyleDeclaration2_get_animation,
HTMLCSSStyleDeclaration2_put_animationFillMode,
HTMLCSSStyleDeclaration2_get_animationFillMode
};
static HRESULT HTMLStyle_get_dispid(DispatchEx *dispex, BSTR name, DWORD flags, DISPID *dispid)
{
const style_tbl_entry_t *style_entry;
style_entry = lookup_style_tbl(name);
if(style_entry) {
DISPID id = dispex_compat_mode(dispex) >= COMPAT_MODE_IE9
? style_entry->dispid : style_entry->compat_dispid;
if(id == DISPID_UNKNOWN)
return DISP_E_UNKNOWNNAME;
*dispid = id;
return S_OK;
}
return DISP_E_UNKNOWNNAME;
}
static void HTMLStyle_init_dispex_info(dispex_data_t *info, compat_mode_t mode)
{
if(mode >= COMPAT_MODE_IE9)
dispex_info_add_interface(info, IHTMLCSSStyleDeclaration_tid, NULL);
}
static const dispex_static_data_vtbl_t HTMLStyle_dispex_vtbl = {
NULL,
HTMLStyle_get_dispid,
NULL,
NULL
};
static const tid_t HTMLStyle_iface_tids[] = {
IHTMLStyle6_tid,
IHTMLStyle5_tid,
IHTMLStyle4_tid,
IHTMLStyle3_tid,
IHTMLStyle2_tid,
IHTMLStyle_tid,
0
};
static dispex_static_data_t HTMLStyle_dispex = {
&HTMLStyle_dispex_vtbl,
DispHTMLStyle_tid,
HTMLStyle_iface_tids,
HTMLStyle_init_dispex_info
};
static HRESULT get_style_from_elem(HTMLElement *elem, nsIDOMCSSStyleDeclaration **ret)
{
nsIDOMElementCSSInlineStyle *nselemstyle;
nsresult nsres;
if(!elem->dom_element) {
FIXME("comment element\n");
return E_NOTIMPL;
}
nsres = nsIDOMElement_QueryInterface(elem->dom_element, &IID_nsIDOMElementCSSInlineStyle,
(void**)&nselemstyle);
assert(nsres == NS_OK);
nsres = nsIDOMElementCSSInlineStyle_GetStyle(nselemstyle, ret);
nsIDOMElementCSSInlineStyle_Release(nselemstyle);
if(NS_FAILED(nsres)) {
ERR("GetStyle failed: %08x\n", nsres);
return E_FAIL;
}
return S_OK;
}
HRESULT HTMLStyle_Create(HTMLElement *elem, HTMLStyle **ret)
{
nsIDOMCSSStyleDeclaration *nsstyle;
HTMLStyle *style;
HRESULT hres;
hres = get_style_from_elem(elem, &nsstyle);
if(FAILED(hres))
return hres;
style = heap_alloc_zero(sizeof(HTMLStyle));
if(!style) {
nsIDOMCSSStyleDeclaration_Release(nsstyle);
return E_OUTOFMEMORY;
}
style->IHTMLStyle_iface.lpVtbl = &HTMLStyleVtbl;
style->IHTMLStyle2_iface.lpVtbl = &HTMLStyle2Vtbl;
style->IHTMLStyle3_iface.lpVtbl = &HTMLStyle3Vtbl;
style->IHTMLStyle4_iface.lpVtbl = &HTMLStyle4Vtbl;
style->IHTMLStyle5_iface.lpVtbl = &HTMLStyle5Vtbl;
style->IHTMLStyle6_iface.lpVtbl = &HTMLStyle6Vtbl;
style->IHTMLCSSStyleDeclaration_iface.lpVtbl = &HTMLCSSStyleDeclarationVtbl;
style->IHTMLCSSStyleDeclaration2_iface.lpVtbl = &HTMLCSSStyleDeclaration2Vtbl;
style->ref = 1;
style->nsstyle = nsstyle;
style->elem = elem;
nsIDOMCSSStyleDeclaration_AddRef(nsstyle);
init_dispex_with_compat_mode(&style->dispex, (IUnknown*)&style->IHTMLStyle_iface, &HTMLStyle_dispex,
dispex_compat_mode(&elem->node.event_target.dispex));
*ret = style;
return S_OK;
}
HRESULT get_elem_style(HTMLElement *elem, styleid_t styleid, BSTR *ret)
{
nsIDOMCSSStyleDeclaration *style;
HRESULT hres;
hres = get_style_from_elem(elem, &style);
if(FAILED(hres))
return hres;
hres = get_nsstyle_property(style, styleid, COMPAT_MODE_IE11, ret);
nsIDOMCSSStyleDeclaration_Release(style);
return hres;
}
HRESULT set_elem_style(HTMLElement *elem, styleid_t styleid, const WCHAR *val)
{
nsIDOMCSSStyleDeclaration *style;
HRESULT hres;
hres = get_style_from_elem(elem, &style);
if(FAILED(hres))
return hres;
hres = set_nsstyle_property(style, styleid, val);
nsIDOMCSSStyleDeclaration_Release(style);
return hres;
}
|
622906.c | #include <curses.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "display.h"
int slideCount;
int max_x;
int max_y;
short keyDigit1 = -1;
short keyDigit2 = -1;
void setSlideCount(int* slides)
{
slideCount = *slides;
}
void initDisplay()
{
// initialize ncurses
initscr();
cbreak();
noecho();
clear();
}
void closeDisplay()
{
// end ncurses session
endwin();
exit(0);
}
void displayLoop(Slide *slide, int* slideNumber, char* title, char* fileName)
{
// assigns screen x/y length continually (incase of screen resize)
getmaxyx(stdscr, max_y, max_x);
printw(title);
printw("\n");
printw(slide->content); //to be used when parser.c implemented
mvprintw(max_y-1, 1, fileName);
char bottomRightCounter[15];
sprintf(bottomRightCounter, "slide %i / %i", slide->number, slideCount);
mvprintw(max_y-1, max_x-15, bottomRightCounter);
int keyInput = getch();
switch(keyInput) {
case 'q':
case 'Q':
closeDisplay();
break;
case 'j':
case 'J':
case ' ':
if (*slideNumber != slideCount-1) {
*slideNumber = *slideNumber + 1;
}
break;
case 'k':
case 'K':
if (*slideNumber != 0) {
*slideNumber = *slideNumber - 1;
}
break;
case '9':
case '8':
case '7':
case '6':
case '5':
case '4':
case '3':
case '2':
case '1':
case '0':
if (keyDigit1 >= 1 && keyDigit2 >= 0) {
keyDigit1 = keyInput - 48;
keyDigit2 = -1;
} else if (keyDigit1 == -1 && keyInput != '0') {
keyDigit1 = keyInput - 48;
} else if (keyDigit2 == -1) {
keyDigit2 = keyInput - 48;
}
//if ((keyInput-48) <= slideCount) {
//*slideNumber = keyInput - 49;
//}
break;
case 'g':
*slideNumber = 0;
break;
case 'G':
if (keyDigit1 >= 0) {
if (keyDigit2 >= 0) { // todo: look into making sure 2 digits slides are found correctly
char dest[3];
if (keyDigit2 == 0) {
sprintf(dest, "%i%i", keyDigit1-1, 9);
} else {
sprintf(dest, "%i%i", keyDigit1, keyDigit2-1);
}
if (atoi(dest)<=slideCount) {
*slideNumber = atoi(dest);
keyDigit1 = -1;
keyDigit2 = -1;
}
} else {
if (keyDigit1<=slideCount) {
*slideNumber = keyDigit1-1;
keyDigit1 = -1;
}
}
} else {
*slideNumber = slideCount - 1;
}
break;
default:
break;
}
clear();
}
|
304595.c | /*
* ALSA SoC I2S Audio Layer for the Stretch S6000 family
*
* Author: Daniel Gloeckner, <[email protected]>
* Copyright: (C) 2009 emlix GmbH <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/clk.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/initval.h>
#include <sound/soc.h>
#include "s6000-i2s.h"
#include "s6000-pcm.h"
struct s6000_i2s_dev {
dma_addr_t sifbase;
u8 __iomem *scbbase;
unsigned int wide;
unsigned int channel_in;
unsigned int channel_out;
unsigned int lines_in;
unsigned int lines_out;
struct s6000_pcm_dma_params dma_params;
};
#define S6_I2S_INTERRUPT_STATUS 0x00
#define S6_I2S_INT_OVERRUN 1
#define S6_I2S_INT_UNDERRUN 2
#define S6_I2S_INT_ALIGNMENT 4
#define S6_I2S_INTERRUPT_ENABLE 0x04
#define S6_I2S_INTERRUPT_RAW 0x08
#define S6_I2S_INTERRUPT_CLEAR 0x0C
#define S6_I2S_INTERRUPT_SET 0x10
#define S6_I2S_MODE 0x20
#define S6_I2S_DUAL 0
#define S6_I2S_WIDE 1
#define S6_I2S_TX_DEFAULT 0x24
#define S6_I2S_DATA_CFG(c) (0x40 + 0x10 * (c))
#define S6_I2S_IN 0
#define S6_I2S_OUT 1
#define S6_I2S_UNUSED 2
#define S6_I2S_INTERFACE_CFG(c) (0x44 + 0x10 * (c))
#define S6_I2S_DIV_MASK 0x001fff
#define S6_I2S_16BIT 0x000000
#define S6_I2S_20BIT 0x002000
#define S6_I2S_24BIT 0x004000
#define S6_I2S_32BIT 0x006000
#define S6_I2S_BITS_MASK 0x006000
#define S6_I2S_MEM_16BIT 0x000000
#define S6_I2S_MEM_32BIT 0x008000
#define S6_I2S_MEM_MASK 0x008000
#define S6_I2S_CHANNELS_SHIFT 16
#define S6_I2S_CHANNELS_MASK 0x030000
#define S6_I2S_SCK_IN 0x000000
#define S6_I2S_SCK_OUT 0x040000
#define S6_I2S_SCK_DIR 0x040000
#define S6_I2S_WS_IN 0x000000
#define S6_I2S_WS_OUT 0x080000
#define S6_I2S_WS_DIR 0x080000
#define S6_I2S_LEFT_FIRST 0x000000
#define S6_I2S_RIGHT_FIRST 0x100000
#define S6_I2S_FIRST 0x100000
#define S6_I2S_CUR_SCK 0x200000
#define S6_I2S_CUR_WS 0x400000
#define S6_I2S_ENABLE(c) (0x48 + 0x10 * (c))
#define S6_I2S_DISABLE_IF 0x02
#define S6_I2S_ENABLE_IF 0x03
#define S6_I2S_IS_BUSY 0x04
#define S6_I2S_DMA_ACTIVE 0x08
#define S6_I2S_IS_ENABLED 0x10
#define S6_I2S_NUM_LINES 4
#define S6_I2S_SIF_PORT0 0x0000000
#define S6_I2S_SIF_PORT1 0x0000080 /* docs say 0x0000010 */
static inline void s6_i2s_write_reg(struct s6000_i2s_dev *dev, int reg, u32 val)
{
writel(val, dev->scbbase + reg);
}
static inline u32 s6_i2s_read_reg(struct s6000_i2s_dev *dev, int reg)
{
return readl(dev->scbbase + reg);
}
static inline void s6_i2s_mod_reg(struct s6000_i2s_dev *dev, int reg,
u32 mask, u32 val)
{
val ^= s6_i2s_read_reg(dev, reg) & ~mask;
s6_i2s_write_reg(dev, reg, val);
}
static void s6000_i2s_start_channel(struct s6000_i2s_dev *dev, int channel)
{
int i, j, cur, prev;
/*
* Wait for WCLK to toggle 5 times before enabling the channel
* s6000 Family Datasheet 3.6.4:
* "At least two cycles of WS must occur between commands
* to disable or enable the interface"
*/
j = 0;
prev = ~S6_I2S_CUR_WS;
for (i = 1000000; --i && j < 6; ) {
cur = s6_i2s_read_reg(dev, S6_I2S_INTERFACE_CFG(channel))
& S6_I2S_CUR_WS;
if (prev != cur) {
prev = cur;
j++;
}
}
if (j < 6)
printk(KERN_WARNING "s6000-i2s: timeout waiting for WCLK\n");
s6_i2s_write_reg(dev, S6_I2S_ENABLE(channel), S6_I2S_ENABLE_IF);
}
static void s6000_i2s_stop_channel(struct s6000_i2s_dev *dev, int channel)
{
s6_i2s_write_reg(dev, S6_I2S_ENABLE(channel), S6_I2S_DISABLE_IF);
}
static void s6000_i2s_start(struct snd_pcm_substream *substream)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct s6000_i2s_dev *dev = rtd->dai->cpu_dai->private_data;
int channel;
channel = (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) ?
dev->channel_out : dev->channel_in;
s6000_i2s_start_channel(dev, channel);
}
static void s6000_i2s_stop(struct snd_pcm_substream *substream)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct s6000_i2s_dev *dev = rtd->dai->cpu_dai->private_data;
int channel;
channel = (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) ?
dev->channel_out : dev->channel_in;
s6000_i2s_stop_channel(dev, channel);
}
static int s6000_i2s_trigger(struct snd_pcm_substream *substream, int cmd,
int after)
{
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
if ((substream->stream == SNDRV_PCM_STREAM_CAPTURE) ^ !after)
s6000_i2s_start(substream);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_SUSPEND:
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
if (!after)
s6000_i2s_stop(substream);
}
return 0;
}
static unsigned int s6000_i2s_int_sources(struct s6000_i2s_dev *dev)
{
unsigned int pending;
pending = s6_i2s_read_reg(dev, S6_I2S_INTERRUPT_RAW);
pending &= S6_I2S_INT_ALIGNMENT |
S6_I2S_INT_UNDERRUN |
S6_I2S_INT_OVERRUN;
s6_i2s_write_reg(dev, S6_I2S_INTERRUPT_CLEAR, pending);
return pending;
}
static unsigned int s6000_i2s_check_xrun(struct snd_soc_dai *cpu_dai)
{
struct s6000_i2s_dev *dev = cpu_dai->private_data;
unsigned int errors;
unsigned int ret;
errors = s6000_i2s_int_sources(dev);
if (likely(!errors))
return 0;
ret = 0;
if (errors & S6_I2S_INT_ALIGNMENT)
printk(KERN_ERR "s6000-i2s: WCLK misaligned\n");
if (errors & S6_I2S_INT_UNDERRUN)
ret |= 1 << SNDRV_PCM_STREAM_PLAYBACK;
if (errors & S6_I2S_INT_OVERRUN)
ret |= 1 << SNDRV_PCM_STREAM_CAPTURE;
return ret;
}
static void s6000_i2s_wait_disabled(struct s6000_i2s_dev *dev)
{
int channel;
int n = 50;
for (channel = 0; channel < 2; channel++) {
while (--n >= 0) {
int v = s6_i2s_read_reg(dev, S6_I2S_ENABLE(channel));
if ((v & S6_I2S_IS_ENABLED)
|| !(v & (S6_I2S_DMA_ACTIVE | S6_I2S_IS_BUSY)))
break;
udelay(20);
}
}
if (n < 0)
printk(KERN_WARNING "s6000-i2s: timeout disabling interfaces");
}
static int s6000_i2s_set_dai_fmt(struct snd_soc_dai *cpu_dai,
unsigned int fmt)
{
struct s6000_i2s_dev *dev = cpu_dai->private_data;
u32 w;
switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) {
case SND_SOC_DAIFMT_CBM_CFM:
w = S6_I2S_SCK_IN | S6_I2S_WS_IN;
break;
case SND_SOC_DAIFMT_CBS_CFM:
w = S6_I2S_SCK_OUT | S6_I2S_WS_IN;
break;
case SND_SOC_DAIFMT_CBM_CFS:
w = S6_I2S_SCK_IN | S6_I2S_WS_OUT;
break;
case SND_SOC_DAIFMT_CBS_CFS:
w = S6_I2S_SCK_OUT | S6_I2S_WS_OUT;
break;
default:
return -EINVAL;
}
switch (fmt & SND_SOC_DAIFMT_INV_MASK) {
case SND_SOC_DAIFMT_NB_NF:
w |= S6_I2S_LEFT_FIRST;
break;
case SND_SOC_DAIFMT_NB_IF:
w |= S6_I2S_RIGHT_FIRST;
break;
default:
return -EINVAL;
}
s6_i2s_mod_reg(dev, S6_I2S_INTERFACE_CFG(0),
S6_I2S_FIRST | S6_I2S_WS_DIR | S6_I2S_SCK_DIR, w);
s6_i2s_mod_reg(dev, S6_I2S_INTERFACE_CFG(1),
S6_I2S_FIRST | S6_I2S_WS_DIR | S6_I2S_SCK_DIR, w);
return 0;
}
static int s6000_i2s_set_clkdiv(struct snd_soc_dai *dai, int div_id, int div)
{
struct s6000_i2s_dev *dev = dai->private_data;
if (!div || (div & 1) || div > (S6_I2S_DIV_MASK + 1) * 2)
return -EINVAL;
s6_i2s_mod_reg(dev, S6_I2S_INTERFACE_CFG(div_id),
S6_I2S_DIV_MASK, div / 2 - 1);
return 0;
}
static int s6000_i2s_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct s6000_i2s_dev *dev = dai->private_data;
int interf;
u32 w = 0;
if (dev->wide)
interf = 0;
else {
w |= (((params_channels(params) - 2) / 2)
<< S6_I2S_CHANNELS_SHIFT) & S6_I2S_CHANNELS_MASK;
interf = (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
? dev->channel_out : dev->channel_in;
}
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
w |= S6_I2S_16BIT | S6_I2S_MEM_16BIT;
break;
case SNDRV_PCM_FORMAT_S32_LE:
w |= S6_I2S_32BIT | S6_I2S_MEM_32BIT;
break;
default:
printk(KERN_WARNING "s6000-i2s: unsupported PCM format %x\n",
params_format(params));
return -EINVAL;
}
if (s6_i2s_read_reg(dev, S6_I2S_INTERFACE_CFG(interf))
& S6_I2S_IS_ENABLED) {
printk(KERN_ERR "s6000-i2s: interface already enabled\n");
return -EBUSY;
}
s6_i2s_mod_reg(dev, S6_I2S_INTERFACE_CFG(interf),
S6_I2S_CHANNELS_MASK|S6_I2S_MEM_MASK|S6_I2S_BITS_MASK,
w);
return 0;
}
static int s6000_i2s_dai_probe(struct platform_device *pdev,
struct snd_soc_dai *dai)
{
struct s6000_i2s_dev *dev = dai->private_data;
struct s6000_snd_platform_data *pdata = pdev->dev.platform_data;
if (!pdata)
return -EINVAL;
dev->wide = pdata->wide;
dev->channel_in = pdata->channel_in;
dev->channel_out = pdata->channel_out;
dev->lines_in = pdata->lines_in;
dev->lines_out = pdata->lines_out;
s6_i2s_write_reg(dev, S6_I2S_MODE,
dev->wide ? S6_I2S_WIDE : S6_I2S_DUAL);
if (dev->wide) {
int i;
if (dev->lines_in + dev->lines_out > S6_I2S_NUM_LINES)
return -EINVAL;
dev->channel_in = 0;
dev->channel_out = 1;
dai->capture.channels_min = 2 * dev->lines_in;
dai->capture.channels_max = dai->capture.channels_min;
dai->playback.channels_min = 2 * dev->lines_out;
dai->playback.channels_max = dai->playback.channels_min;
for (i = 0; i < dev->lines_out; i++)
s6_i2s_write_reg(dev, S6_I2S_DATA_CFG(i), S6_I2S_OUT);
for (; i < S6_I2S_NUM_LINES - dev->lines_in; i++)
s6_i2s_write_reg(dev, S6_I2S_DATA_CFG(i),
S6_I2S_UNUSED);
for (; i < S6_I2S_NUM_LINES; i++)
s6_i2s_write_reg(dev, S6_I2S_DATA_CFG(i), S6_I2S_IN);
} else {
unsigned int cfg[2] = {S6_I2S_UNUSED, S6_I2S_UNUSED};
if (dev->lines_in > 1 || dev->lines_out > 1)
return -EINVAL;
dai->capture.channels_min = 2 * dev->lines_in;
dai->capture.channels_max = 8 * dev->lines_in;
dai->playback.channels_min = 2 * dev->lines_out;
dai->playback.channels_max = 8 * dev->lines_out;
if (dev->lines_in)
cfg[dev->channel_in] = S6_I2S_IN;
if (dev->lines_out)
cfg[dev->channel_out] = S6_I2S_OUT;
s6_i2s_write_reg(dev, S6_I2S_DATA_CFG(0), cfg[0]);
s6_i2s_write_reg(dev, S6_I2S_DATA_CFG(1), cfg[1]);
}
if (dev->lines_out) {
if (dev->lines_in) {
if (!dev->dma_params.dma_out)
return -ENODEV;
} else {
dev->dma_params.dma_out = dev->dma_params.dma_in;
dev->dma_params.dma_in = 0;
}
}
dev->dma_params.sif_in = dev->sifbase + (dev->channel_in ?
S6_I2S_SIF_PORT1 : S6_I2S_SIF_PORT0);
dev->dma_params.sif_out = dev->sifbase + (dev->channel_out ?
S6_I2S_SIF_PORT1 : S6_I2S_SIF_PORT0);
dev->dma_params.same_rate = pdata->same_rate | pdata->wide;
return 0;
}
#define S6000_I2S_RATES (SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_5512 | \
SNDRV_PCM_RATE_8000_192000)
#define S6000_I2S_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S32_LE)
static struct snd_soc_dai_ops s6000_i2s_dai_ops = {
.set_fmt = s6000_i2s_set_dai_fmt,
.set_clkdiv = s6000_i2s_set_clkdiv,
.hw_params = s6000_i2s_hw_params,
};
struct snd_soc_dai s6000_i2s_dai = {
.name = "s6000-i2s",
.id = 0,
.probe = s6000_i2s_dai_probe,
.playback = {
.channels_min = 2,
.channels_max = 8,
.formats = S6000_I2S_FORMATS,
.rates = S6000_I2S_RATES,
.rate_min = 0,
.rate_max = 1562500,
},
.capture = {
.channels_min = 2,
.channels_max = 8,
.formats = S6000_I2S_FORMATS,
.rates = S6000_I2S_RATES,
.rate_min = 0,
.rate_max = 1562500,
},
.ops = &s6000_i2s_dai_ops,
}
EXPORT_SYMBOL_GPL(s6000_i2s_dai);
static int __devinit s6000_i2s_probe(struct platform_device *pdev)
{
struct s6000_i2s_dev *dev;
struct resource *scbmem, *sifmem, *region, *dma1, *dma2;
u8 __iomem *mmio;
int ret;
scbmem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!scbmem) {
dev_err(&pdev->dev, "no mem resource?\n");
ret = -ENODEV;
goto err_release_none;
}
region = request_mem_region(scbmem->start,
scbmem->end - scbmem->start + 1,
pdev->name);
if (!region) {
dev_err(&pdev->dev, "I2S SCB region already claimed\n");
ret = -EBUSY;
goto err_release_none;
}
mmio = ioremap(scbmem->start, scbmem->end - scbmem->start + 1);
if (!mmio) {
dev_err(&pdev->dev, "can't ioremap SCB region\n");
ret = -ENOMEM;
goto err_release_scb;
}
sifmem = platform_get_resource(pdev, IORESOURCE_MEM, 1);
if (!sifmem) {
dev_err(&pdev->dev, "no second mem resource?\n");
ret = -ENODEV;
goto err_release_map;
}
region = request_mem_region(sifmem->start,
sifmem->end - sifmem->start + 1,
pdev->name);
if (!region) {
dev_err(&pdev->dev, "I2S SIF region already claimed\n");
ret = -EBUSY;
goto err_release_map;
}
dma1 = platform_get_resource(pdev, IORESOURCE_DMA, 0);
if (!dma1) {
dev_err(&pdev->dev, "no dma resource?\n");
ret = -ENODEV;
goto err_release_sif;
}
region = request_mem_region(dma1->start, dma1->end - dma1->start + 1,
pdev->name);
if (!region) {
dev_err(&pdev->dev, "I2S DMA region already claimed\n");
ret = -EBUSY;
goto err_release_sif;
}
dma2 = platform_get_resource(pdev, IORESOURCE_DMA, 1);
if (dma2) {
region = request_mem_region(dma2->start,
dma2->end - dma2->start + 1,
pdev->name);
if (!region) {
dev_err(&pdev->dev,
"I2S DMA region already claimed\n");
ret = -EBUSY;
goto err_release_dma1;
}
}
dev = kzalloc(sizeof(struct s6000_i2s_dev), GFP_KERNEL);
if (!dev) {
ret = -ENOMEM;
goto err_release_dma2;
}
s6000_i2s_dai.dev = &pdev->dev;
s6000_i2s_dai.private_data = dev;
s6000_i2s_dai.dma_data = &dev->dma_params;
dev->sifbase = sifmem->start;
dev->scbbase = mmio;
s6_i2s_write_reg(dev, S6_I2S_INTERRUPT_ENABLE, 0);
s6_i2s_write_reg(dev, S6_I2S_INTERRUPT_CLEAR,
S6_I2S_INT_ALIGNMENT |
S6_I2S_INT_UNDERRUN |
S6_I2S_INT_OVERRUN);
s6000_i2s_stop_channel(dev, 0);
s6000_i2s_stop_channel(dev, 1);
s6000_i2s_wait_disabled(dev);
dev->dma_params.check_xrun = s6000_i2s_check_xrun;
dev->dma_params.trigger = s6000_i2s_trigger;
dev->dma_params.dma_in = dma1->start;
dev->dma_params.dma_out = dma2 ? dma2->start : 0;
dev->dma_params.irq = platform_get_irq(pdev, 0);
if (dev->dma_params.irq < 0) {
dev_err(&pdev->dev, "no irq resource?\n");
ret = -ENODEV;
goto err_release_dev;
}
s6_i2s_write_reg(dev, S6_I2S_INTERRUPT_ENABLE,
S6_I2S_INT_ALIGNMENT |
S6_I2S_INT_UNDERRUN |
S6_I2S_INT_OVERRUN);
ret = snd_soc_register_dai(&s6000_i2s_dai);
if (ret)
goto err_release_dev;
return 0;
err_release_dev:
kfree(dev);
err_release_dma2:
if (dma2)
release_mem_region(dma2->start, dma2->end - dma2->start + 1);
err_release_dma1:
release_mem_region(dma1->start, dma1->end - dma1->start + 1);
err_release_sif:
release_mem_region(sifmem->start, (sifmem->end - sifmem->start) + 1);
err_release_map:
iounmap(mmio);
err_release_scb:
release_mem_region(scbmem->start, (scbmem->end - scbmem->start) + 1);
err_release_none:
return ret;
}
static void __devexit s6000_i2s_remove(struct platform_device *pdev)
{
struct s6000_i2s_dev *dev = s6000_i2s_dai.private_data;
struct resource *region;
void __iomem *mmio = dev->scbbase;
snd_soc_unregister_dai(&s6000_i2s_dai);
s6000_i2s_stop_channel(dev, 0);
s6000_i2s_stop_channel(dev, 1);
s6_i2s_write_reg(dev, S6_I2S_INTERRUPT_ENABLE, 0);
s6000_i2s_dai.private_data = 0;
kfree(dev);
region = platform_get_resource(pdev, IORESOURCE_DMA, 0);
release_mem_region(region->start, region->end - region->start + 1);
region = platform_get_resource(pdev, IORESOURCE_DMA, 1);
if (region)
release_mem_region(region->start,
region->end - region->start + 1);
region = platform_get_resource(pdev, IORESOURCE_MEM, 0);
release_mem_region(region->start, (region->end - region->start) + 1);
iounmap(mmio);
region = platform_get_resource(pdev, IORESOURCE_IO, 0);
release_mem_region(region->start, (region->end - region->start) + 1);
}
static struct platform_driver s6000_i2s_driver = {
.probe = s6000_i2s_probe,
.remove = __devexit_p(s6000_i2s_remove),
.driver = {
.name = "s6000-i2s",
.owner = THIS_MODULE,
},
};
static int __init s6000_i2s_init(void)
{
return platform_driver_register(&s6000_i2s_driver);
}
module_init(s6000_i2s_init);
static void __exit s6000_i2s_exit(void)
{
platform_driver_unregister(&s6000_i2s_driver);
}
module_exit(s6000_i2s_exit);
MODULE_AUTHOR("Daniel Gloeckner");
MODULE_DESCRIPTION("Stretch s6000 family I2S SoC Interface");
MODULE_LICENSE("GPL");
|
163081.c | //------------------------------------------------------------------------------
// GB_AxB__lor_ne_uint8.c: matrix multiply for a single semiring
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated1/ or Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB_dev.h"
#ifndef GBCOMPACT
#include "GB.h"
#include "GB_control.h"
#include "GB_bracket.h"
#include "GB_sort.h"
#include "GB_atomics.h"
#include "GB_AxB_saxpy.h"
#if 1
#include "GB_AxB__include2.h"
#else
#include "GB_AxB__include1.h"
#endif
#include "GB_unused.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_ek_slice_search.c"
// This C=A*B semiring is defined by the following types and operators:
// A'*B (dot2): GB (_Adot2B__lor_ne_uint8)
// A'*B (dot3): GB (_Adot3B__lor_ne_uint8)
// C+=A'*B (dot4): GB (_Adot4B__lor_ne_uint8)
// A*B (saxpy bitmap): GB (_AsaxbitB__lor_ne_uint8)
// A*B (saxpy3): GB (_Asaxpy3B__lor_ne_uint8)
// no mask: GB (_Asaxpy3B_noM__lor_ne_uint8)
// mask M: GB (_Asaxpy3B_M__lor_ne_uint8)
// mask !M: GB (_Asaxpy3B_notM__lor_ne_uint8)
// A*B (saxpy4): GB (_Asaxpy4B__lor_ne_uint8)
// A*B (saxpy5): GB (_Asaxpy5B__lor_ne_uint8)
// C type: bool
// A type: uint8_t
// A pattern? 0
// B type: uint8_t
// B pattern? 0
// Multiply: z = (x != y)
// Add: cij |= t
// 'any' monoid? 0
// atomic? 1
// OpenMP atomic? 1
// identity: false
// terminal? 1
// terminal condition: if (cij == true) { break ; }
// MultAdd: z |= (x != y)
#define GB_ATYPE \
uint8_t
#define GB_BTYPE \
uint8_t
#define GB_CTYPE \
bool
#define GB_ASIZE \
sizeof (uint8_t)
#define GB_BSIZE \
sizeof (uint8_t)
#define GB_CSIZE \
sizeof (bool)
// # of bits in the type of C, for AVX2 and AVX512F
#define GB_CNBITS \
8
// true for int64, uint64, float, double, float complex, and double complex
#define GB_CTYPE_IGNORE_OVERFLOW \
0
// aik = Ax [pA]
#define GB_GETA(aik,Ax,pA,A_iso) \
uint8_t aik = GBX (Ax, pA, A_iso)
// true if values of A are not used
#define GB_A_IS_PATTERN \
0 \
// bkj = Bx [pB]
#define GB_GETB(bkj,Bx,pB,B_iso) \
uint8_t bkj = GBX (Bx, pB, B_iso)
// true if values of B are not used
#define GB_B_IS_PATTERN \
0 \
// Gx [pG] = Ax [pA]
#define GB_LOADA(Gx,pG,Ax,pA,A_iso) \
Gx [pG] = GBX (Ax, pA, A_iso)
// Gx [pG] = Bx [pB]
#define GB_LOADB(Gx,pG,Bx,pB,B_iso) \
Gx [pG] = GBX (Bx, pB, B_iso)
#define GB_CX(p) \
Cx [p]
// multiply operator
#define GB_MULT(z, x, y, i, k, j) \
z = (x != y)
// cast from a real scalar (or 2, if C is complex) to the type of C
#define GB_CTYPE_CAST(x,y) \
((bool) x)
// cast from a real scalar (or 2, if A is complex) to the type of A
#define GB_ATYPE_CAST(x,y) \
((uint8_t) x)
// multiply-add
#define GB_MULTADD(z, x, y, i, k, j) \
z |= (x != y)
// monoid identity value
#define GB_IDENTITY \
false
// 1 if the identity value can be assigned via memset, with all bytes the same
#define GB_HAS_IDENTITY_BYTE \
1
// identity byte, for memset
#define GB_IDENTITY_BYTE \
0
// true if the monoid has a terminal value
#define GB_MONOID_IS_TERMINAL \
1
// break if cij reaches the terminal value (dot product only)
#define GB_DOT_TERMINAL(cij) \
if (cij == true) { break ; }
// simd pragma for dot-product loop vectorization
#define GB_PRAGMA_SIMD_DOT(cij) \
;
// simd pragma for other loop vectorization
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// 1 for the PLUS_PAIR_(real) semirings, not for the complex case
#define GB_IS_PLUS_PAIR_REAL_SEMIRING \
0
// 1 if the semiring is accelerated with AVX2 or AVX512f
#define GB_SEMIRING_HAS_AVX_IMPLEMENTATION \
0
// declare the cij scalar (initialize cij to zero for PLUS_PAIR)
#define GB_CIJ_DECLARE(cij) \
bool cij
// Cx [pC] = cij
#define GB_PUTC(cij,p) \
Cx [p] = cij
// Cx [p] = t
#define GB_CIJ_WRITE(p,t) \
Cx [p] = t
// C(i,j) += t
#define GB_CIJ_UPDATE(p,t) \
Cx [p] |= t
// x + y
#define GB_ADD_FUNCTION(x,y) \
x | y
// bit pattern for bool, 8-bit, 16-bit, and 32-bit integers
#define GB_CTYPE_BITS \
0x1L
// 1 if monoid update can skipped entirely (the ANY monoid)
#define GB_IS_ANY_MONOID \
0
// 1 if monoid update is EQ
#define GB_IS_EQ_MONOID \
0
// 1 if monoid update can be done atomically, 0 otherwise
#define GB_HAS_ATOMIC \
1
// 1 if monoid update can be done with an OpenMP atomic update, 0 otherwise
#if GB_COMPILER_MSC
/* MS Visual Studio only has OpenMP 2.0, with fewer atomics */
#define GB_HAS_OMP_ATOMIC \
0
#else
#define GB_HAS_OMP_ATOMIC \
1
#endif
// 1 for the ANY_PAIR_ISO semiring
#define GB_IS_ANY_PAIR_SEMIRING \
0
// 1 if PAIR is the multiply operator
#define GB_IS_PAIR_MULTIPLIER \
0
// 1 if monoid is PLUS_FC32
#define GB_IS_PLUS_FC32_MONOID \
0
// 1 if monoid is PLUS_FC64
#define GB_IS_PLUS_FC64_MONOID \
0
// 1 if monoid is ANY_FC32
#define GB_IS_ANY_FC32_MONOID \
0
// 1 if monoid is ANY_FC64
#define GB_IS_ANY_FC64_MONOID \
0
// 1 if monoid is MIN for signed or unsigned integers
#define GB_IS_IMIN_MONOID \
0
// 1 if monoid is MAX for signed or unsigned integers
#define GB_IS_IMAX_MONOID \
0
// 1 if monoid is MIN for float or double
#define GB_IS_FMIN_MONOID \
0
// 1 if monoid is MAX for float or double
#define GB_IS_FMAX_MONOID \
0
// 1 for the FIRSTI or FIRSTI1 multiply operator
#define GB_IS_FIRSTI_MULTIPLIER \
0
// 1 for the FIRSTJ or FIRSTJ1 multiply operator
#define GB_IS_FIRSTJ_MULTIPLIER \
0
// 1 for the SECONDJ or SECONDJ1 multiply operator
#define GB_IS_SECONDJ_MULTIPLIER \
0
// 1 for the FIRSTI1, FIRSTJ1, SECONDI1, or SECONDJ1 multiply operators
#define GB_OFFSET \
0
// atomic compare-exchange
#define GB_ATOMIC_COMPARE_EXCHANGE(target, expected, desired) \
GB_ATOMIC_COMPARE_EXCHANGE_8 (target, expected, desired)
// Hx [i] = t
#define GB_HX_WRITE(i,t) \
Hx [i] = t
// Cx [p] = Hx [i]
#define GB_CIJ_GATHER(p,i) \
Cx [p] = Hx [i]
// Cx [p] += Hx [i]
#define GB_CIJ_GATHER_UPDATE(p,i) \
Cx [p] |= Hx [i]
// Hx [i] += t
#define GB_HX_UPDATE(i,t) \
Hx [i] |= t
// memcpy (&(Cx [p]), &(Hx [i]), len)
#define GB_CIJ_MEMCPY(p,i,len) \
memcpy (Cx +(p), Hx +(i), (len) * sizeof(bool));
// disable this semiring and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_LOR || GxB_NO_NE || GxB_NO_UINT8 || GxB_NO_LOR_BOOL || GxB_NO_NE_UINT8 || GxB_NO_LOR_NE_UINT8)
//------------------------------------------------------------------------------
// GB_Adot2B: C=A'*B, C<M>=A'*B, or C<!M>=A'*B: dot product method, C is bitmap
//------------------------------------------------------------------------------
// if A_not_transposed is true, then C=A*B is computed where A is bitmap or full
GrB_Info GB (_Adot2B__lor_ne_uint8)
(
GrB_Matrix C,
const GrB_Matrix M, const bool Mask_comp, const bool Mask_struct,
const bool A_not_transposed,
const GrB_Matrix A, int64_t *restrict A_slice,
const GrB_Matrix B, int64_t *restrict B_slice,
int nthreads, int naslice, int nbslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_AxB_dot2_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// GB_Adot3B: C<M>=A'*B: masked dot product, C is sparse or hyper
//------------------------------------------------------------------------------
GrB_Info GB (_Adot3B__lor_ne_uint8)
(
GrB_Matrix C,
const GrB_Matrix M, const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const GB_task_struct *restrict TaskList,
const int ntasks,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_AxB_dot3_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// GB_Adot4B: C+=A'*B: dense dot product (not used for ANY_PAIR_ISO)
//------------------------------------------------------------------------------
#if 1
GrB_Info GB (_Adot4B__lor_ne_uint8)
(
GrB_Matrix C,
const GrB_Matrix A, int64_t *restrict A_slice, int naslice,
const GrB_Matrix B, int64_t *restrict B_slice, int nbslice,
const int nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_AxB_dot4_meta.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// GB_AsaxbitB: C=A*B, C<M>=A*B, C<!M>=A*B: saxpy method, C is bitmap/full
//------------------------------------------------------------------------------
#include "GB_AxB_saxpy3_template.h"
GrB_Info GB (_AsaxbitB__lor_ne_uint8)
(
GrB_Matrix C, // bitmap or full
const GrB_Matrix M, const bool Mask_comp, const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_AxB_saxpy_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// GB_Asaxpy4B: C += A*B when C is full
//------------------------------------------------------------------------------
#if 1
GrB_Info GB (_Asaxpy4B__lor_ne_uint8)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int ntasks,
const int nthreads,
const int nfine_tasks_per_vector,
const bool use_coarse_tasks,
const bool use_atomics,
const int64_t *A_slice,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_AxB_saxpy4_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// GB_Asaxpy5B: C += A*B when C is full, A is bitmap/full, B is sparse/hyper
//------------------------------------------------------------------------------
#if 1
#if GB_DISABLE
#elif ( !GB_A_IS_PATTERN )
//----------------------------------------------------------------------
// saxpy5 method with vectors of length 8 for double, 16 for single
//----------------------------------------------------------------------
// AVX512F: vector registers are 512 bits, or 64 bytes, which can hold
// 16 floats or 8 doubles.
#define GB_V16_512 (16 * GB_CNBITS <= 512)
#define GB_V8_512 ( 8 * GB_CNBITS <= 512)
#define GB_V4_512 ( 4 * GB_CNBITS <= 512)
#define GB_V16 GB_V16_512
#define GB_V8 GB_V8_512
#define GB_V4 GB_V4_512
#if GB_SEMIRING_HAS_AVX_IMPLEMENTATION && GB_COMPILER_SUPPORTS_AVX512F \
&& GB_V4_512
GB_TARGET_AVX512F static inline void GB_AxB_saxpy5_unrolled_avx512f
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int ntasks,
const int nthreads,
const int64_t *B_slice,
GB_Context Context
)
{
#include "GB_AxB_saxpy5_unrolled.c"
}
#endif
//----------------------------------------------------------------------
// saxpy5 method with vectors of length 4 for double, 8 for single
//----------------------------------------------------------------------
// AVX2: vector registers are 256 bits, or 32 bytes, which can hold
// 8 floats or 4 doubles.
#define GB_V16_256 (16 * GB_CNBITS <= 256)
#define GB_V8_256 ( 8 * GB_CNBITS <= 256)
#define GB_V4_256 ( 4 * GB_CNBITS <= 256)
#undef GB_V16
#undef GB_V8
#undef GB_V4
#define GB_V16 GB_V16_256
#define GB_V8 GB_V8_256
#define GB_V4 GB_V4_256
#if GB_SEMIRING_HAS_AVX_IMPLEMENTATION && GB_COMPILER_SUPPORTS_AVX2 \
&& GB_V4_256
GB_TARGET_AVX2 static inline void GB_AxB_saxpy5_unrolled_avx2
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int ntasks,
const int nthreads,
const int64_t *B_slice,
GB_Context Context
)
{
#include "GB_AxB_saxpy5_unrolled.c"
}
#endif
//----------------------------------------------------------------------
// saxpy5 method unrolled, with no vectors
//----------------------------------------------------------------------
#undef GB_V16
#undef GB_V8
#undef GB_V4
#define GB_V16 0
#define GB_V8 0
#define GB_V4 0
static inline void GB_AxB_saxpy5_unrolled_vanilla
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int ntasks,
const int nthreads,
const int64_t *B_slice,
GB_Context Context
)
{
#include "GB_AxB_saxpy5_unrolled.c"
}
#endif
GrB_Info GB (_Asaxpy5B__lor_ne_uint8)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int ntasks,
const int nthreads,
const int64_t *B_slice,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_AxB_saxpy5_meta.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// GB_Asaxpy3B: C=A*B, C<M>=A*B, C<!M>=A*B: saxpy method (Gustavson + Hash)
//------------------------------------------------------------------------------
GrB_Info GB (_Asaxpy3B__lor_ne_uint8)
(
GrB_Matrix C, // C<any M>=A*B, C sparse or hypersparse
const GrB_Matrix M, const bool Mask_comp, const bool Mask_struct,
const bool M_in_place,
const GrB_Matrix A,
const GrB_Matrix B,
GB_saxpy3task_struct *restrict SaxpyTasks,
const int ntasks, const int nfine, const int nthreads, const int do_sort,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
ASSERT (GB_IS_SPARSE (C) || GB_IS_HYPERSPARSE (C)) ;
if (M == NULL)
{
// C = A*B, no mask
return (GB (_Asaxpy3B_noM__lor_ne_uint8) (C, A, B,
SaxpyTasks, ntasks, nfine, nthreads, do_sort, Context)) ;
}
else if (!Mask_comp)
{
// C<M> = A*B
return (GB (_Asaxpy3B_M__lor_ne_uint8) (C,
M, Mask_struct, M_in_place, A, B,
SaxpyTasks, ntasks, nfine, nthreads, do_sort, Context)) ;
}
else
{
// C<!M> = A*B
return (GB (_Asaxpy3B_notM__lor_ne_uint8) (C,
M, Mask_struct, M_in_place, A, B,
SaxpyTasks, ntasks, nfine, nthreads, do_sort, Context)) ;
}
#endif
}
//------------------------------------------------------------------------------
// GB_Asaxpy3B_M: C<M>=A*Bi: saxpy method (Gustavson + Hash)
//------------------------------------------------------------------------------
#if ( !GB_DISABLE )
GrB_Info GB (_Asaxpy3B_M__lor_ne_uint8)
(
GrB_Matrix C, // C<M>=A*B, C sparse or hypersparse
const GrB_Matrix M, const bool Mask_struct,
const bool M_in_place,
const GrB_Matrix A,
const GrB_Matrix B,
GB_saxpy3task_struct *restrict SaxpyTasks,
const int ntasks, const int nfine, const int nthreads,
const int do_sort,
GB_Context Context
)
{
if (GB_IS_SPARSE (A) && GB_IS_SPARSE (B))
{
// both A and B are sparse
#define GB_META16
#define GB_NO_MASK 0
#define GB_MASK_COMP 0
#define GB_A_IS_SPARSE 1
#define GB_A_IS_HYPER 0
#define GB_A_IS_BITMAP 0
#define GB_A_IS_FULL 0
#define GB_B_IS_SPARSE 1
#define GB_B_IS_HYPER 0
#define GB_B_IS_BITMAP 0
#define GB_B_IS_FULL 0
#include "GB_meta16_definitions.h"
#include "GB_AxB_saxpy3_template.c"
}
else
{
// general case
#undef GB_META16
#define GB_NO_MASK 0
#define GB_MASK_COMP 0
#include "GB_meta16_definitions.h"
#include "GB_AxB_saxpy3_template.c"
}
return (GrB_SUCCESS) ;
}
#endif
//------------------------------------------------------------------------------
//GB_Asaxpy3B_noM: C=A*B: saxpy method (Gustavson + Hash)
//------------------------------------------------------------------------------
#if ( !GB_DISABLE )
GrB_Info GB (_Asaxpy3B_noM__lor_ne_uint8)
(
GrB_Matrix C, // C=A*B, C sparse or hypersparse
const GrB_Matrix A,
const GrB_Matrix B,
GB_saxpy3task_struct *restrict SaxpyTasks,
const int ntasks, const int nfine, const int nthreads,
const int do_sort,
GB_Context Context
)
{
if (GB_IS_SPARSE (A) && GB_IS_SPARSE (B))
{
// both A and B are sparse
#define GB_META16
#define GB_NO_MASK 1
#define GB_MASK_COMP 0
#define GB_A_IS_SPARSE 1
#define GB_A_IS_HYPER 0
#define GB_A_IS_BITMAP 0
#define GB_A_IS_FULL 0
#define GB_B_IS_SPARSE 1
#define GB_B_IS_HYPER 0
#define GB_B_IS_BITMAP 0
#define GB_B_IS_FULL 0
#include "GB_meta16_definitions.h"
#include "GB_AxB_saxpy3_template.c"
}
else
{
// general case
#undef GB_META16
#define GB_NO_MASK 1
#define GB_MASK_COMP 0
#include "GB_meta16_definitions.h"
#include "GB_AxB_saxpy3_template.c"
}
return (GrB_SUCCESS) ;
}
#endif
//------------------------------------------------------------------------------
//GB_Asaxpy3B_notM: C<!M>=A*B: saxpy method (Gustavson + Hash)
//------------------------------------------------------------------------------
#if ( !GB_DISABLE )
GrB_Info GB (_Asaxpy3B_notM__lor_ne_uint8)
(
GrB_Matrix C, // C<!M>=A*B, C sparse or hypersparse
const GrB_Matrix M, const bool Mask_struct,
const bool M_in_place,
const GrB_Matrix A,
const GrB_Matrix B,
GB_saxpy3task_struct *restrict SaxpyTasks,
const int ntasks, const int nfine, const int nthreads,
const int do_sort,
GB_Context Context
)
{
if (GB_IS_SPARSE (A) && GB_IS_SPARSE (B))
{
// both A and B are sparse
#define GB_META16
#define GB_NO_MASK 0
#define GB_MASK_COMP 1
#define GB_A_IS_SPARSE 1
#define GB_A_IS_HYPER 0
#define GB_A_IS_BITMAP 0
#define GB_A_IS_FULL 0
#define GB_B_IS_SPARSE 1
#define GB_B_IS_HYPER 0
#define GB_B_IS_BITMAP 0
#define GB_B_IS_FULL 0
#include "GB_meta16_definitions.h"
#include "GB_AxB_saxpy3_template.c"
}
else
{
// general case
#undef GB_META16
#define GB_NO_MASK 0
#define GB_MASK_COMP 1
#include "GB_meta16_definitions.h"
#include "GB_AxB_saxpy3_template.c"
}
return (GrB_SUCCESS) ;
}
#endif
#endif
|
109790.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "mpi.h"
#define STARTUP_TIME_ITERATIONS 10
int NUM_MESSAGES = 6;
int MESSAGE_LENGTHS[] = {1000, 10000, 100000, 1000000, 10000000, 100000000};
int main(int argc, char** argv)
{
// Initialize the MPI library
MPI_Init(&argc, &argv);
MPI_Status status;
int rank, size, sender = 0, receiver = 1, tag = 99;
// Get current process ID and total number of processes
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
// Verify the number of processes
if (size != 2)
{
printf("Error: Program limited to only 2 tasks!\n");
MPI_Finalize();
exit (-1);
}
int i, j;
char received = 'r';
// Log file
MPI_File fh;
MPI_File_open(MPI_COMM_WORLD, "results.out", MPI_MODE_CREATE|MPI_MODE_WRONLY, MPI_INFO_NULL, &fh);
// If process 0
if (rank == 0)
{
// Warmup
MPI_Send(&received, 0, MPI_CHAR, receiver, tag, MPI_COMM_WORLD);
// Compute startup time
double avgStartupTime = 0.0;
for(i = 0; i < STARTUP_TIME_ITERATIONS; i++)
{
double startupTime = MPI_Wtime();
MPI_Send(&received, 0, MPI_CHAR, receiver, tag, MPI_COMM_WORLD);
MPI_Recv(&received, 0, MPI_CHAR, receiver, tag, MPI_COMM_WORLD, &status);
startupTime = (MPI_Wtime() - startupTime) / 2.0;
avgStartupTime += startupTime;
}
avgStartupTime /= STARTUP_TIME_ITERATIONS;
printf("Startup time: %f\n", avgStartupTime);
for (i = 0; i < NUM_MESSAGES; i++)
{
printf("Sending a message of size: %d\n", MESSAGE_LENGTHS[i]);
char* text = malloc(sizeof(char) * MESSAGE_LENGTHS[i]);
for (j = 0; j < MESSAGE_LENGTHS[i] - 1; j++)
text[j] = 'a';
text[j] = '\0';
double startTime = MPI_Wtime(); // Log the start time
MPI_Send(text, MESSAGE_LENGTHS[i], MPI_CHAR, receiver, tag, MPI_COMM_WORLD);
MPI_Recv(&received, 0, MPI_CHAR, receiver, tag, MPI_COMM_WORLD, &status);
double endTime = MPI_Wtime(); // Log the end time
double elapsedTime = endTime - startTime;
if (elapsedTime - avgStartupTime < 0.0)
{
printf("Error: Elapsed time is less than startup time!");
MPI_File_close(&fh);
MPI_Finalize();
exit(-1);
}
// Print the status
printf("Start time: %f | End time: %f | Elapsed time: %f | Actual elapsed time: %f\n", startTime, endTime, elapsedTime, elapsedTime - avgStartupTime);
char textBuffer[200];
snprintf(textBuffer, 200, "%d,%f,%f,%f,%f\n", MESSAGE_LENGTHS[i], startTime, endTime, avgStartupTime, elapsedTime);
MPI_File_write(fh, textBuffer, strlen(textBuffer), MPI_CHAR, MPI_STATUS_IGNORE);
// Free memory
free(text);
}
}
// If process 1
else
{
// Warmup
MPI_Recv(&received, 0, MPI_CHAR, sender, tag, MPI_COMM_WORLD, &status);
// Compute startup time
for(i = 0; i < STARTUP_TIME_ITERATIONS; i++)
{
MPI_Recv(&received, 0, MPI_CHAR, sender, tag, MPI_COMM_WORLD, &status);
MPI_Send(&received, 0, MPI_CHAR, sender, tag, MPI_COMM_WORLD);
}
for (i = 0; i < NUM_MESSAGES; i++)
{
char* buffer = malloc(sizeof(char) * MESSAGE_LENGTHS[i]);
double startTime = MPI_Wtime(); // Log the start time
MPI_Recv(buffer, MESSAGE_LENGTHS[i], MPI_CHAR, sender, tag, MPI_COMM_WORLD, &status);
MPI_Send(&received, 0, MPI_CHAR, sender, tag, MPI_COMM_WORLD);
printf("Process %d received text: %c of length: %d\n", rank, buffer[0], MESSAGE_LENGTHS[i]);
// Free memory
free(buffer);
}
}
//fprintf(outputFile, "%d, %f, %f, %f\n", MESSAGE_LENGTHS[i], startTime, endTime, endTime - startTime);
// Kill all deamons
MPI_File_close(&fh);
MPI_Finalize();
//fclose(outputFile);
}
|
181894.c | /*
* Copyright (C) Huawei Technologies Co., Ltd. 2019. ALL RIGHTS RESERVED.
* See file LICENSE for terms.
*/
#include "../builtin.h"
#include "builtin_plan.h"
#include <string.h>
#include <ucs/debug/log.h>
#include <ucs/debug/memtrack.h>
#include <uct/api/uct_def.h>
#define INDEX_DOUBLE 2
void ucg_builtin_ring_assign_recv_thresh(ucg_builtin_plan_phase_t *phase)
{
phase->recv_thresh.max_short_one = phase->send_thresh.max_short_one;
phase->recv_thresh.max_short_max = phase->send_thresh.max_short_max;
phase->recv_thresh.max_bcopy_one = phase->send_thresh.max_bcopy_one;
phase->recv_thresh.max_bcopy_max = phase->send_thresh.max_bcopy_max;
phase->recv_thresh.max_zcopy_one = phase->send_thresh.max_zcopy_one;
if (phase->md_attr != NULL) {
phase->recv_thresh.md_attr_cap_max_reg = (phase->md_attr->cap.flags & UCT_MD_FLAG_NEED_MEMH) ? phase->md_attr->cap.max_reg : 0;
}
}
ucs_status_t ucg_builtin_ring_connect(ucg_builtin_planner_ctx_t *ctx,
ucg_builtin_plan_phase_t *phase,
ucg_step_idx_ext_t step_idx,
ucg_group_member_index_t peer_index_src,
ucg_group_member_index_t peer_index_dst,
ucg_builtin_plan_t *ring)
{
ucs_status_t status;
uct_ep_h *next_ep = (uct_ep_h*)(phase + step_idx);
if (peer_index_src != peer_index_dst) {
phase->ep_cnt = 1; /* 1 sender and 1 receiver ,the phase->ep_cnt is the number of receiver */
unsigned phase_ep_index = 1; /* index: 0 for sender and 1 for receiver */
phase->multi_eps = next_ep++;
/* connected to src process for second EP, recv */
status = ucg_builtin_connect(ctx, peer_index_src, phase, phase_ep_index);
if (status != UCS_OK) {
return status;
}
phase_ep_index--;
next_ep++;
/* set threshold for receiver
* for ring threshold for receiver and sender maybe not same!!!
*/
ucg_builtin_ring_assign_recv_thresh(phase);
/* connected to dst process for first EP, send */
status = ucg_builtin_connect(ctx, peer_index_dst, phase, phase_ep_index);
if (status != UCS_OK) {
return status;
}
/*
* while phase->ep_cnt is set to be 1. So phase->single_ep should
* point to multi_eps[0].
*/
phase->single_ep = phase->multi_eps[0];
} else {
phase->ep_cnt = 1;
ring->ep_cnt -= 1;
phase->multi_eps = next_ep++;
status = ucg_builtin_connect(ctx, peer_index_src, phase, UCG_BUILTIN_CONNECT_SINGLE_EP);
if (status != UCS_OK) {
return status;
}
/* set threshold for receiver
* for ring threshold for receiver and sender maybe not same!!!
*/
ucg_builtin_ring_assign_recv_thresh(phase);
}
return status;
}
void ucg_builtin_ring_find_my_index(const ucg_group_params_t *group_params, unsigned proc_count, ucg_group_member_index_t *my_index)
{
while ((*my_index < proc_count) &&
(group_params->distance[*my_index] !=
UCG_GROUP_MEMBER_DISTANCE_SELF)) {
(*my_index)++;
}
ucs_assert(*my_index != proc_count);
}
ucs_status_t ucg_builtin_ring_create(ucg_builtin_planner_ctx_t *ctx,
enum ucg_builtin_plan_topology_type plan_topo_type,
const ucg_builtin_config_t *config,
const ucg_group_params_t *group_params,
const ucg_collective_type_t *coll_type,
ucg_builtin_plan_t **plan_p)
{
/* only phase0 need to call builtin_connect */
ucg_builtin_plan_phase_t phase_zero;
/* the number of ring steps is proc_count-1,and the step_size is always 1 */
unsigned proc_count = group_params->member_count;
/* the step number of reduce is proc_count-1, and the step number of allgather is proc_count-1 */
ucg_step_idx_ext_t step_idx = INDEX_DOUBLE * (proc_count - 1);
/* Allocate memory resources */
/* when proc_count >2, the number of endpoints is 2, and when proc_count = 2, the number of endpoints is 1. */
size_t alloc_size = sizeof(ucg_builtin_plan_t) +
(step_idx * sizeof(ucg_builtin_plan_phase_t)
+ (INDEX_DOUBLE * step_idx * sizeof(uct_ep_h)));
ucg_builtin_plan_t *ring = (ucg_builtin_plan_t*)UCG_ALLOC_CHECK(alloc_size, "ring topology");
memset(ring, 0, alloc_size);
ucg_builtin_plan_phase_t *phase = &ring->phss[0];
ring->ep_cnt = step_idx * INDEX_DOUBLE; /* the number of endpoints each step is always 2 for ring */
ring->phs_cnt = step_idx;
/* Find my own index */
ucg_group_member_index_t my_index = 0;
ucg_builtin_ring_find_my_index(group_params, proc_count, &my_index);
ucs_status_t status;
/* builtin phase 0 */
phase->method = UCG_PLAN_METHOD_REDUCE_SCATTER_RING;
phase->step_index = 0;
/* In each step, there are two peers */
ucg_group_member_index_t peer_index_src;
ucg_group_member_index_t peer_index_dst; /* src: source, dst: destination */
peer_index_src = (my_index - 1 + proc_count) % proc_count;
peer_index_dst = (my_index + 1) % proc_count;
#if ENABLE_DEBUG_DATA
phase->indexes = UCG_ALLOC_CHECK((peer_index_src == peer_index_dst ? 1 : INDEX_DOUBLE) * sizeof(my_index),
"ring indexes");
#endif
ucs_info("%lu's peer #%u(source) and #%u(destination) at (step #%u/%u)", my_index, (unsigned)peer_index_src,
(unsigned)peer_index_dst, (unsigned)step_idx + 1, ring->phs_cnt);
status = ucg_builtin_ring_connect(ctx, phase, step_idx, peer_index_src, peer_index_dst, ring);
if (status != UCS_OK) {
ucs_free(ring);
ring = NULL;
ucs_error("Error in ring create: %d", (int)status);
return status;
}
phase_zero = *phase;
phase++;
for (step_idx = 1; step_idx < ring->phs_cnt; step_idx++, phase++) {
/* the following endpoint is as same as phase(0) */
*phase = phase_zero;
phase->ucp_eps = NULL;
/* modify method and step_index in phase */
if (step_idx < proc_count - 1) {
phase->method = UCG_PLAN_METHOD_REDUCE_SCATTER_RING;
} else {
phase->method = UCG_PLAN_METHOD_ALLGATHER_RING;
}
phase->step_index = step_idx;
ucs_info("%lu's peer #%u(source) and #%u(destination) at (step #%u/%u)", my_index, (unsigned)peer_index_src,
(unsigned)peer_index_dst, (unsigned)(phase->step_index) + 1, ring->phs_cnt);
}
ring->super.my_index = my_index;
ring->feature |= UCG_ALGORITHM_SUPPORT_NON_COMMUTATIVE_OPS |
UCG_ALGORITHM_SUPPORT_LARGE_DATATYPE;
*plan_p = ring;
return status;
} |
915739.c | // Authors: Korbinian Schneeberger and Joerg Hagmann
// Copyright (C) 2008 by Max-Planck Institute for Developmental Biology, Tuebingen, Germany
#include "pmindex.h"
void printindex()
{
int i;
BIN* bin;
printf("------%c--%c----\n",CHR_SEQ[CHR_LENGTH-2], CHR_SEQ[CHR_LENGTH-1]);
for (i=0; i!=INDEX_SIZE; ++i) {
if (*(INDEX+i) != NULL) {
bin = *(INDEX+i);
//printf("%i: %i %i\n", i, bin->positions[0].chr, bin->positions[0].pos);
}
}
printf("------------\n");
}
|
480341.c | #include <std.h>
#include "/d/guilds/pack/short.h"
inherit ROOM;
void create() {
::create();
set_terrain(HEAVY_FOREST);
set_travel(FOOT_PATH);
set_property("light", 0);
set_property("indoors", 0);
set_property("no teleport", 1);
set_short("%^BOLD%^%^BLACK%^Shoikan Grove%^RESET%^");
set_long(
@SEETH
%^BOLD%^%^BLACK%^You are following a path in the grove.%^RESET%^
%^BLUE%^The grove is very dark as if a large shadow has descended upon the area. The shadows surround it by day and night because of the huge oak trees. There seems to be many different paths you can take. Each direction seems the same, you think that you can get lost in here easily.
SEETH
);
set_items( ([
]) );
set_exits( ([
"south" : GROVE "g4.c",
"north" : GROVE "g17.c",
"east" : GROVE "g20.c",
"west" : GROVE "g3.c",
]) );
}
|
766924.c | /* -*- Mode: C; c-basic-offset:4 ; -*- */
/*
* (C) 2001 by Argonne National Laboratory.
* See COPYRIGHT in top-level directory.
*
* This file is automatically generated by buildiface
* DO NOT EDIT
*/
#include "mpi_fortimpl.h"
/* Begin MPI profiling block */
#if defined(USE_WEAK_SYMBOLS) && !defined(USE_ONLY_MPI_NAMES)
#if defined(HAVE_MULTIPLE_PRAGMA_WEAK)
extern FORT_DLL_SPEC void FORT_CALL MPIX_COMM_AGREE( MPI_Fint *, MPI_Fint *, MPI_Fint * );
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree__( MPI_Fint *, MPI_Fint *, MPI_Fint * );
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree( MPI_Fint *, MPI_Fint *, MPI_Fint * );
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree_( MPI_Fint *, MPI_Fint *, MPI_Fint * );
#if defined(F77_NAME_UPPER)
#pragma weak MPIX_COMM_AGREE = PMPIX_COMM_AGREE
#pragma weak mpix_comm_agree__ = PMPIX_COMM_AGREE
#pragma weak mpix_comm_agree_ = PMPIX_COMM_AGREE
#pragma weak mpix_comm_agree = PMPIX_COMM_AGREE
#elif defined(F77_NAME_LOWER_2USCORE)
#pragma weak MPIX_COMM_AGREE = pmpix_comm_agree__
#pragma weak mpix_comm_agree__ = pmpix_comm_agree__
#pragma weak mpix_comm_agree_ = pmpix_comm_agree__
#pragma weak mpix_comm_agree = pmpix_comm_agree__
#elif defined(F77_NAME_LOWER_USCORE)
#pragma weak MPIX_COMM_AGREE = pmpix_comm_agree_
#pragma weak mpix_comm_agree__ = pmpix_comm_agree_
#pragma weak mpix_comm_agree_ = pmpix_comm_agree_
#pragma weak mpix_comm_agree = pmpix_comm_agree_
#else
#pragma weak MPIX_COMM_AGREE = pmpix_comm_agree
#pragma weak mpix_comm_agree__ = pmpix_comm_agree
#pragma weak mpix_comm_agree_ = pmpix_comm_agree
#pragma weak mpix_comm_agree = pmpix_comm_agree
#endif
#elif defined(HAVE_PRAGMA_WEAK)
#if defined(F77_NAME_UPPER)
extern FORT_DLL_SPEC void FORT_CALL MPIX_COMM_AGREE( MPI_Fint *, MPI_Fint *, MPI_Fint * );
#pragma weak MPIX_COMM_AGREE = PMPIX_COMM_AGREE
#elif defined(F77_NAME_LOWER_2USCORE)
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree__( MPI_Fint *, MPI_Fint *, MPI_Fint * );
#pragma weak mpix_comm_agree__ = pmpix_comm_agree__
#elif !defined(F77_NAME_LOWER_USCORE)
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree( MPI_Fint *, MPI_Fint *, MPI_Fint * );
#pragma weak mpix_comm_agree = pmpix_comm_agree
#else
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree_( MPI_Fint *, MPI_Fint *, MPI_Fint * );
#pragma weak mpix_comm_agree_ = pmpix_comm_agree_
#endif
#elif defined(HAVE_PRAGMA_HP_SEC_DEF)
#if defined(F77_NAME_UPPER)
#pragma _HP_SECONDARY_DEF PMPIX_COMM_AGREE MPIX_COMM_AGREE
#elif defined(F77_NAME_LOWER_2USCORE)
#pragma _HP_SECONDARY_DEF pmpix_comm_agree__ mpix_comm_agree__
#elif !defined(F77_NAME_LOWER_USCORE)
#pragma _HP_SECONDARY_DEF pmpix_comm_agree mpix_comm_agree
#else
#pragma _HP_SECONDARY_DEF pmpix_comm_agree_ mpix_comm_agree_
#endif
#elif defined(HAVE_PRAGMA_CRI_DUP)
#if defined(F77_NAME_UPPER)
#pragma _CRI duplicate MPIX_COMM_AGREE as PMPIX_COMM_AGREE
#elif defined(F77_NAME_LOWER_2USCORE)
#pragma _CRI duplicate mpix_comm_agree__ as pmpix_comm_agree__
#elif !defined(F77_NAME_LOWER_USCORE)
#pragma _CRI duplicate mpix_comm_agree as pmpix_comm_agree
#else
#pragma _CRI duplicate mpix_comm_agree_ as pmpix_comm_agree_
#endif
#elif defined(HAVE_WEAK_ATTRIBUTE)
#if defined(F77_NAME_UPPER)
extern FORT_DLL_SPEC void FORT_CALL MPIX_COMM_AGREE( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("PMPIX_COMM_AGREE")));
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree__( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("PMPIX_COMM_AGREE")));
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree_( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("PMPIX_COMM_AGREE")));
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("PMPIX_COMM_AGREE")));
#elif defined(F77_NAME_LOWER_2USCORE)
extern FORT_DLL_SPEC void FORT_CALL MPIX_COMM_AGREE( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("pmpix_comm_agree__")));
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree__( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("pmpix_comm_agree__")));
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree_( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("pmpix_comm_agree__")));
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("pmpix_comm_agree__")));
#elif defined(F77_NAME_LOWER_USCORE)
extern FORT_DLL_SPEC void FORT_CALL MPIX_COMM_AGREE( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("pmpix_comm_agree_")));
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree__( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("pmpix_comm_agree_")));
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree_( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("pmpix_comm_agree_")));
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("pmpix_comm_agree_")));
#else
extern FORT_DLL_SPEC void FORT_CALL MPIX_COMM_AGREE( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("pmpix_comm_agree")));
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree__( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("pmpix_comm_agree")));
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree_( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("pmpix_comm_agree")));
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("pmpix_comm_agree")));
#endif
#endif /* HAVE_PRAGMA_WEAK */
#endif /* USE_WEAK_SYMBOLS */
/* End MPI profiling block */
/* These definitions are used only for generating the Fortran wrappers */
#if defined(USE_WEAK_SYMBOLS) && defined(USE_ONLY_MPI_NAMES)
#if defined(HAVE_MULTIPLE_PRAGMA_WEAK)
extern FORT_DLL_SPEC void FORT_CALL MPIX_COMM_AGREE( MPI_Fint *, MPI_Fint *, MPI_Fint * );
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree__( MPI_Fint *, MPI_Fint *, MPI_Fint * );
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree( MPI_Fint *, MPI_Fint *, MPI_Fint * );
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree_( MPI_Fint *, MPI_Fint *, MPI_Fint * );
#if defined(F77_NAME_UPPER)
#pragma weak mpix_comm_agree__ = MPIX_COMM_AGREE
#pragma weak mpix_comm_agree_ = MPIX_COMM_AGREE
#pragma weak mpix_comm_agree = MPIX_COMM_AGREE
#elif defined(F77_NAME_LOWER_2USCORE)
#pragma weak MPIX_COMM_AGREE = mpix_comm_agree__
#pragma weak mpix_comm_agree_ = mpix_comm_agree__
#pragma weak mpix_comm_agree = mpix_comm_agree__
#elif defined(F77_NAME_LOWER_USCORE)
#pragma weak MPIX_COMM_AGREE = mpix_comm_agree_
#pragma weak mpix_comm_agree__ = mpix_comm_agree_
#pragma weak mpix_comm_agree = mpix_comm_agree_
#else
#pragma weak MPIX_COMM_AGREE = mpix_comm_agree
#pragma weak mpix_comm_agree__ = mpix_comm_agree
#pragma weak mpix_comm_agree_ = mpix_comm_agree
#endif
#elif defined(HAVE_WEAK_ATTRIBUTE)
#if defined(F77_NAME_UPPER)
extern FORT_DLL_SPEC void FORT_CALL MPIX_COMM_AGREE( MPI_Fint *, MPI_Fint *, MPI_Fint * );
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree__( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("MPIX_COMM_AGREE")));
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree_( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("MPIX_COMM_AGREE")));
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("MPIX_COMM_AGREE")));
#elif defined(F77_NAME_LOWER_2USCORE)
extern FORT_DLL_SPEC void FORT_CALL MPIX_COMM_AGREE( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("mpix_comm_agree__")));
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree__( MPI_Fint *, MPI_Fint *, MPI_Fint * );
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree_( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("mpix_comm_agree__")));
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("mpix_comm_agree__")));
#elif defined(F77_NAME_LOWER_USCORE)
extern FORT_DLL_SPEC void FORT_CALL MPIX_COMM_AGREE( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("mpix_comm_agree_")));
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree__( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("mpix_comm_agree_")));
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree_( MPI_Fint *, MPI_Fint *, MPI_Fint * );
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("mpix_comm_agree_")));
#else
extern FORT_DLL_SPEC void FORT_CALL MPIX_COMM_AGREE( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("mpix_comm_agree")));
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree__( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("mpix_comm_agree")));
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree_( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("mpix_comm_agree")));
extern FORT_DLL_SPEC void FORT_CALL mpix_comm_agree( MPI_Fint *, MPI_Fint *, MPI_Fint * );
#endif
#endif
#endif
/* Map the name to the correct form */
#ifndef MPICH_MPI_FROM_PMPI
#if defined(USE_WEAK_SYMBOLS)
#if defined(HAVE_MULTIPLE_PRAGMA_WEAK)
/* Define the weak versions of the PMPI routine*/
#ifndef F77_NAME_UPPER
extern FORT_DLL_SPEC void FORT_CALL PMPIX_COMM_AGREE( MPI_Fint *, MPI_Fint *, MPI_Fint * );
#endif
#ifndef F77_NAME_LOWER_2USCORE
extern FORT_DLL_SPEC void FORT_CALL pmpix_comm_agree__( MPI_Fint *, MPI_Fint *, MPI_Fint * );
#endif
#ifndef F77_NAME_LOWER_USCORE
extern FORT_DLL_SPEC void FORT_CALL pmpix_comm_agree_( MPI_Fint *, MPI_Fint *, MPI_Fint * );
#endif
#ifndef F77_NAME_LOWER
extern FORT_DLL_SPEC void FORT_CALL pmpix_comm_agree( MPI_Fint *, MPI_Fint *, MPI_Fint * );
#endif
#if defined(F77_NAME_UPPER)
#pragma weak pmpix_comm_agree__ = PMPIX_COMM_AGREE
#pragma weak pmpix_comm_agree_ = PMPIX_COMM_AGREE
#pragma weak pmpix_comm_agree = PMPIX_COMM_AGREE
#elif defined(F77_NAME_LOWER_2USCORE)
#pragma weak PMPIX_COMM_AGREE = pmpix_comm_agree__
#pragma weak pmpix_comm_agree_ = pmpix_comm_agree__
#pragma weak pmpix_comm_agree = pmpix_comm_agree__
#elif defined(F77_NAME_LOWER_USCORE)
#pragma weak PMPIX_COMM_AGREE = pmpix_comm_agree_
#pragma weak pmpix_comm_agree__ = pmpix_comm_agree_
#pragma weak pmpix_comm_agree = pmpix_comm_agree_
#else
#pragma weak PMPIX_COMM_AGREE = pmpix_comm_agree
#pragma weak pmpix_comm_agree__ = pmpix_comm_agree
#pragma weak pmpix_comm_agree_ = pmpix_comm_agree
#endif /* Test on name mapping */
#elif defined(HAVE_WEAK_ATTRIBUTE)
#if defined(F77_NAME_UPPER)
extern FORT_DLL_SPEC void FORT_CALL pmpix_comm_agree__( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("PMPIX_COMM_AGREE")));
extern FORT_DLL_SPEC void FORT_CALL pmpix_comm_agree_( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("PMPIX_COMM_AGREE")));
extern FORT_DLL_SPEC void FORT_CALL pmpix_comm_agree( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("PMPIX_COMM_AGREE")));
#elif defined(F77_NAME_LOWER_2USCORE)
extern FORT_DLL_SPEC void FORT_CALL PMPIX_COMM_AGREE( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("pmpix_comm_agree__")));
extern FORT_DLL_SPEC void FORT_CALL pmpix_comm_agree_( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("pmpix_comm_agree__")));
extern FORT_DLL_SPEC void FORT_CALL pmpix_comm_agree( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("pmpix_comm_agree__")));
#elif defined(F77_NAME_LOWER_USCORE)
extern FORT_DLL_SPEC void FORT_CALL PMPIX_COMM_AGREE( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("pmpix_comm_agree_")));
extern FORT_DLL_SPEC void FORT_CALL pmpix_comm_agree__( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("pmpix_comm_agree_")));
extern FORT_DLL_SPEC void FORT_CALL pmpix_comm_agree( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("pmpix_comm_agree_")));
#else
extern FORT_DLL_SPEC void FORT_CALL PMPIX_COMM_AGREE( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("pmpix_comm_agree")));
extern FORT_DLL_SPEC void FORT_CALL pmpix_comm_agree__( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("pmpix_comm_agree")));
extern FORT_DLL_SPEC void FORT_CALL pmpix_comm_agree_( MPI_Fint *, MPI_Fint *, MPI_Fint * ) __attribute__((weak,alias("pmpix_comm_agree")));
#endif /* Test on name mapping */
#endif /* HAVE_MULTIPLE_PRAGMA_WEAK */
#endif /* USE_WEAK_SYMBOLS */
#ifdef F77_NAME_UPPER
#define mpix_comm_agree_ PMPIX_COMM_AGREE
#elif defined(F77_NAME_LOWER_2USCORE)
#define mpix_comm_agree_ pmpix_comm_agree__
#elif !defined(F77_NAME_LOWER_USCORE)
#define mpix_comm_agree_ pmpix_comm_agree
#else
#define mpix_comm_agree_ pmpix_comm_agree_
#endif /* Test on name mapping */
/* This defines the routine that we call, which must be the PMPI version
since we're renaming the Fortran entry as the pmpi version. The MPI name
must be undefined first to prevent any conflicts with previous renamings. */
#undef MPIX_Comm_agree
#define MPIX_Comm_agree PMPIX_Comm_agree
#else
#ifdef F77_NAME_UPPER
#define mpix_comm_agree_ MPIX_COMM_AGREE
#elif defined(F77_NAME_LOWER_2USCORE)
#define mpix_comm_agree_ mpix_comm_agree__
#elif !defined(F77_NAME_LOWER_USCORE)
#define mpix_comm_agree_ mpix_comm_agree
/* Else leave name alone */
#endif
#endif /* MPICH_MPI_FROM_PMPI */
/* Prototypes for the Fortran interfaces */
#include "fproto.h"
FORT_DLL_SPEC void FORT_CALL mpix_comm_agree_ ( MPI_Fint *v1, MPI_Fint *v2, MPI_Fint *ierr ){
*ierr = MPIX_Comm_agree( (MPI_Comm)(*v1), v2 );
}
|
894848.c | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE190_Integer_Overflow__int_rand_add_52a.c
Label Definition File: CWE190_Integer_Overflow__int.label.xml
Template File: sources-sinks-52a.tmpl.c
*/
/*
* @description
* CWE: 190 Integer Overflow
* BadSource: rand Set data to result of rand(), which may be zero
* GoodSource: Small, non-zero
* Sinks: add
* GoodSink: Ensure there is no overflow before performing the addition
* BadSink : Add 1 to data
* Flow Variant: 52 Data flow: data passed as an argument from one function to another to another in three different source files
*
* */
#include "std_testcase.h"
#ifndef OMITBAD
/* bad function declaration */
void CWE190_Integer_Overflow__int_rand_add_52b_bad_sink(int data);
void CWE190_Integer_Overflow__int_rand_add_52_bad()
{
int data;
/* Initialize data */
data = -1;
data = RAND32();
CWE190_Integer_Overflow__int_rand_add_52b_bad_sink(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void CWE190_Integer_Overflow__int_rand_add_52b_goodG2B_sink(int data);
static void goodG2B()
{
int data;
/* Initialize data */
data = -1;
/* FIX: Use a small, non-zero value that will not cause an integer overflow in the sinks */
data = 5;
CWE190_Integer_Overflow__int_rand_add_52b_goodG2B_sink(data);
}
/* goodB2G uses the BadSource with the GoodSink */
void CWE190_Integer_Overflow__int_rand_add_52b_goodB2G_sink(int data);
static void goodB2G()
{
int data;
/* Initialize data */
data = -1;
data = RAND32();
CWE190_Integer_Overflow__int_rand_add_52b_goodB2G_sink(data);
}
void CWE190_Integer_Overflow__int_rand_add_52_good()
{
goodG2B();
goodB2G();
}
#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()...");
CWE190_Integer_Overflow__int_rand_add_52_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE190_Integer_Overflow__int_rand_add_52_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
589334.c | /*
* ----------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <[email protected]> wrote this file. As long as you retain this notice you
* can do whatever you want with this stuff. If we meet some day, and you think
* this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp
* ----------------------------------------------------------------------------
*
*/
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: src/tools/tools/ministat/ministat.c,v 1.8 2006/02/23 20:46:10 wkoszek Exp $");
#include <stdio.h>
#include <math.h>
#include <err.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/queue.h>
#include <sys/ttycom.h>
#define NSTUDENT 100
#define NCONF 6
double const studentpct[] = { 80, 90, 95, 98, 99, 99.5 };
double student [NSTUDENT + 1][NCONF] = {
/* inf */ { 1.282, 1.645, 1.960, 2.326, 2.576, 3.090 },
/* 1. */ { 3.078, 6.314, 12.706, 31.821, 63.657, 318.313 },
/* 2. */ { 1.886, 2.920, 4.303, 6.965, 9.925, 22.327 },
/* 3. */ { 1.638, 2.353, 3.182, 4.541, 5.841, 10.215 },
/* 4. */ { 1.533, 2.132, 2.776, 3.747, 4.604, 7.173 },
/* 5. */ { 1.476, 2.015, 2.571, 3.365, 4.032, 5.893 },
/* 6. */ { 1.440, 1.943, 2.447, 3.143, 3.707, 5.208 },
/* 7. */ { 1.415, 1.895, 2.365, 2.998, 3.499, 4.782 },
/* 8. */ { 1.397, 1.860, 2.306, 2.896, 3.355, 4.499 },
/* 9. */ { 1.383, 1.833, 2.262, 2.821, 3.250, 4.296 },
/* 10. */ { 1.372, 1.812, 2.228, 2.764, 3.169, 4.143 },
/* 11. */ { 1.363, 1.796, 2.201, 2.718, 3.106, 4.024 },
/* 12. */ { 1.356, 1.782, 2.179, 2.681, 3.055, 3.929 },
/* 13. */ { 1.350, 1.771, 2.160, 2.650, 3.012, 3.852 },
/* 14. */ { 1.345, 1.761, 2.145, 2.624, 2.977, 3.787 },
/* 15. */ { 1.341, 1.753, 2.131, 2.602, 2.947, 3.733 },
/* 16. */ { 1.337, 1.746, 2.120, 2.583, 2.921, 3.686 },
/* 17. */ { 1.333, 1.740, 2.110, 2.567, 2.898, 3.646 },
/* 18. */ { 1.330, 1.734, 2.101, 2.552, 2.878, 3.610 },
/* 19. */ { 1.328, 1.729, 2.093, 2.539, 2.861, 3.579 },
/* 20. */ { 1.325, 1.725, 2.086, 2.528, 2.845, 3.552 },
/* 21. */ { 1.323, 1.721, 2.080, 2.518, 2.831, 3.527 },
/* 22. */ { 1.321, 1.717, 2.074, 2.508, 2.819, 3.505 },
/* 23. */ { 1.319, 1.714, 2.069, 2.500, 2.807, 3.485 },
/* 24. */ { 1.318, 1.711, 2.064, 2.492, 2.797, 3.467 },
/* 25. */ { 1.316, 1.708, 2.060, 2.485, 2.787, 3.450 },
/* 26. */ { 1.315, 1.706, 2.056, 2.479, 2.779, 3.435 },
/* 27. */ { 1.314, 1.703, 2.052, 2.473, 2.771, 3.421 },
/* 28. */ { 1.313, 1.701, 2.048, 2.467, 2.763, 3.408 },
/* 29. */ { 1.311, 1.699, 2.045, 2.462, 2.756, 3.396 },
/* 30. */ { 1.310, 1.697, 2.042, 2.457, 2.750, 3.385 },
/* 31. */ { 1.309, 1.696, 2.040, 2.453, 2.744, 3.375 },
/* 32. */ { 1.309, 1.694, 2.037, 2.449, 2.738, 3.365 },
/* 33. */ { 1.308, 1.692, 2.035, 2.445, 2.733, 3.356 },
/* 34. */ { 1.307, 1.691, 2.032, 2.441, 2.728, 3.348 },
/* 35. */ { 1.306, 1.690, 2.030, 2.438, 2.724, 3.340 },
/* 36. */ { 1.306, 1.688, 2.028, 2.434, 2.719, 3.333 },
/* 37. */ { 1.305, 1.687, 2.026, 2.431, 2.715, 3.326 },
/* 38. */ { 1.304, 1.686, 2.024, 2.429, 2.712, 3.319 },
/* 39. */ { 1.304, 1.685, 2.023, 2.426, 2.708, 3.313 },
/* 40. */ { 1.303, 1.684, 2.021, 2.423, 2.704, 3.307 },
/* 41. */ { 1.303, 1.683, 2.020, 2.421, 2.701, 3.301 },
/* 42. */ { 1.302, 1.682, 2.018, 2.418, 2.698, 3.296 },
/* 43. */ { 1.302, 1.681, 2.017, 2.416, 2.695, 3.291 },
/* 44. */ { 1.301, 1.680, 2.015, 2.414, 2.692, 3.286 },
/* 45. */ { 1.301, 1.679, 2.014, 2.412, 2.690, 3.281 },
/* 46. */ { 1.300, 1.679, 2.013, 2.410, 2.687, 3.277 },
/* 47. */ { 1.300, 1.678, 2.012, 2.408, 2.685, 3.273 },
/* 48. */ { 1.299, 1.677, 2.011, 2.407, 2.682, 3.269 },
/* 49. */ { 1.299, 1.677, 2.010, 2.405, 2.680, 3.265 },
/* 50. */ { 1.299, 1.676, 2.009, 2.403, 2.678, 3.261 },
/* 51. */ { 1.298, 1.675, 2.008, 2.402, 2.676, 3.258 },
/* 52. */ { 1.298, 1.675, 2.007, 2.400, 2.674, 3.255 },
/* 53. */ { 1.298, 1.674, 2.006, 2.399, 2.672, 3.251 },
/* 54. */ { 1.297, 1.674, 2.005, 2.397, 2.670, 3.248 },
/* 55. */ { 1.297, 1.673, 2.004, 2.396, 2.668, 3.245 },
/* 56. */ { 1.297, 1.673, 2.003, 2.395, 2.667, 3.242 },
/* 57. */ { 1.297, 1.672, 2.002, 2.394, 2.665, 3.239 },
/* 58. */ { 1.296, 1.672, 2.002, 2.392, 2.663, 3.237 },
/* 59. */ { 1.296, 1.671, 2.001, 2.391, 2.662, 3.234 },
/* 60. */ { 1.296, 1.671, 2.000, 2.390, 2.660, 3.232 },
/* 61. */ { 1.296, 1.670, 2.000, 2.389, 2.659, 3.229 },
/* 62. */ { 1.295, 1.670, 1.999, 2.388, 2.657, 3.227 },
/* 63. */ { 1.295, 1.669, 1.998, 2.387, 2.656, 3.225 },
/* 64. */ { 1.295, 1.669, 1.998, 2.386, 2.655, 3.223 },
/* 65. */ { 1.295, 1.669, 1.997, 2.385, 2.654, 3.220 },
/* 66. */ { 1.295, 1.668, 1.997, 2.384, 2.652, 3.218 },
/* 67. */ { 1.294, 1.668, 1.996, 2.383, 2.651, 3.216 },
/* 68. */ { 1.294, 1.668, 1.995, 2.382, 2.650, 3.214 },
/* 69. */ { 1.294, 1.667, 1.995, 2.382, 2.649, 3.213 },
/* 70. */ { 1.294, 1.667, 1.994, 2.381, 2.648, 3.211 },
/* 71. */ { 1.294, 1.667, 1.994, 2.380, 2.647, 3.209 },
/* 72. */ { 1.293, 1.666, 1.993, 2.379, 2.646, 3.207 },
/* 73. */ { 1.293, 1.666, 1.993, 2.379, 2.645, 3.206 },
/* 74. */ { 1.293, 1.666, 1.993, 2.378, 2.644, 3.204 },
/* 75. */ { 1.293, 1.665, 1.992, 2.377, 2.643, 3.202 },
/* 76. */ { 1.293, 1.665, 1.992, 2.376, 2.642, 3.201 },
/* 77. */ { 1.293, 1.665, 1.991, 2.376, 2.641, 3.199 },
/* 78. */ { 1.292, 1.665, 1.991, 2.375, 2.640, 3.198 },
/* 79. */ { 1.292, 1.664, 1.990, 2.374, 2.640, 3.197 },
/* 80. */ { 1.292, 1.664, 1.990, 2.374, 2.639, 3.195 },
/* 81. */ { 1.292, 1.664, 1.990, 2.373, 2.638, 3.194 },
/* 82. */ { 1.292, 1.664, 1.989, 2.373, 2.637, 3.193 },
/* 83. */ { 1.292, 1.663, 1.989, 2.372, 2.636, 3.191 },
/* 84. */ { 1.292, 1.663, 1.989, 2.372, 2.636, 3.190 },
/* 85. */ { 1.292, 1.663, 1.988, 2.371, 2.635, 3.189 },
/* 86. */ { 1.291, 1.663, 1.988, 2.370, 2.634, 3.188 },
/* 87. */ { 1.291, 1.663, 1.988, 2.370, 2.634, 3.187 },
/* 88. */ { 1.291, 1.662, 1.987, 2.369, 2.633, 3.185 },
/* 89. */ { 1.291, 1.662, 1.987, 2.369, 2.632, 3.184 },
/* 90. */ { 1.291, 1.662, 1.987, 2.368, 2.632, 3.183 },
/* 91. */ { 1.291, 1.662, 1.986, 2.368, 2.631, 3.182 },
/* 92. */ { 1.291, 1.662, 1.986, 2.368, 2.630, 3.181 },
/* 93. */ { 1.291, 1.661, 1.986, 2.367, 2.630, 3.180 },
/* 94. */ { 1.291, 1.661, 1.986, 2.367, 2.629, 3.179 },
/* 95. */ { 1.291, 1.661, 1.985, 2.366, 2.629, 3.178 },
/* 96. */ { 1.290, 1.661, 1.985, 2.366, 2.628, 3.177 },
/* 97. */ { 1.290, 1.661, 1.985, 2.365, 2.627, 3.176 },
/* 98. */ { 1.290, 1.661, 1.984, 2.365, 2.627, 3.175 },
/* 99. */ { 1.290, 1.660, 1.984, 2.365, 2.626, 3.175 },
/* 100. */ { 1.290, 1.660, 1.984, 2.364, 2.626, 3.174 }
};
#define MAX_DS 8
static char symbol[MAX_DS] = { ' ', 'x', '+', '*', '%', '#', '@', 'O' };
TAILQ_HEAD(pointlist, point);
struct dataset {
struct pointlist list;
double sy, syy;
int n;
};
static struct dataset *
NewSet(void)
{
struct dataset *ds;
ds = calloc(1, sizeof *ds);
TAILQ_INIT(&ds->list);
return(ds);
}
struct point {
TAILQ_ENTRY(point) list;
double val;
};
static void
AddPoint(struct dataset *ds, double a)
{
struct point *pp, *pp2;
pp = calloc(1, sizeof *pp);
pp->val = a;
ds->n++;
ds->sy += a;
ds->syy += a * a;
if (TAILQ_EMPTY(&ds->list)) {
TAILQ_INSERT_HEAD(&ds->list, pp, list);
return;
}
TAILQ_FOREACH(pp2, &ds->list, list) {
if (pp->val < pp2->val) {
TAILQ_INSERT_BEFORE(pp2, pp, list);
return;
}
}
TAILQ_INSERT_TAIL(&ds->list, pp, list);
}
static double
Min(struct dataset *ds)
{
return (TAILQ_FIRST(&ds->list)->val);
}
static double
Max(struct dataset *ds)
{
return(TAILQ_LAST(&ds->list, pointlist)->val);
}
static double
Avg(struct dataset *ds)
{
return(ds->sy / ds->n);
}
static double
Median(struct dataset *ds)
{
int even, i;
struct point *p1, *p2;
if ((ds->n % 2) == 1) {
i = (ds->n / 2) + 1;
even = 0;
} else {
i = ds->n / 2;
even = 1;
}
TAILQ_FOREACH(p1, &ds->list, list) {
--i;
if (i == 0)
break;
}
if (even) {
p2 = TAILQ_NEXT(p1, list);
return ((p2->val + p1->val) / 2);
}
return (p1->val);
}
static double
Var(struct dataset *ds)
{
return (ds->syy - ds->sy * ds->sy / ds->n) / (ds->n - 1.0);
}
static double
Stddev(struct dataset *ds)
{
return sqrt(Var(ds));
}
static void
VitalsHead(void)
{
printf(" N Min Max Median Avg Stddev\n");
}
static void
Vitals(struct dataset *ds, int flag)
{
double a;
printf("%c %3d %13.8g %13.8g %13.8g %13.8g %13.8g", symbol[flag],
ds->n, Min(ds), Max(ds), Median(ds), Avg(ds), Stddev(ds));
printf("\n");
}
static void
Relative(struct dataset *ds, struct dataset *rs, int confidx)
{
double spool, s, d, e, t;
int i, c;
i = ds->n + rs->n - 2;
if (i > NSTUDENT)
t = student[0][confidx];
else
t = student[i][confidx];
spool = (ds->n - 1) * Var(ds) + (rs->n - 1) * Var(rs);
spool /= ds->n + rs->n - 2;
spool = sqrt(spool);
s = spool * sqrt(1.0 / ds->n + 1.0 / rs->n);
d = Avg(ds) - Avg(rs);
e = t * s;
if (fabs(d) > e) {
printf("Difference at %.1f%% confidence\n", studentpct[confidx]);
printf(" %g +/- %g\n", d, e);
printf(" %g%% +/- %g%%\n", d * 100 / Avg(rs), e * 100 / Avg(rs));
printf(" (Student's t, pooled s = %g)\n", spool);
} else {
printf("No difference proven at %.1f%% confidence\n",
studentpct[confidx]);
}
}
struct plot {
double min;
double max;
double span;
int width;
double x0, dx;
int height;
char *data;
char **bar;
int separate_bars;
int num_datasets;
};
static struct plot plot;
static void
SetupPlot(int width, int separate, int num_datasets)
{
struct plot *pl;
pl = &plot;
pl->width = width;
pl->height = 0;
pl->data = NULL;
pl->bar = NULL;
pl->separate_bars = separate;
pl->num_datasets = num_datasets;
pl->min = 999e99;
pl->max = -999e99;
}
static void
AdjPlot(double a)
{
struct plot *pl;
pl = &plot;
if (a < pl->min)
pl->min = a;
if (a > pl->max)
pl->max = a;
pl->span = pl->max - pl->min;
pl->dx = pl->span / (pl->width - 1.0);
pl->x0 = pl->min - .5 * pl->dx;
}
static void
DimPlot(struct dataset *ds)
{
AdjPlot(Min(ds));
AdjPlot(Max(ds));
AdjPlot(Avg(ds) - Stddev(ds));
AdjPlot(Avg(ds) + Stddev(ds));
}
static void
PlotSet(struct dataset *ds, int val)
{
struct plot *pl;
struct point *pp;
int i, j, m, x;
int bar;
pl = &plot;
if (pl->span == 0)
return;
if (pl->separate_bars)
bar = val-1;
else
bar = 0;
if (pl->bar == NULL) {
pl->bar = malloc(sizeof(char *) * pl->num_datasets);
memset(pl->bar, 0, sizeof(char*) * pl->num_datasets);
}
if (pl->bar[bar] == NULL) {
pl->bar[bar] = malloc(pl->width);
memset(pl->bar[bar], 0, pl->width);
}
m = 1;
i = -1;
j = 0;
TAILQ_FOREACH(pp, &ds->list, list) {
x = (pp->val - pl->x0) / pl->dx;
if (x == i) {
j++;
if (j > m)
m = j;
} else {
j = 1;
i = x;
}
}
m += 1;
if (m > pl->height) {
pl->data = realloc(pl->data, pl->width * m);
memset(pl->data + pl->height * pl->width, 0,
(m - pl->height) * pl->width);
}
pl->height = m;
i = -1;
TAILQ_FOREACH(pp, &ds->list, list) {
x = (pp->val - pl->x0) / pl->dx;
if (x == i) {
j++;
} else {
j = 1;
i = x;
}
pl->data[j * pl->width + x] |= val;
}
x = ((Avg(ds) - Stddev(ds)) - pl->x0) / pl->dx;
m = ((Avg(ds) + Stddev(ds)) - pl->x0) / pl->dx;
pl->bar[bar][m] = '|';
pl->bar[bar][x] = '|';
for (i = x + 1; i < m; i++)
if (pl->bar[bar][i] == 0)
pl->bar[bar][i] = '_';
x = (Median(ds) - pl->x0) / pl->dx;
pl->bar[bar][x] = 'M';
x = (Avg(ds) - pl->x0) / pl->dx;
pl->bar[bar][x] = 'A';
}
static void
DumpPlot(void)
{
struct plot *pl;
int i, j, k;
pl = &plot;
if (pl->span == 0) {
printf("[no plot, span is zero width]\n");
return;
}
putchar('+');
for (i = 0; i < pl->width; i++)
putchar('-');
putchar('+');
putchar('\n');
for (i = 1; i < pl->height; i++) {
putchar('|');
for (j = 0; j < pl->width; j++) {
k = pl->data[(pl->height - i) * pl->width + j];
if (k >= 0 && k < MAX_DS)
putchar(symbol[k]);
else
printf("[%02x]", k);
}
putchar('|');
putchar('\n');
}
for (i = 0; i < pl->num_datasets; i++) {
if (pl->bar[i] == NULL)
continue;
putchar('|');
for (j = 0; j < pl->width; j++) {
k = pl->bar[i][j];
if (k == 0)
k = ' ';
putchar(k);
}
putchar('|');
putchar('\n');
}
putchar('+');
for (i = 0; i < pl->width; i++)
putchar('-');
putchar('+');
putchar('\n');
}
static struct dataset *
ReadSet(char *n)
{
FILE *f;
char buf[BUFSIZ], *p;
struct dataset *s;
double d;
int line;
if (n == NULL) {
f = stdin;
n = "<stdin>";
} else if (!strcmp(n, "-")) {
f = stdin;
n = "<stdin>";
} else {
f = fopen(n, "r");
}
if (f == NULL)
err(1, "Cannot open %s", n);
s = NewSet();
line = 0;
while (fgets(buf, sizeof buf, f) != NULL) {
line++;
p = strchr(buf, '#');
if (p != NULL)
*p = '\0';
p = buf + strlen(buf) - 1;
while (p >= buf && isspace(*p)) {
*p = '\0';
p--;
}
d = strtod(buf, &p);
if (p != NULL && *p != '\0')
err(2, "Invalid data on line %d in %s\n", line, n);
if (*buf != '\0')
AddPoint(s, d);
}
fclose(f);
if (s->n < 3) {
fprintf(stderr,
"Dataset %s must contain at least 3 data points\n", n);
exit (2);
}
return (s);
}
static void
usage(char const *whine)
{
int i;
fprintf(stderr, "%s\n", whine);
fprintf(stderr,
"Usage: ministat [ -c confidence ] [-ns] [-w width] [file [file ...]]\n");
fprintf(stderr, "\tconfidence = {");
for (i = 0; i < NCONF; i++) {
fprintf(stderr, "%s%g%%",
i ? ", " : "",
studentpct[i]);
}
fprintf(stderr, "}\n");
fprintf(stderr, "\t-n : print summary statistics only, no graph/test\n");
fprintf(stderr, "\t-s : print avg/median/stddev bars on separate lines\n");
fprintf(stderr, "\t-w : width of graph/test output (default 74 or terminal width)\n");
exit (2);
}
int
main(int argc, char **argv)
{
struct dataset *ds[7];
int nds;
double a;
char *p;
int c, i, ci;
int flag_s = 0;
int flag_n = 0;
int termwidth = 74;
if (isatty(STDOUT_FILENO)) {
struct winsize wsz;
if ((p = getenv("COLUMNS")) != NULL && *p != '\0')
termwidth = atoi(p);
else if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &wsz) != -1 &&
wsz.ws_col > 0)
termwidth = wsz.ws_col - 2;
}
ci = -1;
while ((c = getopt(argc, argv, "c:snw:")) != -1)
switch (c) {
case 'c':
a = strtod(optarg, &p);
if (p != NULL && *p != '\0')
usage("Not a floating point number");
for (i = 0; i < NCONF; i++)
if (a == studentpct[i])
ci = i;
if (ci == -1)
usage("No support for confidence level");
break;
case 'n':
flag_n = 1;
break;
case 's':
flag_s = 1;
break;
case 'w':
termwidth = strtol(optarg, &p, 10);
if (p != NULL && *p != '\0')
usage("Invalid width, not a number.");
if (termwidth < 0)
usage("Unable to move beyond left margin.");
break;
default:
usage("Unknown option");
break;
}
if (ci == -1)
ci = 2;
argc -= optind;
argv += optind;
if (argc == 0) {
ds[0] = ReadSet(NULL);
printf("x stdin\n");
nds = 1;
} else {
if (argc > (MAX_DS - 1))
usage("Too many datasets.");
nds = argc;
for (i = 0; i < nds; i++) {
ds[i] = ReadSet(argv[i]);
printf("%c %s\n", symbol[i+1], argv[i]);
}
}
if (!flag_n) {
SetupPlot(termwidth, flag_s, nds);
for (i = 0; i < nds; i++)
DimPlot(ds[i]);
for (i = 0; i < nds; i++)
PlotSet(ds[i], i + 1);
DumpPlot();
}
VitalsHead();
Vitals(ds[0], 1);
for (i = 1; i < nds; i++) {
Vitals(ds[i], i + 1);
if (!flag_n)
Relative(ds[i], ds[0], ci);
}
exit(0);
}
|
447141.c | /*
* OhmniLabs light animation engine
*
* Jared
*/
/* TODO: instead of states could make this programmable slots that get
* set up from serial for flexibility, and/or even save to flash for boot anim */
/* Including needed modules to compile this module/procedure */
#include "Cpu.h"
#include "Events.h"
/* Including shared modules, which are used for whole project */
#include "PE_Types.h"
/* Our source */
#include "systime.h"
#include "spi_apa102.h"
#include "anim_engine.h"
#include "flash.h"
/* ---- Global ---- */
struct anim_engine _anim = {0};
// 1 millisecond frames, more than needed but convenient for now
#define FRAME_TICKS 1500
// Helper to set lighting
#define SET_HSV(x, h, s, v) { (x)[0] = h; (x)[1] = s; (x)[2] = v; }
/* ---- Methods ---- */
void anim_setup()
{
// Synchronize clock
_anim.fticks = _systime.ticks;
// Start with rise
_anim.state = ANIM_STATE_STARTING_RISE;
anim_state_begin();
}
void anim_poll()
{
// Increment our frame counter
int fadv = 0;
while(1) {
// See if we advanced one frame
int delta = _systime.ticks - _anim.fticks;
if (delta < FRAME_TICKS) break;
// Okay, then we moved, adjust
_anim.fticks += 1500;
fadv += 1;
}
// Check if anything changed
if (fadv == 0) return;
// Increment frames when not animating too
_anim.fnum += fadv;
// If not animating also no-op
if (_anim.state == ANIM_STATE_NONE)
return;
// Compute interpolation factor
int df = _anim.fnum - _anim.start_frame;
// Check if we reached end state
if (df >= _anim.duration_frames) {
SET_HSV(_anim.current_hsv,
_anim.end_hsv[0], _anim.end_hsv[1], _anim.end_hsv[2]);
SET_HSV(_anim.start_hsv,
_anim.end_hsv[0], _anim.end_hsv[1], _anim.end_hsv[2]);
anim_state_done();
return;
}
// Otherwise, compute interpolation and update
int *curr = _anim.current_hsv;
int *start = _anim.start_hsv;
int *step = _anim.step_hsv;
for (int i = 0; i < 3; i++) {
curr[i] = start[i] + step[i] * df;
}
// Copy over to SPI engine now
spi_set_global_hsv(curr[0] >> 20, curr[1] >> 20, curr[2] >> 20);
}
void anim_begin(struct hsv *start, struct hsv *end, int nframes)
{
// Snapshot frame start and frame duration
_anim.start_frame = _anim.fnum;
_anim.duration_frames = nframes;
// Save start and end in our scaled space
int* s = _anim.start_hsv;
if (start != NULL) {
s[0] = start->h << 20;
s[1] = start->s << 20;
s[2] = start->v << 20;
}
int* e = _anim.end_hsv;
if (end != NULL) {
e[0] = end->h << 20;
e[1] = end->s << 20;
e[2] = end->v << 20;
}
// Compute step values here per frame in our scaled space
for (int i = 0; i < 3; i++) {
_anim.step_hsv[i] = (e[i] - s[i]) / nframes;
_anim.current_hsv[i] = s[i];
}
}
void anim_state_begin()
{
switch(_anim.state) {
case ANIM_STATE_STARTING_RISE:
{
// Start animation up
struct hsv start = { 130, 240, 0 };
struct hsv end = { 130, 140, 120 };
// Use the boot hue
start.h = _flash.boot_hue;
end.h = _flash.boot_hue;
anim_begin(&start, &end, 2000);
break;
}
case ANIM_STATE_STARTING_SETTLE:
{
// Start from wherever we last finished (rise)
struct hsv end = { 130, 180, 30 };
end.h = _flash.boot_hue;
anim_begin(NULL, &end, 1500);
break;
}
default:
// Normalize any other state
_anim.state = ANIM_STATE_NONE;
break;
}
}
void anim_state_done()
{
switch(_anim.state) {
case ANIM_STATE_STARTING_RISE:
_anim.state = ANIM_STATE_STARTING_SETTLE;
anim_state_begin();
break;
default:
_anim.state = ANIM_STATE_NONE;
anim_state_begin();
break;
}
}
|
460607.c | /*
* Copyright (C) 2019-2020 BiiLabs Co., Ltd. and Contributors
* All Rights Reserved.
* This is free software; you can redistribute it and/or modify it under the
* terms of the MIT license. A copy of the license can be found in the file
* "LICENSE" at the root of this distribution.
*/
#include "duplex_callback.h"
#include <stdlib.h>
#include <string.h>
#include "connectivity/common.h"
#define MQTT_CALLBACK_LOGGER "duplex_callback"
static logger_id_t logger_id;
static ta_core_t *ta_core;
void mqtt_callback_logger_init() { logger_id = logger_helper_enable(MQTT_CALLBACK_LOGGER, LOGGER_DEBUG, true); }
int mqtt_callback_logger_release() {
logger_helper_release(logger_id);
if (logger_helper_destroy() != RC_OK) {
ta_log_error("Destroying logger failed %s.\n", MQTT_CALLBACK_LOGGER);
return EXIT_FAILURE;
}
return 0;
}
void ta_mqtt_init(ta_core_t *const core) { ta_core = core; }
status_t check_valid_tag(char *tag) {
size_t len = strnlen(tag, NUM_TRYTES_TAG + 1);
if (len < 1 || len > NUM_TRYTES_TAG) {
ta_log_error("%s\n", ta_error_to_string(SC_MQTT_INVALID_TAG));
return SC_MQTT_INVALID_TAG;
}
for (size_t i = 0; i < len; ++i) {
if ((tag[i] > 'Z' || tag[i] < 'A') && tag[i] != '9') {
ta_log_error("%s\n", ta_error_to_string(SC_MQTT_INVALID_TAG));
return SC_MQTT_INVALID_TAG;
}
}
return SC_OK;
}
static status_t mqtt_request_handler(mosq_config_t *cfg, char *subscribe_topic, char *req) {
if (cfg == NULL || subscribe_topic == NULL || req == NULL) {
ta_log_error("%s\n", ta_error_to_string(SC_NULL));
return SC_NULL;
}
status_t ret = SC_OK;
char *json_result = NULL;
char *res_topic = NULL;
char device_id[ID_LEN] = {0};
// get the Device ID.
ret = mqtt_device_id_deserialize(req, device_id);
if (ret != SC_OK) {
ta_log_error("%s\n", ta_error_to_string(ret));
goto done;
}
iota_client_service_t iota_service;
ta_set_iota_client_service(&iota_service, ta_core->iota_service.http.host, ta_core->iota_service.http.port,
ta_core->iota_service.http.ca_pem);
char *api_sub_topic = subscribe_topic + strlen(ta_core->ta_conf.mqtt_topic_root);
if (api_path_matcher(api_sub_topic, "/tag/hashes") == SC_OK) {
char tag[NUM_TRYTES_TAG + 1] = {0};
mqtt_tag_req_deserialize(req, tag);
if (check_valid_tag(tag) == SC_OK) {
ret = api_find_transactions_by_tag(&iota_service, tag, &json_result);
} else {
ret = SC_HTTP_URL_NOT_MATCH;
}
} else if (api_path_matcher(api_sub_topic, "/tag/object") == SC_OK) {
char tag[NUM_TRYTES_TAG + 1] = {0};
mqtt_tag_req_deserialize(req, tag);
if (check_valid_tag(tag) == SC_OK) {
ret = api_find_transactions_obj_by_tag(&iota_service, tag, &json_result);
} else {
ret = SC_HTTP_URL_NOT_MATCH;
}
} else if (api_path_matcher(api_sub_topic, "/transaction") == SC_OK) {
char hash[NUM_TRYTES_HASH + 1];
mqtt_transaction_hash_req_deserialize(req, hash);
ret = api_find_transaction_object_single(&iota_service, hash, &json_result);
} else if (api_path_matcher(api_sub_topic, "/transaction/object") == SC_OK) {
ret = api_find_transaction_objects(&iota_service, req, &json_result);
} else if (api_path_matcher(api_sub_topic, "/transaction/send") == SC_OK) {
ret = api_send_transfer(ta_core, &iota_service, req, &json_result);
} else if (api_path_matcher(api_sub_topic, "/tryte") == SC_OK) {
ret = api_send_trytes(&ta_core->ta_conf, &ta_core->iota_conf, &iota_service, req, &json_result);
} else {
cJSON *json_obj = cJSON_CreateObject();
cJSON_AddStringToObject(json_obj, "message", api_sub_topic);
json_result = cJSON_PrintUnformatted(json_obj);
cJSON_Delete(json_obj);
}
set_response_content(ret, &json_result);
// Log results
printf("\"%s\" %s\n", api_sub_topic, ta_error_to_string(ret));
// Set response publishing topic with the topic we got message and the Device ID (client ID) we got in the message
int res_topic_len = strlen(subscribe_topic) + 1 + ID_LEN + 1;
res_topic = (char *)malloc(res_topic_len);
snprintf(res_topic, res_topic_len, "%s/%s", subscribe_topic, device_id);
ret = gossip_channel_set(cfg, NULL, NULL, res_topic);
if (ret != SC_OK) {
ta_log_error("%s\n", ta_error_to_string(ret));
goto done;
}
// Set recv_message as publishing message
ret = gossip_message_set(cfg, json_result);
if (ret != SC_OK) {
ta_log_error("%s\n", ta_error_to_string(ret));
}
done:
free(json_result);
free(res_topic);
return ret;
}
static void publish_callback_duplex_func(struct mosquitto *mosq, void *obj, int mid, int reason_code,
const mosquitto_property *properties) {
publish_callback_pub_func(mosq, obj, mid, reason_code, properties);
}
static void message_callback_duplex_func(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message,
const mosquitto_property *properties) {
mosq_config_t *cfg = (mosq_config_t *)obj;
message_callback_sub_func(mosq, obj, message, properties);
mosquitto_disconnect_v5(mosq, 0, cfg->property_config->disconnect_props);
// Process received requests
mqtt_request_handler(cfg, message->topic, cfg->sub_config->recv_message);
// The following one line is used for testing if this server work fine with requests with given topics.
// Uncomment it if it is necessitated
// gossip_message_set(cfg, cfg->sub_config->recv_message);
}
static void connect_callback_duplex_func(struct mosquitto *mosq, void *obj, int result, int flags,
const mosquitto_property *properties) {
mosq_config_t *cfg = (mosq_config_t *)obj;
if (cfg->general_config->client_type == client_pub) {
connect_callback_pub_func(mosq, obj, result, flags, properties);
} else if (cfg->general_config->client_type == client_sub) {
connect_callback_sub_func(mosq, obj, result, flags, properties);
}
}
static void disconnect_callback_duplex_func(struct mosquitto *mosq, void *obj, mosq_retcode_t ret,
const mosquitto_property *properties) {
UNUSED(mosq);
UNUSED(obj);
UNUSED(ret);
UNUSED(properties);
// TODO we may necessitate doing something here after client is disconnected.
}
static void subscribe_callback_duplex_func(struct mosquitto *mosq, void *obj, int mid, int qos_count,
const int *granted_qos) {
subscribe_callback_sub_func(mosq, obj, mid, qos_count, granted_qos);
}
static void log_callback_duplex_func(struct mosquitto *mosq, void *obj, int level, const char *str) {
UNUSED(mosq);
UNUSED(obj);
UNUSED(level);
log_info(logger_id, "log: %s\n", str);
}
status_t duplex_callback_func_set(struct mosquitto *mosq) {
if (mosq == NULL) {
ta_log_error("%s\n", ta_error_to_string(SC_NULL));
return SC_NULL;
}
mosquitto_log_callback_set(mosq, log_callback_duplex_func);
mosquitto_subscribe_callback_set(mosq, subscribe_callback_duplex_func);
mosquitto_connect_v5_callback_set(mosq, connect_callback_duplex_func);
mosquitto_disconnect_v5_callback_set(mosq, disconnect_callback_duplex_func);
mosquitto_publish_v5_callback_set(mosq, publish_callback_duplex_func);
mosquitto_message_v5_callback_set(mosq, message_callback_duplex_func);
return SC_OK;
}
|
620455.c | /**************************************************************************
*
* Copyright 2011-2017 by Andrey Butok. FNET Community.
*
***************************************************************************
*
* 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.
*
***************************************************************************
*
* Ethernet driver interafce.
*
***************************************************************************/
#include "fnet.h"
#if FNET_MK && FNET_CFG_CPU_ETH0
#include "port/cpu/netif/fec/fnet_fec.h"
/************************************************************************
* Ethernet interface structure.
*************************************************************************/
static fnet_eth_if_t fnet_mk_eth0_if =
{
.eth_prv = &fnet_fec0_if, /* Points to Ethernet driver-specific control data structure. */
.eth_mac_number = 0, /* MAC module number. */
.eth_output = fnet_fec_output, /* Ethernet driver output.*/
#if FNET_CFG_MULTICAST
.eth_multicast_join = fnet_fec_multicast_join, /* Ethernet driver join multicast group.*/
.eth_multicast_leave = fnet_fec_multicast_leave /* Ethernet driver leave multicast group.*/
#endif
};
fnet_netif_t fnet_cpu_eth0_if =
{
.netif_name = FNET_CFG_CPU_ETH0_NAME, /* Network interface name.*/
.netif_mtu = FNET_CFG_CPU_ETH0_MTU, /* Maximum transmission unit.*/
.netif_prv = &fnet_mk_eth0_if, /* Points to interface specific data structure.*/
.netif_api = &fnet_fec_api /* Interface API */
};
/************************************************************************
* DESCRIPTION: Ethernet IO initialization.
*************************************************************************/
#if FNET_CFG_CPU_ETH_IO_INIT
void fnet_eth_io_init(void)
{
FNET_MK_PORT_MemMapPtr pctl;
FNET_MK_SIM_MemMapPtr sim = (FNET_MK_SIM_MemMapPtr)FNET_MK_SIM_BASE_PTR;
#if FNET_CFG_CPU_MK64FN1
/* Enable clock */
FNET_MK_SIM_SCGC5 |= FNET_MK_SIM_SCGC5_PORTC_MASK | FNET_MK_SIM_SCGC5_PORTA_MASK | FNET_MK_SIM_SCGC5_PORTB_MASK;
pctl = (FNET_MK_PORT_MemMapPtr)FNET_MK_PORTC_BASE_PTR;
#if 0 /* PTC16-17 may be used also as UART pins */
pctl->PCR[16] = 0x00000400u;
pctl->PCR[17] = 0x00000400u;
#endif
pctl->PCR[18] = 0x00000400u;
pctl->PCR[19] = 0x00000400u;
pctl = (FNET_MK_PORT_MemMapPtr)FNET_MK_PORTA_BASE_PTR;
pctl->PCR[12] = 0x00000400u; /* PTA12, RMII0_RXD1/MII0_RXD1 */
pctl->PCR[13] = 0x00000400u; /* PTA13, RMII0_RXD0/MII0_RXD0 */
pctl->PCR[14] = 0x00000400u; /* PTA14, RMII0_CRS_DV/MII0_RXDV */
pctl->PCR[15] = 0x00000400u; /* PTA15, RMII0_TXEN/MII0_TXEN */
pctl->PCR[16] = 0x00000400u; /* PTA16, RMII0_TXD0/MII0_TXD0 */
pctl->PCR[17] = 0x00000400u; /* PTA17, RMII0_TXD1/MII0_TXD1 */
pctl->PCR[5] = 0x00000400u;
pctl->PCR[28] = 0x00000400u;
pctl = (FNET_MK_PORT_MemMapPtr)FNET_MK_PORTB_BASE_PTR;
pctl->PCR[0] = FNET_MK_PORT_PCR_MUX(4) | FNET_MK_PORT_PCR_ODE_MASK | FNET_MK_PORT_PCR_PS_MASK | FNET_MK_PORT_PCR_PE_MASK; /* PTB0, RMII0_MDIO/MII0_MDIO */
pctl->PCR[1] = FNET_MK_PORT_PCR_MUX(4); /* PTB1, RMII0_MDC/MII0_MDC */
#elif FNET_CFG_CPU_MK66FN2
/* Enable clock */
FNET_MK_SIM_SCGC5 |= FNET_MK_SIM_SCGC5_PORTE_MASK | FNET_MK_SIM_SCGC5_PORTA_MASK | FNET_MK_SIM_SCGC5_PORTB_MASK;
pctl = (FNET_MK_PORT_MemMapPtr)FNET_MK_PORTE_BASE_PTR;
pctl->PCR[26] = 0x00000200u;
pctl = (FNET_MK_PORT_MemMapPtr)FNET_MK_PORTA_BASE_PTR;
pctl->PCR[5] = 0x00000400u;
pctl->PCR[12] = 0x00000400u; /* PTA12, RMII0_RXD1/MII0_RXD1 */
pctl->PCR[13] = 0x00000400u; /* PTA13, RMII0_RXD0/MII0_RXD0 */
pctl->PCR[14] = 0x00000400u; /* PTA14, RMII0_CRS_DV/MII0_RXDV */
pctl->PCR[15] = 0x00000400u; /* PTA15, RMII0_TXEN/MII0_TXEN */
pctl->PCR[16] = 0x00000400u; /* PTA16, RMII0_TXD0/MII0_TXD0 */
pctl->PCR[17] = 0x00000400u; /* PTA17, RMII0_TXD1/MII0_TXD1 */
pctl->PCR[28] = 0x00000400u;
pctl = (FNET_MK_PORT_MemMapPtr)FNET_MK_PORTB_BASE_PTR;
pctl->PCR[0] = FNET_MK_PORT_PCR_MUX(4) | FNET_MK_PORT_PCR_ODE_MASK | FNET_MK_PORT_PCR_PS_MASK | FNET_MK_PORT_PCR_PE_MASK; /* PTB0, RMII0_MDIO/MII0_MDIO */
pctl->PCR[1] = FNET_MK_PORT_PCR_MUX(4); /* PTB1, RMII0_MDC/MII0_MDC */
/* Set RMII clock src. */
sim->SOPT2 |= FNET_MK_SIM_SOPT2_RMIISRC(1);
#else /* TWR */
/* Enable clock */
FNET_MK_SIM_SCGC5 |= FNET_MK_SIM_SCGC5_PORTA_MASK | FNET_MK_SIM_SCGC5_PORTB_MASK;
pctl = (FNET_MK_PORT_MemMapPtr)FNET_MK_PORTA_BASE_PTR;
pctl->PCR[12] = 0x00000400u; /* PTA12, RMII0_RXD1/MII0_RXD1 */
pctl->PCR[13] = 0x00000400u; /* PTA13, RMII0_RXD0/MII0_RXD0 */
pctl->PCR[14] = 0x00000400u; /* PTA14, RMII0_CRS_DV/MII0_RXDV */
pctl->PCR[15] = 0x00000400u; /* PTA15, RMII0_TXEN/MII0_TXEN */
pctl->PCR[16] = 0x00000400u; /* PTA16, RMII0_TXD0/MII0_TXD0 */
pctl->PCR[17] = 0x00000400u; /* PTA17, RMII0_TXD1/MII0_TXD1 */
pctl = (FNET_MK_PORT_MemMapPtr)FNET_MK_PORTB_BASE_PTR;
pctl->PCR[0] = FNET_MK_PORT_PCR_MUX(4) | FNET_MK_PORT_PCR_ODE_MASK; /* PTB0, RMII0_MDIO/MII0_MDIO */
pctl->PCR[1] = FNET_MK_PORT_PCR_MUX(4); /* PTB1, RMII0_MDC/MII0_MDC */
#endif
/* Enable clock for ENET module */
sim->SCGC2 |= FNET_MK_SIM_SCGC2_ENET_MASK;
/*Allow concurrent access to MPU controller. Example: ENET uDMA to SRAM, otherwise bus error*/
FNET_MK_MPU_CESR = 0u; /* MPU is disabled. All accesses from all bus masters are allowed.*/
}
#endif /*!FNET_CFG_CPU_ETH_IO_INIT*/
/************************************************************************
* DESCRIPTION: Ethernet Physical Transceiver initialization and/or reset.
*************************************************************************/
void fnet_eth_phy_init(fnet_fec_if_t *ethif)
{
FNET_COMP_UNUSED_ARG(ethif);
}
/* If vector table is in ROM, pre-installed FNET ISR for ENET Receive Frame interrupt*/
#if !FNET_CFG_CPU_VECTOR_TABLE_IS_IN_RAM
void ENET_Receive_IRQHandler (void)
{
FNET_ISR_HANDLER();
}
#endif
#endif /* FNET_MK && FNET_CFG_ETH */
|
607313.c | #include "secdesk.h"
static char *RESPONSE_FORMAT= "<!DOCTYPE html><html><body>%s<br><img height=\"200px\" src=\"%s\" id=\"myImage\" /></body></html>";
/* Set up command line interface and defaults */
static void initialize_cli(int argc, char const *argv[]) {
fio_cli_start(
argc, argv, 0, 0, NULL,
FIO_CLI_PRINT_HEADER("Address binding:"),
FIO_CLI_INT("-port -p port number to listen to. default: port 3000"),
FIO_CLI_STRING("-bind -b address to listen to. default: any available."),
FIO_CLI_PRINT_HEADER("Concurrency:"),
FIO_CLI_INT("-workers -w number of processes to use."),
FIO_CLI_INT("-threads -t number of threads per process."),
FIO_CLI_PRINT_HEADER("HTTP Server:"),
FIO_CLI_STRING("-public -www public folder, for static file service."),
FIO_CLI_INT("-keep-alive -k HTTP keep-alive timeout (0..255). default: ~5s"),
FIO_CLI_INT("-max-body -maxbd HTTP upload limit. default: ~50Mb"),
FIO_CLI_BOOL("-log -v request verbosity (logging)."),
FIO_CLI_PRINT_HEADER("Database:"),
FIO_CLI_STRING("-database -db Database file. default ./db/secdesk.db"));
if (!fio_cli_get("-b")) {
char *tmp = getenv("ADDRESS");
if (tmp) {
fio_cli_set("-b", tmp);
fio_cli_set("-bind", tmp);
}
}
if (!fio_cli_get("-p")) {
char *tmp = getenv("PORT");
if (!tmp && !fio_cli_get("-b")) tmp = "3000";
fio_cli_set("-p", tmp);
fio_cli_set("-port", tmp);
}
if (!fio_cli_get("-www")) {
char *tmp = getenv("HTTP_PUBLIC_FOLDER");
if (tmp) {
fio_cli_set("-public", tmp);
fio_cli_set("-www", tmp);
}
}
if (!fio_cli_get("-db")) {
char *tmp = getenv("DBURI");
if (!tmp) tmp = "./db/secdesk.db";
fio_cli_set("-database", tmp);
fio_cli_set("-db", tmp);
}
}
static int get_file(FIOBJ o, void *arg) {
struct secinput *s = arg;
if (o) {
char * key = fiobj_obj2cstr(fiobj_hash_key_in_loop()).data;
if (strcmp(key,"name") == 0) { s->filename = o; }
else if (strcmp(key,"data") == 0) { s->filedata = o; }
}
return 0;
}
static int get_fields(FIOBJ o, void *arg) {
struct secinput *s = arg;
if (o) {
char * key = fiobj_obj2cstr(fiobj_hash_key_in_loop()).data;
if (strcmp(key,"imageFile") == 0) { fiobj_each1(o, 0, get_file, arg); }
else if (strcmp(key,"fname") == 0) { s->fname = o; }
else if (strcmp(key,"mi") == 0) { s->mi = o; }
else if (strcmp(key,"lname") == 0) { s->lname = o; }
}
return 0;
}
static int process_secinput(struct secinput *s, char *overlayImageFile) {
fio_str_info_s tmp = fiobj_obj2cstr(s->filedata);
char *filename = fiobj_obj2cstr(s->filename).data;
char dir[256], tmpfile[512];
sprintf(dir, "%s/tmp", fio_cli_get("-www"));
mkdir(dir, 0777);
sprintf(tmpfile, "%s/secdesk_img_XXXXXX", dir);
FILE * fp = fdopen(mkstemp(tmpfile), "wb");
if (!fp) perror("Error opening tempfile");
if (fwrite(tmp.data, tmp.len, 1, fp) != 1) {
fprintf(stderr, "Error writing image file %s into %s\n", filename, tmpfile);
}
fclose(fp);
char tmp2[32] = "overlay_XXXXXX";
close(mkstemp(tmp2)); // returns fd open for writing, so closing
remove(tmp2); // remove temp file, png created with same name in www/tmp separately
sprintf(overlayImageFile, "%s/%s.png", dir, tmp2); // .png is necessary for python to find the right writer.
char *f, *m, *l;
f = strdup(fiobj_obj2cstr(s->fname).data);
m = strdup(fiobj_obj2cstr(s->mi).data);
l = strdup(fiobj_obj2cstr(s->lname).data);
double embedding[128];
get_features(tmpfile, embedding);
int i;
i = recognize(embedding);
int j;
j = lookup(f,m,l);
free(f); free(m); free(l);
overlay(tmpfile, overlayImageFile, i);
int n = strlen(fio_cli_get("-www")) + 1; // e.g. www/
int len = strlen(overlayImageFile);
memmove(overlayImageFile, overlayImageFile + n, len - n + 1);
remove(tmpfile);
return (i > 0 && j > 0 && i == j) ? 1 : 0;
}
static void on_http_request(http_s *h) {
#define ERRCLN(x) if(x) perror(x);http_send_error(h,404);goto cleanup;
http_parse_query(h);
if ((strcmp(fiobj_obj2cstr(h->path).data,"/check_person") != 0)
|| (strcmp(fiobj_obj2cstr(h->method).data,"POST") != 0)
|| (http_parse_body(h) == -1)) { ERRCLN("Invalid request") }
struct secinput s;
char overlayImageFile[512];
fiobj_each1(h->params, 0, get_fields, &s);
int rsp = process_secinput(&s, overlayImageFile);
char response[1024];
sprintf(response, RESPONSE_FORMAT, (rsp ? "ALLOWED!" : "DENIED!"), overlayImageFile);
http_send_body(h, response, strlen(response));
cleanup: http_finish(h); return;
}
void run_secdesk_service(int argc, char const *argv[]) {
initialize_cli(argc, argv);
if (http_listen(fio_cli_get("-p"), fio_cli_get("-b"),
.on_request = on_http_request,
.public_folder = fio_cli_get("-www"),
.timeout = fio_cli_get_i("-k"),
.max_body_size = fio_cli_get_i("-maxbd") * 1024 * 1024,
.log = fio_cli_get_bool("-v")) == -1) {
perror("ERROR: facil couldn't initialize HTTP service (already running?)");
exit(1);
}
const char *d = fio_cli_get("-db");
start_database(d);
start_imageprocessor();
start_recognizer();
fio_start(.threads = fio_cli_get_i("-t"), .workers = fio_cli_get_i("-w"));
stop_recognizer();
stop_imageprocessor();
stop_database();
fio_cli_end();
}
int main(int argc, char const **argv) {
run_secdesk_service(argc, argv);
return 0;
}
|
108418.c | /******************************************************************************
* *
* Copyright (C) 2018 The Android Open Source Project
*
* 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.
*
*****************************************************************************
* Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore
*/
#include <stdlib.h>
#include <math.h>
#include "ixheaacd_type_def.h"
#include "ixheaacd_bitbuffer.h"
#include "ixheaacd_interface.h"
#include "ixheaacd_tns_usac.h"
#include "ixheaacd_cnst.h"
#include "ixheaacd_acelp_info.h"
#include "ixheaacd_td_mdct.h"
#include "ixheaacd_sbrdecsettings.h"
#include "ixheaacd_info.h"
#include "ixheaacd_sbr_common.h"
#include "ixheaacd_drc_data_struct.h"
#include "ixheaacd_drc_dec.h"
#include "ixheaacd_sbrdecoder.h"
#include "ixheaacd_mps_polyphase.h"
#include "ixheaacd_sbr_const.h"
#include "ixheaacd_main.h"
#include "ixheaacd_arith_dec.h"
#include "ixheaacd_func_def.h"
#include "ixheaacd_constants.h"
#include "ixheaacd_basic_ops32.h"
#include "ixheaacd_basic_ops40.h"
extern const WORD32 ixheaacd_pre_post_twid_cos_sin_512[4][512];
extern const WORD32 ixheaacd_pre_post_twid_cos_sin_384[4][384];
extern const WORD32 ixheaacd_pre_post_twid_cos_sin_256[4][256];
extern const WORD32 ixheaacd_pre_post_twid_cos_sin_192[4][192];
extern const WORD32 ixheaacd_pre_post_twid_cos_sin_128[4][128];
extern const WORD32 ixheaacd_pre_post_twid_cos_sin_96[4][96];
extern const WORD32 ixheaacd_pre_post_twid_cos_sin_64[4][64];
extern const WORD32 ixheaacd_pre_post_twid_cos_sin_48[4][48];
extern const WORD32 ixheaacd_pre_post_twid_cos_sin_32[4][32];
extern const WORD32 ixheaacd_pre_post_twid_cos_sin_24[4][24];
static PLATFORM_INLINE WORD32 ixheaacd_mul_sub64_sat_32(WORD32 a, WORD32 b,
WORD32 c, WORD32 d) {
WORD64 diff;
WORD64 temp_result1;
WORD64 temp_result2;
temp_result1 = (WORD64)a * (WORD64)c;
temp_result2 = (WORD64)b * (WORD64)d;
diff = (temp_result1 - temp_result2) >> 32;
if (diff >= 2147483647)
diff = 2147483647;
else if (diff <= -2147483647 - 1)
diff = -2147483647 - 1;
return ((WORD32)diff);
}
static PLATFORM_INLINE WORD32 ixheaacd_mul_add64_sat_32(WORD32 a, WORD32 b,
WORD32 c, WORD32 d) {
WORD64 sum;
WORD64 temp_result1;
WORD64 temp_result2;
temp_result1 = (WORD64)a * (WORD64)c;
temp_result2 = (WORD64)b * (WORD64)d;
sum = (temp_result1 + temp_result2) >> 32;
if (sum >= 2147483647)
sum = 2147483647;
else if (sum <= -2147483647 - 1)
sum = -2147483647 - 1;
return ((WORD32)sum);
}
static void ixheaacd_pre_twid(WORD32 *in, WORD32 *r_ptr, WORD32 *i_ptr,
WORD32 nlength, const WORD32 *ptr_pre_cos_sin) {
WORD32 i;
const WORD32 *cos_ptr = &ptr_pre_cos_sin[0];
const WORD32 *sin_ptr = &ptr_pre_cos_sin[nlength];
for (i = 0; i < nlength; i += 4) {
*r_ptr++ = ixheaacd_mul_sub64_sat_32(in[i], in[nlength + i], cos_ptr[i],
sin_ptr[i]);
*i_ptr++ = ixheaacd_mul_add64_sat_32(in[i], in[nlength + i], sin_ptr[i],
cos_ptr[i]);
*r_ptr++ = ixheaacd_mul_sub64_sat_32(in[i + 1], in[nlength + i + 1],
cos_ptr[i + 1], sin_ptr[i + 1]);
*i_ptr++ = ixheaacd_mul_add64_sat_32(in[i + 1], in[nlength + i + 1],
sin_ptr[i + 1], cos_ptr[i + 1]);
*r_ptr++ = ixheaacd_mul_sub64_sat_32(in[i + 2], in[nlength + i + 2],
cos_ptr[i + 2], sin_ptr[i + 2]);
*i_ptr++ = ixheaacd_mul_add64_sat_32(in[i + 2], in[nlength + i + 2],
sin_ptr[i + 2], cos_ptr[i + 2]);
*r_ptr++ = ixheaacd_mul_sub64_sat_32(in[i + 3], in[nlength + i + 3],
cos_ptr[i + 3], sin_ptr[i + 3]);
*i_ptr++ = ixheaacd_mul_add64_sat_32(in[i + 3], in[nlength + i + 3],
sin_ptr[i + 3], cos_ptr[i + 3]);
}
}
static void ixheaacd_post_twid(WORD32 *data_re, WORD32 *data_im, WORD32 *out,
WORD32 nlength, const WORD32 *ptr_post_cos_sin) {
WORD32 i;
const WORD32 *cos_ptr = &ptr_post_cos_sin[nlength * 2];
const WORD32 *sin_ptr = &ptr_post_cos_sin[nlength * 3];
WORD32 *out_ptr = &out[2 * nlength - 1];
for (i = 0; i < nlength; i += 4) {
out[0] = ixheaacd_mul_sub64_sat_32(data_re[i], data_im[i], cos_ptr[i],
sin_ptr[i]);
out_ptr[0] = -ixheaacd_mul_add64_sat_32(data_re[i], data_im[i], sin_ptr[i],
cos_ptr[i]);
out[2] = ixheaacd_mul_sub64_sat_32(data_re[i + 1], data_im[i + 1],
cos_ptr[i + 1], sin_ptr[i + 1]);
out_ptr[-2] = -ixheaacd_mul_add64_sat_32(data_re[i + 1], data_im[i + 1],
sin_ptr[i + 1], cos_ptr[i + 1]);
out[4] = ixheaacd_mul_sub64_sat_32(data_re[i + 2], data_im[i + 2],
cos_ptr[i + 2], sin_ptr[i + 2]);
out_ptr[-4] = -ixheaacd_mul_add64_sat_32(data_re[i + 2], data_im[i + 2],
sin_ptr[i + 2], cos_ptr[i + 2]);
out[6] = ixheaacd_mul_sub64_sat_32(data_re[i + 3], data_im[i + 3],
cos_ptr[i + 3], sin_ptr[i + 3]);
out_ptr[-6] = -ixheaacd_mul_add64_sat_32(data_re[i + 3], data_im[i + 3],
sin_ptr[i + 3], cos_ptr[i + 3]);
out += 8;
out_ptr -= 8;
}
}
WORD32 ixheaacd_acelp_mdct(WORD32 *ptr_in, WORD32 *ptr_out, WORD32 *preshift,
WORD32 length, WORD32 *ptr_scratch) {
WORD32 *ptr_data_r = ptr_scratch;
WORD32 *ptr_data_i = ptr_scratch + 512;
const WORD32 *ptr_pre_post_twid;
WORD32 err = 0;
switch (length) {
case 1024:
ptr_pre_post_twid = &ixheaacd_pre_post_twid_cos_sin_512[0][0];
break;
case 768:
ptr_pre_post_twid = &ixheaacd_pre_post_twid_cos_sin_384[0][0];
break;
case 512:
ptr_pre_post_twid = &ixheaacd_pre_post_twid_cos_sin_256[0][0];
break;
case 384:
ptr_pre_post_twid = &ixheaacd_pre_post_twid_cos_sin_192[0][0];
break;
case 256:
ptr_pre_post_twid = &ixheaacd_pre_post_twid_cos_sin_128[0][0];
break;
case 192:
ptr_pre_post_twid = &ixheaacd_pre_post_twid_cos_sin_96[0][0];
break;
case 128:
ptr_pre_post_twid = &ixheaacd_pre_post_twid_cos_sin_64[0][0];
break;
case 96:
ptr_pre_post_twid = &ixheaacd_pre_post_twid_cos_sin_48[0][0];
break;
case 64:
ptr_pre_post_twid = &ixheaacd_pre_post_twid_cos_sin_32[0][0];
break;
case 48:
ptr_pre_post_twid = &ixheaacd_pre_post_twid_cos_sin_24[0][0];
break;
default:
ptr_pre_post_twid = &ixheaacd_pre_post_twid_cos_sin_24[0][0];
break;
}
ixheaacd_pre_twid(ptr_in, ptr_data_r, ptr_data_i, length / 2,
ptr_pre_post_twid);
err = ixheaacd_complex_fft(ptr_data_r, ptr_data_i, length / 2, -1, preshift);
if (err) return err;
*preshift += 1;
ixheaacd_post_twid(ptr_data_r, ptr_data_i, ptr_out, length / 2,
ptr_pre_post_twid);
*preshift += 1;
return err;
}
WORD32 ixheaacd_acelp_mdct_main(ia_usac_data_struct *usac_data, WORD32 *in,
WORD32 *out, WORD32 l, WORD32 m,
WORD32 *preshift) {
WORD32 i;
WORD32 *ptr_scratch = &usac_data->scratch_buffer[0];
WORD32 *output_buffer = &usac_data->x_ac_dec[0];
WORD32 err = 0;
err = ixheaacd_acelp_mdct(in, output_buffer, preshift, l + m, ptr_scratch);
if (err == -1) return err;
for (i = 0; i < m / 2; i++) {
out[l + m / 2 - 1 - i] = -output_buffer[m / 2 + l / 2 + i];
}
for (i = 0; i < l / 2; i++) {
out[i] = output_buffer[m + l / 2 + i];
out[l - 1 - i] = -output_buffer[m + l / 2 + i];
}
for (i = 0; i < m / 2; i++) {
out[l + m / 2 + i] = -output_buffer[m / 2 + l / 2 - 1 - i];
}
for (i = 0; i < l / 2; i++) {
out[l + m + i] = -output_buffer[l / 2 - 1 - i];
out[2 * l + m - 1 - i] = -output_buffer[l / 2 - 1 - i];
}
return err;
}
|
729420.c | #include<stdio.h>
#include<math.h>
float fun(float x){
float y=(3*x)-cos(x)-1;
return y;
}
float diff(float x){
float y=3+sin(x);
return y;
}
int main(){
float y,d,x=0.5;
int i;
for(i=0;i<5;i++){
y=x-(fun(x)/diff(x));
printf("x%d = %f\nf(x%d) = %f\n\n",i+1,y,i+1,fun(y));
if((x>y && (x-y)<0.0001) || (x<y && (y-x)<0.0001)){
break;
}
x=y;
}
printf("Root is %0.3f\n",y);
}
|
96906.c | #include <stdio.h>
#include <assert.h>
#include "search.h"
/// \author Binh Nguyen Duc
/// \brief module finds MIN value of a[0]*a[1], a[1]*a[2],..., a[N-2]*a[N-1]
/// where a - const array. Use library "search.h"
/// \param[in] a - array, pe - pointer to right border
/// \param[out] minimum value
int execute(const int *a, const int *pe) // main
{
assert(pe - a >= 2); // check number elements
int best, cur;
const int *p;
p = pe-1;
best = *p;
best *= *(p-1);
for(p = pe - 1; p > a; p--)
{
cur = *p; cur *= *(p-1);
best = (best < cur)? best : cur; // count min
}
return best;
} |
39144.c | #include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <gencon-impl.h>
#include <parRSB.h>
int PRE_TO_SYM_VERTEX[GC_MAX_VERTICES] = {0, 1, 3, 2, 4, 5, 7, 6};
int PRE_TO_SYM_FACE[GC_MAX_FACES] = {2, 1, 3, 0, 4, 5};
#define check_error(id, err, msg) \
do { \
if (err > 0) { \
if (id == 0) \
printf("\n Error: %s\n", msg); \
buffer_free(&bfr); \
mesh_free(mesh); \
comm_free(&c); \
return err; \
} \
} while (0)
static int transferBoundaryFaces(Mesh mesh, struct comm *c) {
uint size = c->np;
struct array *boundary = &mesh->boundary;
BoundaryFace ptr = boundary->ptr;
int nFaces = boundary->n;
slong nelgt = mesh->nelgt;
sint nelt = nelgt / size;
sint nrem = nelgt - nelt * size;
slong N = (size - nrem) * nelt;
sint i;
slong eid;
for (i = 0; i < nFaces; i++) {
eid = ptr[i].elementId;
if (eid < N)
ptr[i].proc = eid / nelt;
else
ptr[i].proc = (eid - N) / (nelt + 1) + size - nrem;
}
struct crystal cr;
crystal_init(&cr, c);
sarray_transfer(struct Boundary_private, boundary, proc, 1, &cr);
crystal_free(&cr);
return 0;
}
/*
* coord [nelt, nv, ndim] - in, vertices are in preprocessor ordering
* vtx[nelt, nv] - out
* nv = 8 if ndim == 3 or nv = 4 if ndim = 2
*/
int parrsb_find_conn(long long *vtx, double *coord, int nelt, int ndim,
long long *periodicInfo, int nPeriodicFaces, double tol,
MPI_Comm comm, int verbose) {
struct comm c;
comm_init(&c, comm);
int rank = c.id;
int size = c.np;
if (rank == 0) {
printf("Running parCon ... (tol=%g)\n", tol);
fflush(stdout);
}
genmap_barrier(&c);
double tcon = comm_time();
Mesh mesh;
mesh_init(&mesh, nelt, ndim);
slong out[2][1], buff[2][1];
slong in = nelt;
comm_scan(out, &c, gs_long, gs_add, &in, 1, buff);
ulong start = out[0][0];
ulong nelgt = out[1][0];
mesh->nelgt = mesh->nelgv = nelgt;
int nelt_ = nelgt / size;
int nrem = nelgt - nelt_ * size;
if (rank >= (size - nrem))
nelt_++;
assert(nelt == nelt_);
int nvertex = mesh->nVertex;
uint nunits = nvertex * nelt;
struct Point_private p;
uint i, j, k, l;
for (i = 0; i < nelt; i++) {
for (k = 0; k < nvertex; k++) {
j = PRE_TO_SYM_VERTEX[k];
for (l = 0; l < ndim; l++)
p.x[l] = coord[i * nvertex * ndim + j * ndim + l];
p.elementId = start + i;
p.sequenceId = nvertex * (start + i) + k;
p.origin = rank;
array_cat(struct Point_private, &mesh->elements, &p, 1);
}
}
assert(mesh->elements.n == nunits);
struct Boundary_private b;
for (i = 0; i < nPeriodicFaces; i++) {
b.elementId = periodicInfo[4 * i + 0] - 1;
b.faceId = PRE_TO_SYM_FACE[periodicInfo[4 * i + 1] - 1];
b.bc[0] = periodicInfo[4 * i + 2] - 1;
b.bc[1] = PRE_TO_SYM_FACE[periodicInfo[4 * i + 3] - 1];
array_cat(struct Boundary_private, &mesh->boundary, &b, 1);
}
assert(mesh->boundary.n == nPeriodicFaces);
buffer bfr;
buffer_init(&bfr, 1024);
sint err, buf;
err = transferBoundaryFaces(mesh, &c);
comm_allreduce(&c, gs_int, gs_max, &err, 1, &buf);
check_error(rank, err, "transferBoundaryFaces");
err = findMinNeighborDistance(mesh);
comm_allreduce(&c, gs_int, gs_max, &err, 1, &buf);
check_error(rank, err, "findMinNeighborDistance");
err = findUniqueVertices(mesh, &c, tol, verbose, &bfr);
comm_allreduce(&c, gs_int, gs_max, &err, 1, &buf);
check_error(rank, err, "findSegments");
setGlobalID(mesh, &c);
sendBack(mesh, &c, &bfr);
err = elementCheck(mesh, &c, &bfr);
comm_allreduce(&c, gs_int, gs_max, &err, 1, &buf);
check_error(rank, err, "elementCheck");
err = faceCheck(mesh, &c, &bfr);
comm_allreduce(&c, gs_int, gs_max, &err, 1, &buf);
check_error(rank, err, "faceCheck");
err = matchPeriodicFaces(mesh, &c, &bfr);
comm_allreduce(&c, gs_int, gs_max, &err, 1, &buf);
check_error(rank, err, "matchPeriodicFaces");
/* Copy output */
Point ptr = mesh->elements.ptr;
for (i = 0; i < nelt; i++) {
// printf("e = %d, ", i);
for (j = 0; j < nvertex; j++) {
vtx[i * nvertex + j] = ptr[i * nvertex + j].globalId + 1;
// printf("%lld ", vtx[i * nvertex + j]);
}
// printf("\n");
}
/* Report time and finish */
genmap_barrier(&c);
tcon = comm_time() - tcon;
if (rank == 0 && verbose > 0) {
printf("parCon finished in %g s\n", tcon);
fflush(stdout);
}
buffer_free(&bfr);
mesh_free(mesh);
comm_free(&c);
return err;
}
void fparrsb_find_conn(long long *vtx, double *coord, int *nelt, int *ndim,
long long *periodicInfo, int *nPeriodicFaces,
double *tol, MPI_Fint *fcomm, int *verbose, int *err) {
*err = 1;
MPI_Comm c = MPI_Comm_f2c(*fcomm);
*err = parrsb_find_conn(vtx, coord, *nelt, *ndim, periodicInfo,
*nPeriodicFaces, *tol, c, *verbose);
}
|
569672.c | /* *********************************************************************
* Broadcom Common Firmware Environment (CFE)
*
* Board device initialization File: littlesur_pci.c
*
* This is the part of the board support package for boards
* that support PCI. It describes the board-specific slots/devices
* and wiring thereof.
*
*********************************************************************
*
* Copyright 2000,2001,2002,2003
* Broadcom Corporation. All rights reserved.
*
* This software is furnished under license and may be used and
* copied only in accordance with the following terms and
* conditions. Subject to these conditions, you may download,
* copy, install, use, modify and distribute modified or unmodified
* copies of this software in source and/or binary form. No title
* or ownership is transferred hereby.
*
* 1) Any source code used, modified or distributed must reproduce
* and retain this copyright notice and list of conditions
* as they appear in the source file.
*
* 2) No right is granted to use any trade name, trademark, or
* logo of Broadcom Corporation. The "Broadcom Corporation"
* name may not be used to endorse or promote products derived
* from this software without the prior written permission of
* Broadcom Corporation.
*
* 3) THIS SOFTWARE IS PROVIDED "AS-IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING BUT NOT LIMITED TO, ANY IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT
* SHALL BROADCOM BE LIABLE FOR ANY DAMAGES WHATSOEVER, AND IN
* PARTICULAR, BROADCOM SHALL NOT BE LIABLE FOR 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), EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
********************************************************************* */
#include "lib_types.h"
#include "pcireg.h"
#include "pcivar.h"
/* PCI interrupt mapping on the Littlesur (BCM912500E) board:
The Littlesur is wired for PCI Device mode and has no interrupt inputs.
*/
/* Return the base shift of a slot or device on the motherboard.
This is board specific, for the Littlesur only. */
uint8_t
pci_int_shift_0(pcitag_t tag)
{
return 0;
}
/* Return the mapping of a littlesur device/function interrupt to an
interrupt line. For the SB-1250, return 1-4 to indicate the
pci_inta - pci_intd inputs to the interrupt mapper, respectively,
or 0 if there is no mapping. */
uint8_t
pci_int_map_0(pcitag_t tag)
{
return 0;
}
|
266179.c | /*-
* Copyright (c) 1998 Michael Smith ([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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");
#include <stand.h>
#include <bootstrap.h>
#include <machine/cpufunc.h>
#include <dev/ic/ns16550.h>
#include <dev/pci/pcireg.h>
#include "libi386.h"
#define COMC_FMT 0x3 /* 8N1 */
#define COMC_TXWAIT 0x40000 /* transmit timeout */
#define COMC_BPS(x) (115200 / (x)) /* speed to DLAB divisor */
#define COMC_DIV2BPS(x) (115200 / (x)) /* DLAB divisor to speed */
#ifndef COMPORT
#define COMPORT 0x3f8
#endif
#ifndef COMSPEED
#define COMSPEED 9600
#endif
static void comc_probe(struct console *cp);
static int comc_init(int arg);
static void comc_putchar(int c);
static int comc_getchar(void);
static int comc_getspeed(void);
static int comc_ischar(void);
static int comc_parseint(const char *string);
static uint32_t comc_parse_pcidev(const char *string);
static int comc_pcidev_set(struct env_var *ev, int flags,
const void *value);
static int comc_pcidev_handle(uint32_t locator);
static int comc_port_set(struct env_var *ev, int flags,
const void *value);
static void comc_setup(int speed, int port);
static int comc_speed_set(struct env_var *ev, int flags,
const void *value);
static int comc_curspeed;
static int comc_port = COMPORT;
static uint32_t comc_locator;
struct console comconsole = {
.c_name = "comconsole",
.c_desc = "serial port",
.c_flags = 0,
.c_probe = comc_probe,
.c_init = comc_init,
.c_out = comc_putchar,
.c_in = comc_getchar,
.c_ready = comc_ischar
};
static void
comc_probe(struct console *cp)
{
char intbuf[16];
char *cons, *env;
int speed, port;
uint32_t locator;
if (comc_curspeed == 0) {
comc_curspeed = COMSPEED;
/*
* Assume that the speed was set by an earlier boot loader if
* comconsole is already the preferred console.
*/
cons = getenv("console");
if ((cons != NULL && strcmp(cons, comconsole.c_name) == 0) ||
getenv("boot_multicons") != NULL) {
comc_curspeed = comc_getspeed();
}
env = getenv("comconsole_speed");
if (env != NULL) {
speed = comc_parseint(env);
if (speed > 0)
comc_curspeed = speed;
}
sprintf(intbuf, "%d", comc_curspeed);
unsetenv("comconsole_speed");
env_setenv("comconsole_speed", EV_VOLATILE, intbuf,
comc_speed_set, env_nounset);
env = getenv("comconsole_port");
if (env != NULL) {
port = comc_parseint(env);
if (port > 0)
comc_port = port;
}
sprintf(intbuf, "%d", comc_port);
unsetenv("comconsole_port");
env_setenv("comconsole_port", EV_VOLATILE, intbuf,
comc_port_set, env_nounset);
env = getenv("comconsole_pcidev");
if (env != NULL) {
locator = comc_parse_pcidev(env);
if (locator != 0)
comc_pcidev_handle(locator);
}
unsetenv("comconsole_pcidev");
env_setenv("comconsole_pcidev", EV_VOLATILE, env,
comc_pcidev_set, env_nounset);
}
comc_setup(comc_curspeed, comc_port);
}
static int
comc_init(int arg)
{
comc_setup(comc_curspeed, comc_port);
if ((comconsole.c_flags & (C_PRESENTIN | C_PRESENTOUT)) ==
(C_PRESENTIN | C_PRESENTOUT))
return (CMD_OK);
return (CMD_ERROR);
}
static void
comc_putchar(int c)
{
int wait;
for (wait = COMC_TXWAIT; wait > 0; wait--)
if (inb(comc_port + com_lsr) & LSR_TXRDY) {
outb(comc_port + com_data, (u_char)c);
break;
}
}
static int
comc_getchar(void)
{
return (comc_ischar() ? inb(comc_port + com_data) : -1);
}
static int
comc_ischar(void)
{
return (inb(comc_port + com_lsr) & LSR_RXRDY);
}
static int
comc_speed_set(struct env_var *ev, int flags, const void *value)
{
int speed;
if (value == NULL || (speed = comc_parseint(value)) <= 0) {
printf("Invalid speed\n");
return (CMD_ERROR);
}
if (comc_curspeed != speed)
comc_setup(speed, comc_port);
env_setenv(ev->ev_name, flags | EV_NOHOOK, value, NULL, NULL);
return (CMD_OK);
}
static int
comc_port_set(struct env_var *ev, int flags, const void *value)
{
int port;
if (value == NULL || (port = comc_parseint(value)) <= 0) {
printf("Invalid port\n");
return (CMD_ERROR);
}
if (comc_port != port)
comc_setup(comc_curspeed, port);
env_setenv(ev->ev_name, flags | EV_NOHOOK, value, NULL, NULL);
return (CMD_OK);
}
/*
* Input: bus:dev:func[:bar]. If bar is not specified, it is 0x10.
* Output: bar[24:16] bus[15:8] dev[7:3] func[2:0]
*/
static uint32_t
comc_parse_pcidev(const char *string)
{
#ifdef EFI
/* We don't support PCI in EFI yet */
return (0);
#else
char *p, *p1;
uint8_t bus, dev, func, bar;
uint32_t locator;
int pres;
pres = strtol(string, &p, 0);
if (p == string || *p != ':' || pres < 0 )
return (0);
bus = pres;
p1 = ++p;
pres = strtol(p1, &p, 0);
if (p == string || *p != ':' || pres < 0 )
return (0);
dev = pres;
p1 = ++p;
pres = strtol(p1, &p, 0);
if (p == string || (*p != ':' && *p != '\0') || pres < 0 )
return (0);
func = pres;
if (*p == ':') {
p1 = ++p;
pres = strtol(p1, &p, 0);
if (p == string || *p != '\0' || pres <= 0 )
return (0);
bar = pres;
} else
bar = 0x10;
locator = (bar << 16) | biospci_locator(bus, dev, func);
return (locator);
#endif
}
static int
comc_pcidev_handle(uint32_t locator)
{
#ifdef EFI
/* We don't support PCI in EFI yet */
return (CMD_ERROR);
#else
char intbuf[64];
uint32_t port;
if (biospci_read_config(locator & 0xffff,
(locator & 0xff0000) >> 16, BIOSPCI_32BITS, &port) == -1) {
printf("Cannot read bar at 0x%x\n", locator);
return (CMD_ERROR);
}
/*
* biospci_read_config() sets port == 0xffffffff if the pcidev
* isn't found on the bus. Check for 0xffffffff and return to not
* panic in BTX.
*/
if (port == 0xffffffff) {
printf("Cannot find specified pcidev\n");
return (CMD_ERROR);
}
if (!PCI_BAR_IO(port)) {
printf("Memory bar at 0x%x\n", locator);
return (CMD_ERROR);
}
port &= PCIM_BAR_IO_BASE;
sprintf(intbuf, "%d", port);
unsetenv("comconsole_port");
env_setenv("comconsole_port", EV_VOLATILE, intbuf,
comc_port_set, env_nounset);
comc_setup(comc_curspeed, port);
comc_locator = locator;
return (CMD_OK);
#endif
}
static int
comc_pcidev_set(struct env_var *ev, int flags, const void *value)
{
uint32_t locator;
int error;
if (value == NULL || (locator = comc_parse_pcidev(value)) <= 0) {
printf("Invalid pcidev\n");
return (CMD_ERROR);
}
if ((comconsole.c_flags & (C_ACTIVEIN | C_ACTIVEOUT)) != 0 &&
comc_locator != locator) {
error = comc_pcidev_handle(locator);
if (error != CMD_OK)
return (error);
}
env_setenv(ev->ev_name, flags | EV_NOHOOK, value, NULL, NULL);
return (CMD_OK);
}
static void
comc_setup(int speed, int port)
{
static int TRY_COUNT = 1000000;
char intbuf[64];
int tries;
unsetenv("hw.uart.console");
comc_curspeed = speed;
comc_port = port;
if ((comconsole.c_flags & (C_ACTIVEIN | C_ACTIVEOUT)) == 0)
return;
outb(comc_port + com_cfcr, CFCR_DLAB | COMC_FMT);
outb(comc_port + com_dlbl, COMC_BPS(speed) & 0xff);
outb(comc_port + com_dlbh, COMC_BPS(speed) >> 8);
outb(comc_port + com_cfcr, COMC_FMT);
outb(comc_port + com_mcr, MCR_RTS | MCR_DTR);
tries = 0;
do
inb(comc_port + com_data);
while (inb(comc_port + com_lsr) & LSR_RXRDY && ++tries < TRY_COUNT);
if (tries < TRY_COUNT) {
comconsole.c_flags |= (C_PRESENTIN | C_PRESENTOUT);
sprintf(intbuf, "io:%d,br:%d", comc_port, comc_curspeed);
env_setenv("hw.uart.console", EV_VOLATILE, intbuf, NULL, NULL);
} else
comconsole.c_flags &= ~(C_PRESENTIN | C_PRESENTOUT);
}
static int
comc_parseint(const char *speedstr)
{
char *p;
int speed;
speed = strtol(speedstr, &p, 0);
if (p == speedstr || *p != '\0' || speed <= 0)
return (-1);
return (speed);
}
static int
comc_getspeed(void)
{
u_int divisor;
u_char dlbh;
u_char dlbl;
u_char cfcr;
cfcr = inb(comc_port + com_cfcr);
outb(comc_port + com_cfcr, CFCR_DLAB | cfcr);
dlbl = inb(comc_port + com_dlbl);
dlbh = inb(comc_port + com_dlbh);
outb(comc_port + com_cfcr, cfcr);
divisor = dlbh << 8 | dlbl;
/* XXX there should be more sanity checking. */
if (divisor == 0)
return (COMSPEED);
return (COMC_DIV2BPS(divisor));
}
|
982971.c | //*****************************************************************************
//
// startup_gcc.c - Startup code for use with GNU tools.
//
// Copyright (c) 2013-2017 Texas Instruments Incorporated. All rights reserved.
// Software License Agreement
//
// Texas Instruments (TI) is supplying this software for use solely and
// exclusively on TI's microcontroller products. The software is owned by
// TI and/or its suppliers, and is protected under applicable copyright
// laws. You may not combine this software with "viral" open-source
// software in order to form a larger program.
//
// THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS.
// NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT
// NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY
// CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
// DAMAGES, FOR ANY REASON WHATSOEVER.
//
// This is part of revision 2.1.4.178 of the EK-TM4C123GXL Firmware Package.
//
//*****************************************************************************
#include <stdint.h>
#include "inc/hw_nvic.h"
#include "inc/hw_types.h"
//*****************************************************************************
//
// Forward declaration of the default fault handlers.
//
//*****************************************************************************
void ResetISR(void);
static void NmiSR(void);
static void FaultISR(void);
static void IntDefaultHandler(void);
//*****************************************************************************
//
// External declarations for the interrupt handlers used by the application.
//
//*****************************************************************************
extern void IntGPIOb(void);
extern void MPU9150I2CIntHandler(void);
extern void UARTStdioIntHandler(void);
extern void RGBBlinkIntHandler(void);
//*****************************************************************************
//
// The entry point for the application.
//
//*****************************************************************************
extern int main(void);
//*****************************************************************************
//
// Reserve space for the system stack.
//
//*****************************************************************************
static uint32_t pui32Stack[256];
//*****************************************************************************
//
// The vector table. Note that the proper constructs must be placed on this to
// ensure that it ends up at physical address 0x0000.0000.
//
//*****************************************************************************
__attribute__ ((section(".isr_vector")))
void (* const g_pfnVectors[])(void) =
{
(void (*)(void))((uint32_t)pui32Stack + sizeof(pui32Stack)),
// The initial stack pointer
ResetISR, // The reset handler
NmiSR, // The NMI handler
FaultISR, // The hard fault handler
IntDefaultHandler, // The MPU fault handler
IntDefaultHandler, // The bus fault handler
IntDefaultHandler, // The usage fault handler
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
IntDefaultHandler, // SVCall handler
IntDefaultHandler, // Debug monitor handler
0, // Reserved
IntDefaultHandler, // The PendSV handler
IntDefaultHandler, // The SysTick handler
IntDefaultHandler, // GPIO Port A
IntGPIOb, // GPIO Port B
IntDefaultHandler, // GPIO Port C
IntDefaultHandler, // GPIO Port D
IntDefaultHandler, // GPIO Port E
UARTStdioIntHandler, // UART0 Rx and Tx
IntDefaultHandler, // UART1 Rx and Tx
IntDefaultHandler, // SSI0 Rx and Tx
IntDefaultHandler, // I2C0 Master and Slave
IntDefaultHandler, // PWM Fault
IntDefaultHandler, // PWM Generator 0
IntDefaultHandler, // PWM Generator 1
IntDefaultHandler, // PWM Generator 2
IntDefaultHandler, // Quadrature Encoder 0
IntDefaultHandler, // ADC Sequence 0
IntDefaultHandler, // ADC Sequence 1
IntDefaultHandler, // ADC Sequence 2
IntDefaultHandler, // ADC Sequence 3
IntDefaultHandler, // Watchdog timer
IntDefaultHandler, // Timer 0 subtimer A
IntDefaultHandler, // Timer 0 subtimer B
IntDefaultHandler, // Timer 1 subtimer A
IntDefaultHandler, // Timer 1 subtimer B
IntDefaultHandler, // Timer 2 subtimer A
IntDefaultHandler, // Timer 2 subtimer B
IntDefaultHandler, // Analog Comparator 0
IntDefaultHandler, // Analog Comparator 1
IntDefaultHandler, // Analog Comparator 2
IntDefaultHandler, // System Control (PLL, OSC, BO)
IntDefaultHandler, // FLASH Control
IntDefaultHandler, // GPIO Port F
IntDefaultHandler, // GPIO Port G
IntDefaultHandler, // GPIO Port H
IntDefaultHandler, // UART2 Rx and Tx
IntDefaultHandler, // SSI1 Rx and Tx
IntDefaultHandler, // Timer 3 subtimer A
IntDefaultHandler, // Timer 3 subtimer B
IntDefaultHandler, // I2C1 Master and Slave
IntDefaultHandler, // Quadrature Encoder 1
IntDefaultHandler, // CAN0
IntDefaultHandler, // CAN1
0, // Reserved
0, // Reserved
IntDefaultHandler, // Hibernate
IntDefaultHandler, // USB0
IntDefaultHandler, // PWM Generator 3
IntDefaultHandler, // uDMA Software Transfer
IntDefaultHandler, // uDMA Error
IntDefaultHandler, // ADC1 Sequence 0
IntDefaultHandler, // ADC1 Sequence 1
IntDefaultHandler, // ADC1 Sequence 2
IntDefaultHandler, // ADC1 Sequence 3
0, // Reserved
0, // Reserved
IntDefaultHandler, // GPIO Port J
IntDefaultHandler, // GPIO Port K
IntDefaultHandler, // GPIO Port L
IntDefaultHandler, // SSI2 Rx and Tx
IntDefaultHandler, // SSI3 Rx and Tx
IntDefaultHandler, // UART3 Rx and Tx
IntDefaultHandler, // UART4 Rx and Tx
IntDefaultHandler, // UART5 Rx and Tx
IntDefaultHandler, // UART6 Rx and Tx
IntDefaultHandler, // UART7 Rx and Tx
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
IntDefaultHandler, // I2C2 Master and Slave
MPU9150I2CIntHandler, // I2C3 Master and Slave
IntDefaultHandler, // Timer 4 subtimer A
IntDefaultHandler, // Timer 4 subtimer B
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
IntDefaultHandler, // Timer 5 subtimer A
IntDefaultHandler, // Timer 5 subtimer B
IntDefaultHandler, // Wide Timer 0 subtimer A
IntDefaultHandler, // Wide Timer 0 subtimer B
IntDefaultHandler, // Wide Timer 1 subtimer A
IntDefaultHandler, // Wide Timer 1 subtimer B
IntDefaultHandler, // Wide Timer 2 subtimer A
IntDefaultHandler, // Wide Timer 2 subtimer B
IntDefaultHandler, // Wide Timer 3 subtimer A
IntDefaultHandler, // Wide Timer 3 subtimer B
IntDefaultHandler, // Wide Timer 4 subtimer A
IntDefaultHandler, // Wide Timer 4 subtimer B
IntDefaultHandler, // Wide Timer 5 subtimer A
RGBBlinkIntHandler, // Wide Timer 5 subtimer B
IntDefaultHandler, // FPU
0, // Reserved
0, // Reserved
IntDefaultHandler, // I2C4 Master and Slave
IntDefaultHandler, // I2C5 Master and Slave
IntDefaultHandler, // GPIO Port M
IntDefaultHandler, // GPIO Port N
IntDefaultHandler, // Quadrature Encoder 2
0, // Reserved
0, // Reserved
IntDefaultHandler, // GPIO Port P (Summary or P0)
IntDefaultHandler, // GPIO Port P1
IntDefaultHandler, // GPIO Port P2
IntDefaultHandler, // GPIO Port P3
IntDefaultHandler, // GPIO Port P4
IntDefaultHandler, // GPIO Port P5
IntDefaultHandler, // GPIO Port P6
IntDefaultHandler, // GPIO Port P7
IntDefaultHandler, // GPIO Port Q (Summary or Q0)
IntDefaultHandler, // GPIO Port Q1
IntDefaultHandler, // GPIO Port Q2
IntDefaultHandler, // GPIO Port Q3
IntDefaultHandler, // GPIO Port Q4
IntDefaultHandler, // GPIO Port Q5
IntDefaultHandler, // GPIO Port Q6
IntDefaultHandler, // GPIO Port Q7
IntDefaultHandler, // GPIO Port R
IntDefaultHandler, // GPIO Port S
IntDefaultHandler, // PWM 1 Generator 0
IntDefaultHandler, // PWM 1 Generator 1
IntDefaultHandler, // PWM 1 Generator 2
IntDefaultHandler, // PWM 1 Generator 3
IntDefaultHandler // PWM 1 Fault
};
//*****************************************************************************
//
// The following are constructs created by the linker, indicating where the
// the "data" and "bss" segments reside in memory. The initializers for the
// for the "data" segment resides immediately following the "text" segment.
//
//*****************************************************************************
extern uint32_t _ldata;
extern uint32_t _data;
extern uint32_t _edata;
extern uint32_t _bss;
extern uint32_t _ebss;
//*****************************************************************************
//
// This is the code that gets called when the processor first starts execution
// following a reset event. Only the absolutely necessary set is performed,
// after which the application supplied entry() routine is called. Any fancy
// actions (such as making decisions based on the reset cause register, and
// resetting the bits in that register) are left solely in the hands of the
// application.
//
//*****************************************************************************
void
ResetISR(void)
{
uint32_t *pui32Src, *pui32Dest;
//
// Copy the data segment initializers from flash to SRAM.
//
pui32Src = &_ldata;
for(pui32Dest = &_data; pui32Dest < &_edata; )
{
*pui32Dest++ = *pui32Src++;
}
//
// Zero fill the bss segment.
//
__asm(" ldr r0, =_bss\n"
" ldr r1, =_ebss\n"
" mov r2, #0\n"
" .thumb_func\n"
"zero_loop:\n"
" cmp r0, r1\n"
" it lt\n"
" strlt r2, [r0], #4\n"
" blt zero_loop");
//
// Enable the floating-point unit. This must be done here to handle the
// case where main() uses floating-point and the function prologue saves
// floating-point registers (which will fault if floating-point is not
// enabled). Any configuration of the floating-point unit using DriverLib
// APIs must be done here prior to the floating-point unit being enabled.
//
// Note that this does not use DriverLib since it might not be included in
// this project.
//
HWREG(NVIC_CPAC) = ((HWREG(NVIC_CPAC) &
~(NVIC_CPAC_CP10_M | NVIC_CPAC_CP11_M)) |
NVIC_CPAC_CP10_FULL | NVIC_CPAC_CP11_FULL);
//
// Call the application's entry point.
//
main();
}
//*****************************************************************************
//
// This is the code that gets called when the processor receives a NMI. This
// simply enters an infinite loop, preserving the system state for examination
// by a debugger.
//
//*****************************************************************************
static void
NmiSR(void)
{
//
// Enter an infinite loop.
//
while(1)
{
}
}
//*****************************************************************************
//
// This is the code that gets called when the processor receives a fault
// interrupt. This simply enters an infinite loop, preserving the system state
// for examination by a debugger.
//
//*****************************************************************************
static void
FaultISR(void)
{
//
// Enter an infinite loop.
//
while(1)
{
}
}
//*****************************************************************************
//
// This is the code that gets called when the processor receives an unexpected
// interrupt. This simply enters an infinite loop, preserving the system state
// for examination by a debugger.
//
//*****************************************************************************
static void
IntDefaultHandler(void)
{
//
// Go into an infinite loop.
//
while(1)
{
}
}
|
390506.c | #include <linux/module.h>
#include <linux/vermagic.h>
#include <linux/compiler.h>
MODULE_INFO(vermagic, VERMAGIC_STRING);
__visible struct module __this_module
__attribute__((section(".gnu.linkonce.this_module"))) = {
.name = KBUILD_MODNAME,
.init = init_module,
#ifdef CONFIG_MODULE_UNLOAD
.exit = cleanup_module,
#endif
.arch = MODULE_ARCH_INIT,
};
MODULE_INFO(intree, "Y");
static const char __module_depends[]
__used
__attribute__((section(".modinfo"))) =
"depends=snd-pcm,snd,snd-page-alloc,snd-hda-codec";
MODULE_ALIAS("pci:v00008086d00001C20sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00008086d00001D20sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00008086d00001E20sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00008086d00008C20sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00008086d00008D20sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00008086d00008D21sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00008086d00009C20sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00008086d00009C21sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00008086d00000A0Csv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00008086d00000C0Csv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00008086d00000D0Csv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00008086d00003B56sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00008086d0000811Bsv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00008086d0000080Asv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00008086d00000F04sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00008086d00002668sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00008086d000027D8sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00008086d0000269Asv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00008086d0000284Bsv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00008086d0000293Esv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00008086d0000293Fsv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00008086d00003A3Esv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00008086d00003A6Esv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00008086d*sv*sd*bc04sc03i00*");
MODULE_ALIAS("pci:v00001002d0000437Bsv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00001002d00004383sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00001022d0000780Dsv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00001002d0000793Bsv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00001002d00007919sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00001002d0000960Fsv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00001002d0000970Fsv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00001002d0000AA00sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00001002d0000AA08sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00001002d0000AA10sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00001002d0000AA18sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00001002d0000AA20sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00001002d0000AA28sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00001002d0000AA30sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00001002d0000AA38sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00001002d0000AA40sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00001002d0000AA48sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00001002d00009902sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00001002d0000AAA0sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00001002d0000AAA8sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00001002d0000AAB0sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00001106d00003288sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00001106d00009170sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00001106d00009140sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00001039d00007502sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v000010B9d00005461sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v000010DEd*sv*sd*bc04sc03i00*");
MODULE_ALIAS("pci:v00006549d00001200sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00006549d00002200sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00001102d00000010sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00001102d00000012sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00001102d00000009sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v000017F3d00003010sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v000015ADd00001977sv*sd*bc*sc*i*");
MODULE_ALIAS("pci:v00001002d*sv*sd*bc04sc03i00*");
MODULE_ALIAS("pci:v00001022d*sv*sd*bc04sc03i00*");
|
158850.c | /**************************************************************************//**
* @file main.c
* @version V3.00
* @brief
* Show how to control SMBus interface and use SMBus protocol between Host and Slave.
*
* @copyright SPDX-License-Identifier: Apache-2.0
* @copyright Copyright (C) 2021 Nuvoton Technology Corp. All rights reserved.
******************************************************************************/
#include <stdio.h>
#include "NuMicro.h"
#define SMBUS_ALERT_RESPONSE_ADDRESS 0x0C
#define SMBUS_DEFAULT_ADDRESS 0x61
#define ARP_COMMAND 0x01
/*---------------------------------------------------------------------------------------------------------*/
/* Global variables */
/*---------------------------------------------------------------------------------------------------------*/
const uint8_t g_u8MasterAddr[4] = {0x15, 0x35, 0x55, 0x75};
const uint8_t g_u8SlaveAddr[4] = {0x18, 0x38, 0x58, 0x78};
uint32_t slave_buff_addr;
uint8_t g_u8SlvData[256];
uint8_t g_au8RxData[4];
uint8_t g_u8DeviceAddr;
uint8_t g_u8ARA_Addr;
uint8_t g_au8TxData[4];
uint8_t g_u8RxData;
uint8_t g_u8DataLen0;
uint8_t g_u8DataLen1;
uint8_t g_u8EndFlag = 0;
uint8_t g_u8SendPEC = 0;
uint8_t g_u8AlertInt0 = 0;
uint8_t g_u8AlertInt1 = 0;
uint8_t g_u8AlertAddrAck0 = 0;
uint8_t g_u8AlertAddrAck1 = 0;
uint8_t g_u8PECErr = 0;
typedef void (*I2C_FUNC)(uint32_t u32Status);
static volatile I2C_FUNC s_I2C0HandlerFn = NULL;
static volatile I2C_FUNC s_I2C1HandlerFn = NULL;
/*---------------------------------------------------------------------------------------------------------*/
/* I2C0 IRQ Handler */
/*---------------------------------------------------------------------------------------------------------*/
void I2C0_IRQHandler(void)
{
uint32_t u32Status;
u32Status = I2C_GET_STATUS(I2C0);
/* Check Transmit byte done interrupt flag */
if((I2C_SMBusGetStatus(I2C0) & I2C_BUSSTS_BCDONE_Msk) == I2C_BUSSTS_BCDONE_Msk)
{
I2C_SMBusClearInterruptFlag(I2C0, I2C_BUSSTS_BCDONE_Msk);
//printf("I2C0 Byte Transmit Byte Done Interrupt !\n");
return;
}
/* Occur receive PEC packet error */
if((I2C_SMBusGetStatus(I2C0) & I2C_BUSSTS_PECERR_Msk) == I2C_BUSSTS_PECERR_Msk)
{
I2C_SMBusClearInterruptFlag(I2C0, I2C_BUSSTS_PECERR_Msk);
//printf("I2C0 PEC Error Interrupt !\n");
return;
}
/* Check Alert Interrupt when I2C0 is Host */
if(((I2C_SMBusGetStatus(I2C0) & I2C_BUSSTS_ALERT_Msk) == I2C_BUSSTS_ALERT_Msk) &
((I2C0->BUSCTL & I2C_BUSCTL_BMHEN_Msk) == I2C_BUSCTL_BMHEN_Msk))
{
I2C_SMBusClearInterruptFlag(I2C0, I2C_BUSSTS_ALERT_Msk);
//printf("I2C0 Alert Interrupt !\n");
g_u8AlertInt0 = 1;
return ;
}
if(I2C_GET_TIMEOUT_FLAG(I2C0))
{
/* Clear I2C0 Timeout Flag */
I2C_ClearTimeoutFlag(I2C0);
}
else
{
if(s_I2C0HandlerFn != NULL)
s_I2C0HandlerFn(u32Status);
}
}
/*---------------------------------------------------------------------------------------------------------*/
/* I2C1 IRQ Handler */
/*---------------------------------------------------------------------------------------------------------*/
void I2C1_IRQHandler(void)
{
uint32_t u32Status;
u32Status = I2C_GET_STATUS(I2C1);
/* Check Transmit byte done interrupt flag */
if((I2C_SMBusGetStatus(I2C1) & I2C_BUSSTS_BCDONE_Msk) == I2C_BUSSTS_BCDONE_Msk)
{
I2C_SMBusClearInterruptFlag(I2C1, I2C_BUSSTS_BCDONE_Msk);
//printf("I2C1 Byte Receive Byte Done Interrupt !\n");
return;
}
/* Occur receive PEC packet error */
if((I2C_SMBusGetStatus(I2C1) & I2C_BUSSTS_PECERR_Msk) == I2C_BUSSTS_PECERR_Msk)
{
I2C_SMBusClearInterruptFlag(I2C1, I2C_BUSSTS_PECERR_Msk);
//printf("I2C1 PEC Error Interrupt !\n");
return;
}
/* Check Alert Interrupt when I2C1 is Host */
if(((I2C_SMBusGetStatus(I2C1) & I2C_BUSSTS_ALERT_Msk) == I2C_BUSSTS_ALERT_Msk) &
((I2C1->BUSCTL & I2C_BUSCTL_BMHEN_Msk) == I2C_BUSCTL_BMHEN_Msk))
{
I2C_SMBusClearInterruptFlag(I2C1, I2C_BUSSTS_ALERT_Msk);
//printf("I2C1 Alert Interrupt !\n");
g_u8AlertInt1 = 1;
return ;
}
if(I2C_GET_TIMEOUT_FLAG(I2C1))
{
/* Clear I2C1 Timeout Flag */
I2C_ClearTimeoutFlag(I2C1);
}
else
{
if(s_I2C1HandlerFn != NULL)
s_I2C1HandlerFn(u32Status);
}
}
/*---------------------------------------------------------------------------------------------------------*/
/* I2C Master Tx Callback Function */
/*---------------------------------------------------------------------------------------------------------*/
void I2C_MasterTx(uint32_t u32Status)
{
if(u32Status == 0x08) /* START has been transmitted */
{
I2C_SET_DATA(I2C0, g_u8DeviceAddr << 1); /* Write SLA+W to Register I2CDAT */
I2C_SET_CONTROL_REG(I2C0, I2C_CTL_SI);
}
else if(u32Status == 0x18) /* SLA+W has been transmitted and ACK has been received */
{
I2C_SET_DATA(I2C0, g_au8TxData[g_u8DataLen0++]);
I2C_SET_CONTROL_REG(I2C0, I2C_CTL_SI);
}
else if(u32Status == 0x20) /* SLA+W has been transmitted and NACK has been received */
{
I2C_STOP(I2C0);
I2C_START(I2C0);
}
else if(u32Status == 0x28) /* DATA has been transmitted and ACK has been received */
{
if(g_u8DataLen0 != 3)
{
I2C_SET_DATA(I2C0, g_au8TxData[g_u8DataLen0++]);
I2C_SET_CONTROL_REG(I2C0, I2C_CTL_SI);
}
else
{
if(g_u8SendPEC == 0)
{
g_u8SendPEC = 1;
I2C_SET_CONTROL_REG(I2C0, I2C_CTL_SI);
}
else
{
I2C_SET_CONTROL_REG(I2C0, I2C_CTL_STO_SI);
g_u8EndFlag = 1;
}
}
}
else
{
/* TO DO */
printf("Status 0x%x is NOT processed\n", u32Status);
}
}
/*---------------------------------------------------------------------------------------------------------*/
/* I2C Master Alert Callback Function */
/*---------------------------------------------------------------------------------------------------------*/
void I2C_MasterAlert(uint32_t u32Status)
{
if(u32Status == 0x08) /* START has been transmitted */
{
I2C_SET_DATA(I2C0, (g_u8DeviceAddr << 1) + 1); /* Write SLA+R to Register I2CDAT */
I2C_SET_CONTROL_REG(I2C0, I2C_CTL_SI);
}
else if(u32Status == 0x18) /* SLA+W has been transmitted and ACK has been received */
{
I2C_SET_DATA(I2C0, g_au8TxData[g_u8DataLen0++]);
I2C_SET_CONTROL_REG(I2C0, I2C_CTL_SI);
}
else if(u32Status == 0x20) /* SLA+W has been transmitted and NACK has been received */
{
I2C_STOP(I2C0);
I2C_START(I2C0);
}
else if(u32Status == 0x40)
{
I2C_SET_CONTROL_REG(I2C0, I2C_CTL_SI_AA);
}
else if(u32Status == 0x50)
{
if(g_u8DataLen0 == 0)
{
g_au8RxData[g_u8DataLen0] = (unsigned char)I2C_GET_DATA(I2C0);
I2C_SET_CONTROL_REG(I2C0, I2C_CTL_SI_AA);
g_u8DataLen0++;
}
else
{
g_au8RxData[g_u8DataLen0] = (unsigned char) I2C_GET_DATA(I2C0);
I2C_SET_CONTROL_REG(I2C0, I2C_CTL_STO_SI_AA);
g_u8AlertAddrAck0 = 1;
}
}
else if(u32Status == 0x28) /* DATA has been transmitted and ACK has been received */
{
if(g_u8DataLen0 != 3)
{
I2C_SET_DATA(I2C0, g_au8TxData[g_u8DataLen0++]);
I2C_SET_CONTROL_REG(I2C0, I2C_CTL_SI);
}
else
{
if(g_u8SendPEC == 0)
{
g_u8SendPEC = 1;
I2C_SET_CONTROL_REG(I2C0, I2C_CTL_SI);
}
else
{
I2C_SET_CONTROL_REG(I2C0, I2C_CTL_STO_SI);
g_u8EndFlag = 1;
}
}
}
else
{
/* TO DO */
printf("Status 0x%x is NOT processed\n", u32Status);
}
}
/*---------------------------------------------------------------------------------------------------------*/
/* I2C Master Default Address and Acknowledge by Manual Callback Function */
/*---------------------------------------------------------------------------------------------------------*/
void I2C_MasterDefaultAddrACKM(uint32_t u32Status)
{
if(u32Status == 0x08) /* START has been transmitted */
{
I2C_SET_DATA(I2C0, g_u8DeviceAddr << 1); /* Write SLA+W to Register I2CDAT */
I2C_SET_CONTROL_REG(I2C0, I2C_CTL_SI);
}
else if(u32Status == 0x18) /* SLA+W has been transmitted and ACK has been received */
{
I2C_SET_DATA(I2C0, g_au8TxData[g_u8DataLen0++]);
I2C_SET_CONTROL_REG(I2C0, I2C_CTL_SI);
}
else if(u32Status == 0x20) /* SLA+W has been transmitted and NACK has been received */
{
I2C_STOP(I2C0);
I2C_START(I2C0);
}
else if(u32Status == 0x28) /* DATA has been transmitted and ACK has been received */
{
if(g_u8SendPEC == 0)
{
g_u8SendPEC = 1;
I2C_SET_CONTROL_REG(I2C0, I2C_CTL_SI);
}
else
{
I2C_SET_CONTROL_REG(I2C0, I2C_CTL_STO_SI);
g_u8EndFlag = 1;
}
}
else
{
/* TO DO */
printf("Status 0x%x is NOT processed\n", u32Status);
}
}
/*---------------------------------------------------------------------------------------------------------*/
/* I2C Slave TRx Callback Function */
/*---------------------------------------------------------------------------------------------------------*/
void I2C_SlaveTRx(uint32_t u32Status)
{
if(u32Status == 0x60) /* Own SLA+W has been receive; ACK has been return */
{
g_u8DataLen1 = 0;
I2C_SET_CONTROL_REG(I2C1, I2C_CTL_SI_AA);
}
else if(u32Status == 0x80) /* Previously address with own SLA address
Data has been received; ACK has been returned*/
{
g_au8RxData[g_u8DataLen1] = (unsigned char)I2C_GET_DATA(I2C1);
g_u8DataLen1++;
if(g_u8DataLen1 == 2)
{
slave_buff_addr = (g_au8RxData[0] << 8) + g_au8RxData[1];
}
if(g_u8DataLen1 == 3)
{
g_u8SlvData[slave_buff_addr] = g_au8RxData[2];
}
if(g_u8DataLen1 == 4)
{
if(g_au8RxData[3] != I2C_SMBusGetPECValue(I2C1))
{
g_u8PECErr = 1;
}
g_u8DataLen1 = 0;
}
I2C_SET_CONTROL_REG(I2C1, I2C_CTL_SI_AA);
}
else if(u32Status == 0xA8) /* Own SLA+R has been receive; ACK has been return */
{
I2C_SET_DATA(I2C1, g_u8SlvData[slave_buff_addr]);
slave_buff_addr++;
I2C_SET_CONTROL_REG(I2C1, I2C_CTL_SI_AA);
}
else if(u32Status == 0xC0) /* Data byte or last data in I2CDAT has been transmitted
Not ACK has been received */
{
I2C_SET_CONTROL_REG(I2C1, I2C_CTL_SI_AA);
}
else if(u32Status == 0x88) /* Previously addressed with own SLA address; NOT ACK has
been returned */
{
g_u8DataLen1 = 0;
I2C_SET_CONTROL_REG(I2C1, I2C_CTL_SI_AA);
}
else if(u32Status == 0xA0) /* A STOP or repeated START has been received while still
addressed as Slave/Receiver*/
{
g_u8DataLen1 = 0;
I2C_SET_CONTROL_REG(I2C1, I2C_CTL_SI_AA);
}
else
{
/* TO DO */
printf("Status 0x%x is NOT processed\n", u32Status);
}
}
/*---------------------------------------------------------------------------------------------------------*/
/* I2C Slave Alert Callback Function */
/*---------------------------------------------------------------------------------------------------------*/
void I2C_SlaveAlert(uint32_t u32Status)
{
if(u32Status == 0x60) /* Own SLA+W has been receive; ACK has been return */
{
g_u8DataLen1 = 0;
I2C_SET_CONTROL_REG(I2C1, I2C_CTL_SI_AA);
}
else if(u32Status == 0x80) /* Previously address with own SLA address
Data has been received; ACK has been returned*/
{
g_au8RxData[g_u8DataLen1] = (unsigned char) I2C_GET_DATA(I2C1);
g_u8DataLen1++;
if(g_u8DataLen1 == 2)
{
slave_buff_addr = (g_au8RxData[0] << 8) + g_au8RxData[1];
}
if(g_u8DataLen1 == 3)
{
g_u8SlvData[slave_buff_addr] = g_au8RxData[2];
}
if(g_u8DataLen1 == 4)
{
if(g_au8RxData[3] != I2C_SMBusGetPECValue(I2C1))
{
g_u8PECErr = 1;
}
g_u8DataLen1 = 0;
}
I2C_SET_CONTROL_REG(I2C1, I2C_CTL_SI_AA);
}
else if(u32Status == 0xA8) /* Own SLA+R has been receive; ACK has been return */
{
I2C_SET_DATA(I2C1, g_u8SlaveAddr[0]);
I2C_SET_CONTROL_REG(I2C1, I2C_CTL_SI_AA);
}
else if(u32Status == 0xC0) /* Data byte or last data in I2CDAT has been transmitted
Not ACK has been received */
{
I2C_SET_CONTROL_REG(I2C1, I2C_CTL_SI_AA);
}
else if(u32Status == 0x88) /* Previously addressed with own SLA address; NOT ACK has
been returned */
{
g_u8DataLen1 = 0;
I2C_SET_CONTROL_REG(I2C1, I2C_CTL_SI_AA);
}
else if(u32Status == 0xA0) /* A STOP or repeated START has been received while still
addressed as Slave/Receiver*/
{
g_u8DataLen1 = 0;
I2C_SET_CONTROL_REG(I2C1, I2C_CTL_SI_AA);
}
else if(u32Status == 0xB8)
{
I2C_SET_CONTROL_REG(I2C1, I2C_CTL_SI_AA);
}
else
{
/* TO DO */
printf("Status 0x%x is NOT processed\n", u32Status);
}
}
/*---------------------------------------------------------------------------------------------------------*/
/* I2C Slave Default Address and Acknowledge by Manual Callback Function */
/*---------------------------------------------------------------------------------------------------------*/
void I2C_SlaveDefaultAddrACKM(uint32_t u32Status)
{
if(u32Status == 0x60) /* Own SLA+W has been receive; ACK has been return */
{
I2C_SET_CONTROL_REG(I2C1, I2C_CTL_SI);
}
else if(u32Status == 0xF0)
{
/* Enable ACKMEN & SLV in Receive Mode */
g_au8RxData[g_u8DataLen1] = (unsigned char) I2C_GET_DATA(I2C1);
g_u8DataLen1++;
I2C_SET_CONTROL_REG(I2C1, I2C_CTL_SI_AA); //Acknowledge by Manual
}
else if(u32Status == 0x80) /* Previously address with own SLA address
Data has been received; ACK has been returned*/
{
g_au8RxData[g_u8DataLen1] = (unsigned char) I2C_GET_DATA(I2C1);
g_u8DataLen1++;
if(g_u8DataLen1 == 2)
{
if(g_au8RxData[1] != I2C_SMBusGetPECValue(I2C1))
{
g_u8PECErr = 1;
}
g_u8DataLen1 = 0;
}
I2C_SET_CONTROL_REG(I2C1, I2C_CTL_SI_AA);
}
else if(u32Status == 0xA8) /* Own SLA+R has been receive; ACK has been return */
{
I2C_SET_DATA(I2C1, g_u8SlvData[slave_buff_addr]);
slave_buff_addr++;
I2C_SET_CONTROL_REG(I2C1, I2C_CTL_SI_AA);
}
else if(u32Status == 0xC0) /* Data byte or last data in I2CDAT has been transmitted
Not ACK has been received */
{
I2C_SET_CONTROL_REG(I2C1, I2C_CTL_SI_AA);
}
else if(u32Status == 0x88) /* Previously addressed with own SLA address; NOT ACK has
been returned */
{
g_u8DataLen1 = 0;
I2C_SET_CONTROL_REG(I2C1, I2C_CTL_SI_AA);
}
else if(u32Status == 0xA0) /* A STOP or repeated START has been received while still
addressed as Slave/Receiver*/
{
g_u8DataLen1 = 0;
I2C_SET_CONTROL_REG(I2C1, I2C_CTL_SI_AA);
}
else
{
/* TO DO */
printf("Status 0x%x is NOT processed\n", u32Status);
}
}
void SYS_Init(void)
{
/*---------------------------------------------------------------------------------------------------------*/
/* Init System Clock */
/*---------------------------------------------------------------------------------------------------------*/
/* Set PCLK0 and PCLK1 to HCLK/2 */
CLK->PCLKDIV = (CLK_PCLKDIV_APB0DIV_DIV2 | CLK_PCLKDIV_APB1DIV_DIV2);
/* Set core clock to 200MHz */
CLK_SetCoreClock(200000000);
/* Enable all GPIO clock */
CLK->AHBCLK0 |= CLK_AHBCLK0_GPACKEN_Msk | CLK_AHBCLK0_GPBCKEN_Msk | CLK_AHBCLK0_GPCCKEN_Msk | CLK_AHBCLK0_GPDCKEN_Msk |
CLK_AHBCLK0_GPECKEN_Msk | CLK_AHBCLK0_GPFCKEN_Msk | CLK_AHBCLK0_GPGCKEN_Msk | CLK_AHBCLK0_GPHCKEN_Msk;
CLK->AHBCLK1 |= CLK_AHBCLK1_GPICKEN_Msk | CLK_AHBCLK1_GPJCKEN_Msk;
/* Enable UART0 module clock */
CLK_EnableModuleClock(UART0_MODULE);
/* Select UART0 module clock source as HIRC and UART0 module clock divider as 1 */
CLK_SetModuleClock(UART0_MODULE, CLK_CLKSEL1_UART0SEL_HIRC, CLK_CLKDIV0_UART0(1));
/* Enable I2C0 clock */
CLK_EnableModuleClock(I2C0_MODULE);
/* Enable I2C1 clock */
CLK_EnableModuleClock(I2C1_MODULE);
/*---------------------------------------------------------------------------------------------------------*/
/* Init I/O Multi-function */
/*---------------------------------------------------------------------------------------------------------*/
/* Set multi-function pins for UART0 RXD and TXD */
SET_UART0_RXD_PB12();
SET_UART0_TXD_PB13();
/* Set I2C0 multi-function pins */
SET_I2C0_SDA_PA4();
SET_I2C0_SCL_PA5();
SET_I2C0_SMBSUS_PA2();
SET_I2C0_SMBAL_PA3();
/* Set I2C1 multi-function pins */
SET_I2C1_SDA_PB10();
SET_I2C1_SCL_PB11();
SET_I2C1_SMBSUS_PB8();
SET_I2C1_SMBAL_PB9();
/* I2C pin enable schmitt trigger */
PA->SMTEN |= GPIO_SMTEN_SMTEN4_Msk | GPIO_SMTEN_SMTEN5_Msk;
PB->SMTEN |= GPIO_SMTEN_SMTEN10_Msk | GPIO_SMTEN_SMTEN11_Msk;
}
void UART0_Init(void)
{
/*---------------------------------------------------------------------------------------------------------*/
/* Init UART */
/*---------------------------------------------------------------------------------------------------------*/
/* Reset IP */
SYS_ResetModule(UART0_RST);
/* Configure UART0 and set UART0 Baudrate */
UART_Open(UART0, 115200);
}
void I2C0_Init(void)
{
/* Reset I2C0 */
SYS_ResetModule(I2C0_RST);
/* Open I2C module and set bus clock */
I2C_Open(I2C0, 100000);
/* Get I2C0 Bus Clock */
printf("I2C0 clock %d Hz\n", I2C_GetBusClockFreq(I2C0));
/* Enable I2C0 interrupt */
I2C_EnableInt(I2C0);
NVIC_EnableIRQ(I2C0_IRQn);
}
void I2C1_Init(void)
{
/* Reset I2C1 */
SYS_ResetModule(I2C1_RST);
/* Open I2C module and set bus clock */
I2C_Open(I2C1, 100000);
/* Get I2C0 Bus Clock */
printf("I2C1 clock %d Hz\n", I2C_GetBusClockFreq(I2C1));
/* Set I2C1 4 Slave addresses */
/* Slave address : 0x18 */
I2C_SetSlaveAddr(I2C1, 0, g_u8SlaveAddr[0], 0); /* Slave Address : 0x18 */
/* Slave address : 0x38 */
I2C_SetSlaveAddr(I2C1, 1, g_u8SlaveAddr[1], 0); /* Slave Address : 0x38 */
/* Slave address : 0x58 */
I2C_SetSlaveAddr(I2C1, 2, g_u8SlaveAddr[2], 0); /* Slave Address : 0x58 */
/* Slave address : 0x78 */
I2C_SetSlaveAddr(I2C1, 3, g_u8SlaveAddr[3], 0); /* Slave Address : 0x78 */
/* Set I2C1 4 Slave addresses mask bits*/
/* Slave address mask Bits: 0x04 */
I2C_SetSlaveAddrMask(I2C1, 0, 0x04);
/* Slave address mask Bits: 0x02 */
I2C_SetSlaveAddrMask(I2C1, 1, 0x02);
/* Slave address mask Bits: 0x04 */
I2C_SetSlaveAddrMask(I2C1, 2, 0x04);
/* Slave address mask Bits: 0x02 */
I2C_SetSlaveAddrMask(I2C1, 3, 0x02);
/* Enable I2C1 interrupt */
I2C_EnableInt(I2C1);
NVIC_EnableIRQ(I2C1_IRQn);
}
void I2C0_Close(void)
{
/* Disable I2C0 interrupt and clear corresponding NVIC bit */
I2C_DisableInt(I2C0);
NVIC_DisableIRQ(I2C0_IRQn);
/* Disable I2C0 and close I2C0 clock */
I2C_Close(I2C0);
CLK_DisableModuleClock(I2C0_MODULE);
}
void I2C1_Close(void)
{
/* Disable I2C1 interrupt and clear corresponding NVIC bit */
I2C_DisableInt(I2C1);
NVIC_DisableIRQ(I2C1_IRQn);
/* Disable I2C1 and close I2C1 clock */
I2C_Close(I2C1);
CLK_DisableModuleClock(I2C1_MODULE);
}
int32_t SMBusSendByteTest(uint8_t slvaddr)
{
uint32_t i, u32TimeOutCnt;
g_u8DeviceAddr = slvaddr;
for(i = 0; i < 0x100; i++)
{
/* Init transmission bytes */
g_au8TxData[0] = (uint8_t)((i & 0xFF00) >> 8);
g_au8TxData[1] = (uint8_t)(i & 0x00FF);
g_au8TxData[2] = (uint8_t)(g_au8TxData[1] + 3);
g_u8DataLen0 = 0;
g_u8EndFlag = 0;
g_u8SendPEC = 0;
/* I2C0 function to write data to slave */
s_I2C0HandlerFn = (I2C_FUNC)I2C_MasterTx;
/* I2C0 as master sends START signal */
I2C_SET_CONTROL_REG(I2C0, I2C_CTL_STA);
/* Wait I2C0 transmit finish */
u32TimeOutCnt = I2C_TIMEOUT;
while(g_u8EndFlag == 0)
{
if(--u32TimeOutCnt == 0)
{
printf("Wait for I2C transmit finish time-out!\n");
return -1;
}
}
g_u8EndFlag = 0;
if(g_u8PECErr)
{
printf("PEC Check Error !\n");
return -1;
}
}
return 0;
}
int32_t SMBusAlertTest(uint8_t slvaddr)
{
uint32_t u32TimeOutCnt;
g_u8DeviceAddr = slvaddr;
/* I2C function to Send Alert Response Address to bus */
s_I2C0HandlerFn = (I2C_FUNC)I2C_MasterAlert;
/* I2C0 Send Start condition */
I2C_SET_CONTROL_REG(I2C0, I2C_CTL_STA);
/* Init receive data index */
g_u8DataLen0 = 0;
/* Waiting for Get Alert Address */
u32TimeOutCnt = I2C_TIMEOUT;
while(g_u8AlertAddrAck0 == 0)
{
if(--u32TimeOutCnt == 0)
{
printf("Wait for I2C get alert address time-out!\n");
return -1;
}
}
g_u8AlertAddrAck0 = 0;
if(g_u8PECErr)
{
printf("PEC Check Error !\n");
return -1;
}
return 0;
}
int32_t SMBusDefaultAddressTest(uint8_t slvaddr)
{
uint32_t u32TimeOutCnt;
g_u8DeviceAddr = slvaddr;
/* Set Transmission ARP command */
g_au8TxData[0] = ARP_COMMAND;
g_u8DataLen0 = 0;
g_u8DataLen1 = 0;
g_u8EndFlag = 0;
g_u8SendPEC = 0;
/* I2C0 function to write data to slave */
s_I2C0HandlerFn = (I2C_FUNC)I2C_MasterDefaultAddrACKM;
/* I2C0 as master sends START signal */
I2C_SET_CONTROL_REG(I2C0, I2C_CTL_STA);
/* Wait I2C0 transmit finish */
u32TimeOutCnt = I2C_TIMEOUT;
while(g_u8EndFlag == 0)
{
if(--u32TimeOutCnt == 0)
{
printf("Wait for I2C transmit finish time-out!\n");
return -1;
}
}
g_u8EndFlag = 0;
if(g_u8PECErr)
{
printf("PEC Check Error !\n");
return -1;
}
printf("\n");
printf("Master Sends ARP Command(0x01) to Slave (0x%X) Test OK\n", slvaddr);
return 0;
}
/*---------------------------------------------------------------------------------------------------------*/
/* Main Function */
/*---------------------------------------------------------------------------------------------------------*/
int32_t main(void)
{
uint32_t i, ch = 0;
uint32_t u32TimeOutCnt;
/* Unlock protected registers */
SYS_UnlockReg();
/* Init System, IP clock and multi-function I/O */
SYS_Init();
/* Init UART0 for printf */
UART0_Init();
while(ch != 0x30)
{
/*
This sample code sets I2C bus clock to 100kHz. Then, Master accesses Slave with Byte Write
and Byte Read operations, and check if the read data is equal to the programmed data.
*/
printf("\n");
printf("+-------------------------------------------------------+\n");
printf("| M460 I2C SMBUS Driver Sample Code |\n");
printf("| |\n");
printf("| I2C Master (I2C0) <---> I2C Slave(I2C1) |\n");
printf("+-------------------------------------------------------+\n");
printf("Configure I2C0 as master and I2C1 as a slave.\n");
printf("\n");
/* Init I2C0 */
I2C0_Init();
/* Init I2C1 */
I2C1_Init();
/* I2C1 enter no address SLV mode */
I2C_SET_CONTROL_REG(I2C1, I2C_CTL_SI_AA);
printf("\n");
printf("I2C Slave Mode is Running.\n");
for(i = 0; i < 0x100; i++)
{
g_u8SlvData[i] = 0;
}
printf("\n");
printf("[1] SMBus Send Bytes Protocol with PEC Test\n");
printf("[2] SMBus Alert Function Test\n");
printf("[3] Simple ARP and ACK Control by Manual Test\n");
printf("[0] Exit\n");
ch = getchar();
if(ch == '1')
{
/* I2C0 Bus Management enable */
I2C_SMBusOpen(I2C0, I2C_SMBH_ENABLE);
/* I2C0 Bus PEC Check and transmit enable */
I2C_SMBusPECTxEnable(I2C0, I2C_PECTX_ENABLE);
/* I2C1 Bus Management init */
I2C_SMBusOpen(I2C1, I2C_SMBD_ENABLE);
/* I2C1 Bus PEC check enable */
I2C_SMBusPECTxEnable(I2C1, I2C_PECTX_DISABLE);
/* Set I2C0 Payload bytes */
I2C_SMBusSetPacketByteCount(I2C0, 4); // I2C0: 1byte address + 3byte data
/* Set I2C1 Payload bytes */
I2C_SMBusSetPacketByteCount(I2C1, 4); // I2C1: 1byte address + 3byte data
g_u8PECErr = 0;
/* I2C function to Slave receive/transmit data */
s_I2C1HandlerFn = I2C_SlaveTRx;
/* Access Slave with no address mask */
printf("\n");
printf(" == SMBus Send Bytes Protocol test ==\n");
/* SMBus send byte protocol test*/
if( SMBusSendByteTest(g_u8SlaveAddr[0]) < 0 ) goto lexit;
printf("\n");
printf("SMBus transmit data done.\n");
}
else if(ch == '2')
{
/* I2C0 Bus Management Enable */
I2C_SMBusOpen(I2C0, I2C_SMBH_ENABLE);
/* I2C0 Bus PEC Check and transmit Enable */
I2C_SMBusPECTxEnable(I2C0, I2C_PECTX_DISABLE);
/* I2C1 Bus Management init */
I2C_SMBusOpen(I2C1, I2C_SMBD_ENABLE);
/* I2C1 Bus PEC Check enable */
I2C_SMBusPECTxEnable(I2C1, I2C_PECTX_ENABLE);
/* Set I2C0 Payload bytes */
I2C_SMBusSetPacketByteCount(I2C0, 2); // I2C0: 1byte address + 1byte data
/* Set I2C1 Payload bytes */
I2C_SMBusSetPacketByteCount(I2C1, 2); // I2C1: 1byte address + 1byte data
/* Alert pin support if BMHEN(I2C0->BUSCTL[4]) = 0 */
I2C_SMBUS_ENABLE_ALERT(I2C0);
/* Enable Host SUSCON pin function and output Hi */
I2C_SMBUS_SET_SUSCON_OUT(I2C0);
I2C_SMBUS_SET_SUSCON_HIGH(I2C0);
/* Release Slave Alert pin to Hi */
I2C_SMBUS_DISABLE_ALERT(I2C1);
/* Set Slave SUSCON pin is Input */
I2C_SMBUS_SET_SUSCON_IN(I2C1);
g_u8PECErr = 0;
/* I2C function to Slave for receive/transmit data */
s_I2C1HandlerFn = I2C_SlaveAlert;
/* Access Slave with no address mask */
printf("\n");
printf(" == SMBus Alert Function Test ==\n");
/* I2C1 Slave has a Alert request, pull Alert Pin to Lo */
I2C_SMBUS_ENABLE_ALERT(I2C1);
printf("\n");
printf("I2C1 has Alert Request and Alert Pin Pull Lo. \n");
/* Wait I2C0 get Alert interrupt */
u32TimeOutCnt = I2C_TIMEOUT;
while(g_u8AlertInt0 == 0)
{
if(--u32TimeOutCnt == 0)
{
printf("Wait for I2C alert interrupt time-out!\n");
goto lexit;
}
}
/* I2C0 Get Alert Request */
g_u8AlertInt0 = 0;
printf("I2C0 Get Alert Interrupt Request\n");
/* I2C0 Send Alert Response Address(ARA) to I2C bus */
if( SMBusAlertTest(SMBUS_ALERT_RESPONSE_ADDRESS) < 0 ) goto lexit;
/* Printf the Alert Slave address */
printf("\n");
printf("Get Alert Address 0x%X test OK.\n", g_au8RxData[0]);
/* Show I2C1 SUSCON pin state before I2C0 pull Lo */
printf("\n");
printf("I2C1 SUSCON Pin state is %d\n", (int)((I2C1->BUSSTS & I2C_BUSSTS_SCTLDIN_Msk) >> 4));
/* Output I2C0 SUSCON pin Low */
I2C_SMBUS_SET_SUSCON_LOW(I2C0);
printf("I2C0 SUSCON Pin output Lo\n");
/* Show I2C1 SUSCON pin state after I2C0 pull Lo */
printf("\n");
printf("I2C1 SUSCON Pin state change to %d\n", (int)((I2C1->BUSSTS & I2C_BUSSTS_SCTLDIN_Msk) >> 4));
printf("\n");
printf("SMBus Alert Test Done\n");
}
else if(ch == '3')
{
/* I2C0 Bus management enable */
I2C_SMBusOpen(I2C0, I2C_SMBH_ENABLE);
/* I2C0 Bus PEC check and transmit enable */
I2C_SMBusPECTxEnable(I2C0, I2C_PECTX_ENABLE);
/* I2C1 Bus Management init */
I2C_SMBusOpen(I2C1, I2C_SMBD_ENABLE);
/* I2C1 Bus PEC check enable */
I2C_SMBusPECTxEnable(I2C1, I2C_PECTX_DISABLE);
/* I2C1 Acknowledge by Manual enable */
I2C_SMBUS_ACK_MANUAL(I2C1);
/* Set I2C0 Payload bytes */
I2C_SMBusSetPacketByteCount(I2C0, 2); // I2C0: 1byte address + 1byte data
/* Set I2C1 Payload bytes */
I2C_SMBusSetPacketByteCount(I2C1, 2); // I2C1: 1byte address + 1byte data
g_u8PECErr = 0;
/* I2C function to Slave receive/transmit data */
s_I2C1HandlerFn = I2C_SlaveDefaultAddrACKM;
printf("\n");
printf("== Simple ARP and Acknowledge by Manual Test ==\n");
/* I2C0 sends Default Address and ARP Command (0x01) to Slave */
if( SMBusDefaultAddressTest(SMBUS_DEFAULT_ADDRESS) < 0 ) goto lexit;
/* Show I2C1 get ARP command from I2C0 */
printf("\n");
printf("Slave Get ARP Command is 0x%X\n", g_au8RxData[0]);
/* Check Slave get command */
printf("\n");
if(g_au8RxData[0] != ARP_COMMAND)
{
printf("Get Wrong ARP Command, Please Check again !\n");
}
else
{
printf("Default Address and Acknowledge by Manual test OK.\n");
}
}
}
lexit:
s_I2C0HandlerFn = NULL;
s_I2C1HandlerFn = NULL;
printf("SMBus Test Exit\n");
/* Close I2C0 */
I2C0_Close();
/* Close I2C1 */
I2C1_Close();
while(1);
}
|
459385.c | /*------------------------------------------------------------------------
* Copyright 2009 (c) Jeff Brown <[email protected]>
*
* This file is part of the ZBar Bar Code Reader.
*
* The ZBar Bar Code Reader is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* The ZBar Bar Code Reader 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 Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with the ZBar Bar Code Reader; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* http://sourceforge.net/projects/zbar
*------------------------------------------------------------------------*/
#include <gtk/gtk.h>
#include <zbar/zbargtk.h>
static GtkWidget *window = NULL;
static GtkWidget *status_image = NULL;
static GtkTextView *results = NULL;
static gchar *open_file = NULL;
int scan_video(void *add_device,
void *userdata,
const char *default_device);
/* decode signal callback
* puts the decoded result in the textbox
*/
static void decoded (GtkWidget *widget,
zbar_symbol_type_t symbol,
const char *result,
gpointer data)
{
GtkTextBuffer *resultbuf = gtk_text_view_get_buffer(results);
GtkTextIter end;
gtk_text_buffer_get_end_iter(resultbuf, &end);
gtk_text_buffer_insert(resultbuf, &end, zbar_get_symbol_name(symbol), -1);
gtk_text_buffer_insert(resultbuf, &end, zbar_get_addon_name(symbol), -1);
gtk_text_buffer_insert(resultbuf, &end, ":", -1);
gtk_text_buffer_insert(resultbuf, &end, result, -1);
gtk_text_buffer_insert(resultbuf, &end, "\n", -1);
gtk_text_view_scroll_to_iter(results, &end, 0, FALSE, 0, 0);
}
/* update botton state when video state changes
*/
static void video_enabled (GObject *object,
GParamSpec *param,
gpointer data)
{
ZBarGtk *zbar = ZBAR_GTK(object);
gboolean enabled = zbar_gtk_get_video_enabled(zbar);
gboolean opened = zbar_gtk_get_video_opened(zbar);
GtkToggleButton *button = GTK_TOGGLE_BUTTON(data);
gboolean active = gtk_toggle_button_get_active(button);
if(active != (opened && enabled))
gtk_toggle_button_set_active(button, enabled);
}
static void video_opened (GObject *object,
GParamSpec *param,
gpointer data)
{
ZBarGtk *zbar = ZBAR_GTK(object);
gboolean opened = zbar_gtk_get_video_opened(zbar);
gboolean enabled = zbar_gtk_get_video_enabled(zbar);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(data), opened && enabled);
gtk_widget_set_sensitive(GTK_WIDGET(data), opened);
}
/* (re)open the video when a new device is selected
*/
static void video_changed (GtkWidget *widget,
gpointer data)
{
const char *video_device =
gtk_combo_box_get_active_text(GTK_COMBO_BOX(widget));
zbar_gtk_set_video_device(ZBAR_GTK(data),
((video_device && video_device[0] != '<')
? video_device
: NULL));
}
static void status_button_toggled (GtkToggleButton *button,
gpointer data)
{
ZBarGtk *zbar = ZBAR_GTK(data);
gboolean opened = zbar_gtk_get_video_opened(zbar);
gboolean enabled = zbar_gtk_get_video_enabled(zbar);
gboolean active = gtk_toggle_button_get_active(button);
if(opened && (active != enabled))
zbar_gtk_set_video_enabled(ZBAR_GTK(data), active);
gtk_image_set_from_stock(GTK_IMAGE(status_image),
(opened && active) ? GTK_STOCK_YES : GTK_STOCK_NO,
GTK_ICON_SIZE_BUTTON);
gtk_button_set_label(GTK_BUTTON(button),
(!opened) ? "closed" :
(active) ? "enabled" : "disabled");
}
static void open_button_clicked (GtkButton *button,
gpointer data)
{
GtkWidget *dialog =
gtk_file_chooser_dialog_new("Open Image File", GTK_WINDOW(window),
GTK_FILE_CHOOSER_ACTION_OPEN,
GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT,
NULL);
GtkFileChooser *chooser = GTK_FILE_CHOOSER(dialog);
if(open_file)
gtk_file_chooser_set_filename(chooser, open_file);
if(gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {
gchar *file = gtk_file_chooser_get_filename(chooser);
GdkPixbuf *pixbuf = gdk_pixbuf_new_from_file(file, NULL);
if(pixbuf)
zbar_gtk_scan_image(ZBAR_GTK(data), pixbuf);
else
fprintf(stderr, "ERROR: unable to open image file: %s\n", file);
if(open_file && file)
g_free(open_file);
open_file = file;
}
gtk_widget_destroy(dialog);
}
/* build a simple gui w/:
* - a combo box to select the desired video device
* - the zbar widget to display video
* - a non-editable text box to display any results
*/
int main (int argc, char *argv[])
{
g_thread_init(NULL);
gdk_threads_init();
gdk_threads_enter();
gtk_init(&argc, &argv);
const char *video_arg = NULL;
if(argc > 1)
video_arg = argv[1];
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "test_gtk");
gtk_container_set_border_width(GTK_CONTAINER(window), 8);
g_signal_connect(G_OBJECT(window), "destroy",
G_CALLBACK(gtk_main_quit), NULL);
GtkWidget *zbar = zbar_gtk_new();
g_signal_connect(G_OBJECT(zbar), "decoded",
G_CALLBACK(decoded), NULL);
/* video device list combo box */
GtkWidget *video_list = gtk_combo_box_new_text();
g_signal_connect(G_OBJECT(video_list), "changed",
G_CALLBACK(video_changed), zbar);
/* enable/disable status button */
GtkWidget *status_button = gtk_toggle_button_new();
status_image = gtk_image_new_from_stock(GTK_STOCK_NO,
GTK_ICON_SIZE_BUTTON);
gtk_button_set_image(GTK_BUTTON(status_button), status_image);
gtk_button_set_label(GTK_BUTTON(status_button), "closed");
gtk_widget_set_sensitive(status_button, FALSE);
/* bind status button state and video state */
g_signal_connect(G_OBJECT(status_button), "toggled",
G_CALLBACK(status_button_toggled), zbar);
g_signal_connect(G_OBJECT(zbar), "notify::video-enabled",
G_CALLBACK(video_enabled), status_button);
g_signal_connect(G_OBJECT(zbar), "notify::video-opened",
G_CALLBACK(video_opened), status_button);
/* open image file button */
GtkWidget *open_button = gtk_button_new_from_stock(GTK_STOCK_OPEN);
g_signal_connect(G_OBJECT(open_button), "clicked",
G_CALLBACK(open_button_clicked), zbar);
gtk_combo_box_append_text(GTK_COMBO_BOX(video_list), "<none>");
int active = scan_video(gtk_combo_box_append_text, video_list, video_arg);
if(active >= 0)
gtk_combo_box_set_active(GTK_COMBO_BOX(video_list), active);
/* hbox for combo box and buttons */
GtkWidget *hbox = gtk_hbox_new(FALSE, 8);
gtk_box_pack_start(GTK_BOX(hbox), video_list, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(hbox), status_button, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(hbox), open_button, FALSE, FALSE, 0);
/* text box for holding results */
results = GTK_TEXT_VIEW(gtk_text_view_new());
gtk_widget_set_size_request(GTK_WIDGET(results), 320, 64);
gtk_text_view_set_editable(results, FALSE);
gtk_text_view_set_cursor_visible(results, FALSE);
gtk_text_view_set_left_margin(results, 4);
/* vbox for hbox, zbar test widget and result text box */
GtkWidget *vbox = gtk_vbox_new(FALSE, 8);
gtk_container_add(GTK_CONTAINER(window), vbox);
gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(vbox), zbar, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(results), FALSE, FALSE, 0);
GdkGeometry hints;
hints.min_width = 320;
hints.min_height = 240;
gtk_window_set_geometry_hints(GTK_WINDOW(window), zbar, &hints,
GDK_HINT_MIN_SIZE);
gtk_widget_show_all(window);
gtk_main();
gdk_threads_leave();
return(0);
}
|
779868.c | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright by The HDF Group. *
* Copyright by the Board of Trustees of the University of Illinois. *
* All rights reserved. *
* *
* This file is part of HDF5. The full HDF5 copyright notice, including *
* terms governing use, modification, and redistribution, is contained in *
* the files COPYING and Copyright.html. COPYING can be found at the root *
* of the source code distribution tree; Copyright.html can be found at the *
* root level of an installed copy of the electronic HDF5 document set and *
* is linked from the top-level documents page. It can also be found at *
* http://hdfgroup.org/HDF5/doc/Copyright.html. If you do not have *
* access to either file, you may request a copy from [email protected]. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*-------------------------------------------------------------------------
*
* Created: H5Sdbg.c
* Jul 24 2007
* Quincey Koziol <[email protected]>
*
* Purpose: Dump debugging information about a dataspace
*
*-------------------------------------------------------------------------
*/
/****************/
/* Module Setup */
/****************/
#define H5S_PACKAGE /*suppress error about including H5Spkg */
/***********/
/* Headers */
/***********/
#include "H5private.h" /* Generic Functions */
#include "H5Eprivate.h" /* Error handling */
#include "H5Spkg.h" /* Dataspaces */
/****************/
/* Local Macros */
/****************/
/******************/
/* Local Typedefs */
/******************/
/********************/
/* Package Typedefs */
/********************/
/********************/
/* Local Prototypes */
/********************/
/*********************/
/* Package Variables */
/*********************/
/*****************************/
/* Library Private Variables */
/*****************************/
/*******************/
/* Local Variables */
/*******************/
/*-------------------------------------------------------------------------
* Function: H5S_debug
*
* Purpose: Prints debugging information about a data space.
*
* Return: Non-negative on success/Negative on failure
*
* Programmer: Robb Matzke
* Tuesday, July 21, 1998
*
*-------------------------------------------------------------------------
*/
herr_t
H5S_debug(H5F_t *f, hid_t dxpl_id, const void *_mesg, FILE *stream, int indent,
int fwidth)
{
const H5S_t *mesg = (const H5S_t*)_mesg;
FUNC_ENTER_NOAPI_NOINIT_NOERR
switch(H5S_GET_EXTENT_TYPE(mesg)) {
case H5S_NULL:
fprintf(stream, "%*s%-*s H5S_NULL\n", indent, "", fwidth,
"Space class:");
break;
case H5S_SCALAR:
fprintf(stream, "%*s%-*s H5S_SCALAR\n", indent, "", fwidth,
"Space class:");
break;
case H5S_SIMPLE:
fprintf(stream, "%*s%-*s H5S_SIMPLE\n", indent, "", fwidth,
"Space class:");
H5O_debug_id(H5O_SDSPACE_ID, f, dxpl_id, &(mesg->extent), stream,
indent + 3, MAX(0, fwidth - 3));
break;
default:
fprintf(stream, "%*s%-*s **UNKNOWN-%ld**\n", indent, "", fwidth,
"Space class:", (long)(H5S_GET_EXTENT_TYPE(mesg)));
break;
} /* end switch */
FUNC_LEAVE_NOAPI(SUCCEED)
} /* end H5S_debug() */
|
27380.c | /*
* Copyright (c) 2012-2020 MIRACL UK Ltd.
*
* This file is part of MIRACL Core
* (see https://github.com/miracl/core).
*
* 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.
*/
/* CORE Elliptic Curve Functions */
/* SU=m, SU is Stack Usage (Weierstrass Curves) */
//#define HAS_MAIN
#include "ecp_ZZZ.h"
/* test for P=O point-at-infinity */
int ECP_ZZZ_isinf(ECP_ZZZ *P)
{
#if CURVETYPE_ZZZ==EDWARDS
return (FP_YYY_iszilch(&(P->x)) && FP_YYY_equals(&(P->y), &(P->z)));
#endif
#if CURVETYPE_ZZZ==WEIERSTRASS
return (FP_YYY_iszilch(&(P->x)) && FP_YYY_iszilch(&(P->z)));
#endif
#if CURVETYPE_ZZZ==MONTGOMERY
return FP_YYY_iszilch(&(P->z));
#endif
}
/* Conditional swap of P and Q dependant on d */
static void ECP_ZZZ_cswap(ECP_ZZZ *P, ECP_ZZZ *Q, int d)
{
FP_YYY_cswap(&(P->x), &(Q->x), d);
#if CURVETYPE_ZZZ!=MONTGOMERY
FP_YYY_cswap(&(P->y), &(Q->y), d);
#endif
FP_YYY_cswap(&(P->z), &(Q->z), d);
}
#if CURVETYPE_ZZZ!=MONTGOMERY
/* Conditional move Q to P dependant on d */
static void ECP_ZZZ_cmove(ECP_ZZZ *P, ECP_ZZZ *Q, int d)
{
FP_YYY_cmove(&(P->x), &(Q->x), d);
#if CURVETYPE_ZZZ!=MONTGOMERY
FP_YYY_cmove(&(P->y), &(Q->y), d);
#endif
FP_YYY_cmove(&(P->z), &(Q->z), d);
}
/* return 1 if b==c, no branching */
static int teq(sign32 b, sign32 c)
{
sign32 x = b ^ c;
x -= 1; // if x=0, x now -1
return (int)((x >> 31) & 1);
}
#endif // CURVETYPE_ZZZ!=MONTGOMERY
#if CURVETYPE_ZZZ!=MONTGOMERY
/* Constant time select from pre-computed table */
static void ECP_ZZZ_select(ECP_ZZZ *P, ECP_ZZZ W[], sign32 b)
{
ECP_ZZZ MP;
sign32 m = b >> 31;
sign32 babs = (b ^ m) - m;
babs = (babs - 1) / 2;
ECP_ZZZ_cmove(P, &W[0], teq(babs, 0)); // conditional move
ECP_ZZZ_cmove(P, &W[1], teq(babs, 1));
ECP_ZZZ_cmove(P, &W[2], teq(babs, 2));
ECP_ZZZ_cmove(P, &W[3], teq(babs, 3));
ECP_ZZZ_cmove(P, &W[4], teq(babs, 4));
ECP_ZZZ_cmove(P, &W[5], teq(babs, 5));
ECP_ZZZ_cmove(P, &W[6], teq(babs, 6));
ECP_ZZZ_cmove(P, &W[7], teq(babs, 7));
ECP_ZZZ_copy(&MP, P);
ECP_ZZZ_neg(&MP); // minus P
ECP_ZZZ_cmove(P, &MP, (int)(m & 1));
}
#endif
/* Test P == Q */
/* SU=168 */
int ECP_ZZZ_equals(ECP_ZZZ *P, ECP_ZZZ *Q)
{
FP_YYY a, b;
FP_YYY_mul(&a, &(P->x), &(Q->z));
FP_YYY_mul(&b, &(Q->x), &(P->z));
if (!FP_YYY_equals(&a, &b)) return 0;
#if CURVETYPE_ZZZ!=MONTGOMERY
FP_YYY_mul(&a, &(P->y), &(Q->z));
FP_YYY_mul(&b, &(Q->y), &(P->z));
if (!FP_YYY_equals(&a, &b)) return 0;
#endif
return 1;
}
/* Set P=Q */
/* SU=16 */
void ECP_ZZZ_copy(ECP_ZZZ *P, ECP_ZZZ *Q)
{
FP_YYY_copy(&(P->x), &(Q->x));
#if CURVETYPE_ZZZ!=MONTGOMERY
FP_YYY_copy(&(P->y), &(Q->y));
#endif
FP_YYY_copy(&(P->z), &(Q->z));
}
/* Set P=-Q */
#if CURVETYPE_ZZZ!=MONTGOMERY
/* SU=8 */
void ECP_ZZZ_neg(ECP_ZZZ *P)
{
#if CURVETYPE_ZZZ==WEIERSTRASS
FP_YYY_neg(&(P->y), &(P->y));
FP_YYY_norm(&(P->y));
#else
FP_YYY_neg(&(P->x), &(P->x));
FP_YYY_norm(&(P->x));
#endif
}
#endif
/* Set P=O */
void ECP_ZZZ_inf(ECP_ZZZ *P)
{
FP_YYY_zero(&(P->x));
#if CURVETYPE_ZZZ!=MONTGOMERY
FP_YYY_one(&(P->y));
#endif
#if CURVETYPE_ZZZ!=EDWARDS
FP_YYY_zero(&(P->z));
#else
FP_YYY_one(&(P->z));
#endif
}
/* Calculate right Hand Side of curve equation y^2=RHS */
/* SU=56 */
void ECP_ZZZ_rhs(FP_YYY *v, FP_YYY *x)
{
#if CURVETYPE_ZZZ==WEIERSTRASS
/* x^3+Ax+B */
FP_YYY t;
FP_YYY_sqr(&t, x);
FP_YYY_mul(&t, &t, x);
#if CURVE_A_ZZZ == -3
FP_YYY_neg(v, x);
FP_YYY_norm(v);
FP_YYY_imul(v, v, -CURVE_A_ZZZ);
FP_YYY_norm(v);
FP_YYY_add(v, &t, v);
#else
FP_YYY_copy(v, &t);
#endif
FP_YYY_rcopy(&t, CURVE_B_ZZZ);
FP_YYY_add(v, &t, v);
FP_YYY_reduce(v);
#endif
#if CURVETYPE_ZZZ==EDWARDS
/* (Ax^2-1)/(Bx^2-1) */
FP_YYY t, one;
FP_YYY_sqr(v, x);
FP_YYY_one(&one);
FP_YYY_rcopy(&t, CURVE_B_ZZZ);
FP_YYY_mul(&t, v, &t);
FP_YYY_sub(&t, &t, &one);
FP_YYY_norm(&t);
#if CURVE_A_ZZZ == 1
FP_YYY_sub(v, v, &one);
#endif
#if CURVE_A_ZZZ == -1
FP_YYY_add(v, v, &one);
FP_YYY_norm(v);
FP_YYY_neg(v, v);
#endif
FP_YYY_norm(v);
FP_YYY_inv(&t, &t, NULL);
FP_YYY_mul(v, v, &t);
FP_YYY_reduce(v);
#endif
#if CURVETYPE_ZZZ==MONTGOMERY
/* x^3+Ax^2+x */
FP_YYY x2, x3;
FP_YYY_sqr(&x2, x);
FP_YYY_mul(&x3, &x2, x);
FP_YYY_copy(v, x);
FP_YYY_imul(&x2, &x2, CURVE_A_ZZZ);
FP_YYY_add(v, v, &x2);
FP_YYY_add(v, v, &x3);
FP_YYY_reduce(v);
#endif
}
#if CURVETYPE_ZZZ==MONTGOMERY
/* Set P=(x,{y}) */
int ECP_ZZZ_set(ECP_ZZZ *P, BIG_XXX x)
{
//BIG_XXX m, b;
FP_YYY rhs;
//BIG_XXX_rcopy(m, Modulus_YYY);
FP_YYY_nres(&rhs, x);
ECP_ZZZ_rhs(&rhs, &rhs);
//FP_YYY_redc(b, &rhs);
//if (BIG_XXX_jacobi(b, m) != 1)
if (!FP_YYY_qr(&rhs,NULL))
{
ECP_ZZZ_inf(P);
return 0;
}
FP_YYY_nres(&(P->x), x);
FP_YYY_one(&(P->z));
return 1;
}
/* Extract x coordinate as BIG */
int ECP_ZZZ_get(BIG_XXX x, ECP_ZZZ *P)
{
ECP_ZZZ W;
ECP_ZZZ_copy(&W, P);
ECP_ZZZ_affine(&W);
if (ECP_ZZZ_isinf(&W)) return -1;
FP_YYY_redc(x, &(W.x));
return 0;
}
#else
/* Extract (x,y) and return sign of y. If x and y are the same return only x */
/* SU=16 */
int ECP_ZZZ_get(BIG_XXX x, BIG_XXX y, ECP_ZZZ *P)
{
ECP_ZZZ W;
int s;
ECP_ZZZ_copy(&W, P);
ECP_ZZZ_affine(&W);
if (ECP_ZZZ_isinf(&W)) return -1;
FP_YYY_redc(y, &(W.y));
s = BIG_XXX_parity(y);
FP_YYY_redc(x, &(W.x));
return s;
}
/* Set P=(x,{y}) */
/* SU=96 */
int ECP_ZZZ_set(ECP_ZZZ *P, BIG_XXX x, BIG_XXX y)
{
FP_YYY rhs, y2;
FP_YYY_nres(&y2, y);
FP_YYY_sqr(&y2, &y2);
FP_YYY_reduce(&y2);
FP_YYY_nres(&rhs, x);
ECP_ZZZ_rhs(&rhs, &rhs);
if (!FP_YYY_equals(&y2, &rhs))
{
ECP_ZZZ_inf(P);
return 0;
}
FP_YYY_nres(&(P->x), x);
FP_YYY_nres(&(P->y), y);
FP_YYY_one(&(P->z));
return 1;
}
/* Set P=(x,y), where y is calculated from x with sign s */
/* SU=136 */
int ECP_ZZZ_setx(ECP_ZZZ *P, BIG_XXX x, int s)
{
FP_YYY rhs,hint;
BIG_XXX t;//, m;
//BIG_XXX_rcopy(m, Modulus_YYY);
FP_YYY_nres(&rhs, x);
ECP_ZZZ_rhs(&rhs, &rhs);
//FP_YYY_redc(t, &rhs);
//if (BIG_XXX_jacobi(t, m) != 1)
if (!FP_YYY_qr(&rhs,&hint))
{
ECP_ZZZ_inf(P);
return 0;
}
FP_YYY_nres(&(P->x), x);
FP_YYY_sqrt(&(P->y), &rhs,&hint);
FP_YYY_redc(t, &(P->y));
if (BIG_XXX_parity(t) != s)
FP_YYY_neg(&(P->y), &(P->y));
FP_YYY_reduce(&(P->y));
FP_YYY_one(&(P->z));
return 1;
}
#endif
void ECP_ZZZ_cfp(ECP_ZZZ *P)
{ /* multiply point by curves cofactor */
BIG_XXX c;
int cf = CURVE_Cof_I_ZZZ;
if (cf == 1) return;
if (cf == 4)
{
ECP_ZZZ_dbl(P);
ECP_ZZZ_dbl(P);
return;
}
if (cf == 8)
{
ECP_ZZZ_dbl(P);
ECP_ZZZ_dbl(P);
ECP_ZZZ_dbl(P);
return;
}
BIG_XXX_rcopy(c, CURVE_Cof_ZZZ);
ECP_ZZZ_mul(P, c);
return;
}
/* Hunt and Peck a BIG to a curve point */
/*
void ECP_ZZZ_hap2point(ECP_ZZZ *P,BIG_XXX h)
{
BIG_XXX x;
BIG_XXX_copy(x,h);
for (;;)
{
#if CURVETYPE_ZZZ!=MONTGOMERY
ECP_ZZZ_setx(P,x,0);
#else
ECP_ZZZ_set(P,x);
#endif
BIG_XXX_inc(x,1); BIG_XXX_norm(x);
if (!ECP_ZZZ_isinf(P)) break;
}
}
*/
/* Constant time Map to Point */
void ECP_ZZZ_map2point(ECP_ZZZ *P,FP_YYY *h)
{
#if CURVETYPE_ZZZ==MONTGOMERY
// Elligator 2
BIG_XXX a;
FP_YYY X1,X2,t,one,A;
//BIG_XXX_zero(a); BIG_XXX_inc(a,CURVE_A_ZZZ); BIG_XXX_norm(a); FP_YYY_nres(&A,a);
FP_YYY_from_int(&A,CURVE_A_ZZZ);
FP_YYY_copy(&t,h);
FP_YYY_sqr(&t,&t); // t^2
if (PM1D2_YYY == 2)
FP_YYY_add(&t,&t,&t); // 2t^2
if (PM1D2_YYY == 1)
FP_YYY_neg(&t,&t); // -t^2
if (PM1D2_YYY > 2)
FP_YYY_imul(&t,&t,QNRI_YYY); // precomputed QNR
FP_YYY_one(&one);
FP_YYY_add(&t,&t,&one); FP_YYY_norm(&t);
FP_YYY_inv(&t,&t,NULL); // 1/(1+z.t^2)
FP_YYY_mul(&X1,&t,&A);
FP_YYY_neg(&X1,&X1);
FP_YYY_copy(&X2,&X1);
FP_YYY_add(&X2,&X2,&A); FP_YYY_norm(&X2);
FP_YYY_neg(&X2,&X2);
ECP_ZZZ_rhs(&t,&X2);
FP_YYY_cmove(&X1,&X2,FP_YYY_qr(&t,NULL));
FP_YYY_redc(a,&X1);
ECP_ZZZ_set(P,a);
return;
#endif
#if CURVETYPE_ZZZ==EDWARDS
// Elligator 2 - map to Montgomery, place point, map back
int qres,sgn,ne,rfc;
BIG_XXX x,y;
FP_YYY X1,X2,t,one,A,w1,w2,B,Y,K,NY;
FP_YYY_one(&one);
#if MODTYPE_YYY != GENERALISED_MERSENNE
// its NOT goldilocks!
// Figure out the Montgomery curve parameters
FP_YYY_rcopy(&B,CURVE_B_ZZZ);
#if CURVE_A_ZZZ == 1
FP_YYY_add(&A,&B,&one); // A=B+1
FP_YYY_sub(&B,&B,&one); // B=B-1
#else
FP_YYY_sub(&A,&B,&one); // A=B-1
FP_YYY_add(&B,&B,&one); // B=B+1
#endif
FP_YYY_norm(&A); FP_YYY_norm(&B);
FP_YYY_div2(&A,&A); // (A+B)/2
FP_YYY_div2(&B,&B); // (B-A)/2
FP_YYY_div2(&B,&B); // (B-A)/4
FP_YYY_neg(&K,&B); FP_YYY_norm(&K);
//FP_YYY_inv(&K,&K,NULL); // K
FP_YYY_invsqrt(&K,&w1,&K);
rfc=RIADZ_YYY;
if (rfc)
{ // RFC7748 method applies
FP_YYY_mul(&A,&A,&K); // = J
FP_YYY_mul(&K,&K,&w1);
//FP_YYY_sqrt(&K,&K,NULL);
} else { // generic method
FP_YYY_sqr(&B,&B);
}
#else
FP_YYY_from_int(&A,156326);
rfc=1;
#endif
// Map to this Montgomery curve X^2=X^3+AX^2+BX
FP_YYY_copy(&t,h); sgn=FP_YYY_sign(&t);
FP_YYY_sqr(&t,&t); // t^2
if (PM1D2_YYY == 2)
FP_YYY_add(&t,&t,&t); // 2t^2
if (PM1D2_YYY == 1)
FP_YYY_neg(&t,&t); // -t^2
if (PM1D2_YYY > 2)
FP_YYY_imul(&t,&t,QNRI_YYY); // precomputed QNR
FP_YYY_add(&t,&t,&one); FP_YYY_norm(&t);
FP_YYY_inv(&t,&t,NULL); // 1/(1+z.t^2)
FP_YYY_mul(&X1,&t,&A);
FP_YYY_neg(&X1,&X1);
FP_YYY_copy(&X2,&X1);
FP_YYY_add(&X2,&X2,&A); FP_YYY_norm(&X2);
FP_YYY_neg(&X2,&X2);
FP_YYY_norm(&X1);
FP_YYY_sqr(&t,&X1); FP_YYY_mul(&w1,&t,&X1); // t=X1^2, w1=X1^3
FP_YYY_mul(&t,&t,&A); FP_YYY_add(&w1,&w1,&t);
if (!rfc)
{
FP_YYY_mul(&t,&X1,&B);
FP_YYY_add(&w1,&w1,&t); // w1=X1^3+AX1^2+BX1
} else {
FP_YYY_add(&w1,&w1,&X1);
}
FP_YYY_norm(&w1);
FP_YYY_norm(&X2);
FP_YYY_sqr(&t,&X2); FP_YYY_mul(&w2,&t,&X2); // t=X1^2, w2=X1^3
FP_YYY_mul(&t,&t,&A); FP_YYY_add(&w2,&w2,&t);
if (!rfc)
{
FP_YYY_mul(&t,&X2,&B);
FP_YYY_add(&w2,&w2,&t); // w2=X1^3+AX1^2+BX1
} else {
FP_YYY_add(&w2,&w2,&X2);
}
FP_YYY_norm(&w2);
qres=FP_YYY_qr(&w2,NULL);
FP_YYY_cmove(&X1,&X2,qres);
FP_YYY_cmove(&w1,&w2,qres);
FP_YYY_sqrt(&Y,&w1,NULL);
FP_YYY_neg(&NY,&Y); FP_YYY_norm(&NY);
FP_YYY_cmove(&Y,&NY,1-qres);
if (!rfc)
{
FP_YYY_mul(&X1,&X1,&K);
FP_YYY_mul(&Y,&Y,&K);
}
// ne=sgn^FP_YYY_sign(&Y);
// FP_YYY_neg(&NY,&Y); FP_YYY_norm(&NY);
// FP_YYY_cmove(&Y,&NY,ne);
#if MODTYPE_YYY == GENERALISED_MERSENNE
// GOLDILOCKS isogeny
FP_YYY_sqr(&t,&X1); // t=u^2
FP_YYY_add(&NY,&t,&one); // NY=u^2+1
FP_YYY_norm(&NY);
FP_YYY_sub(&t,&t,&one); // t=u^2-1
FP_YYY_norm(&t);
FP_YYY_mul(&w1,&t,&Y); // w1=v(u^2-1)
FP_YYY_add(&w1,&w1,&w1);
FP_YYY_add(&w1,&w1,&w1);
FP_YYY_norm(&w1); // w1=4v(u^2-1)
FP_YYY_sqr(&t,&t); // t=(u^2-1)^2
FP_YYY_sqr(&Y,&Y); // v^2
FP_YYY_add(&Y,&Y,&Y);
FP_YYY_add(&Y,&Y,&Y);
FP_YYY_norm(&Y); // 4v^2
FP_YYY_add(&w2,&t,&Y); // w2=(u^2-1)^2+4v^2
FP_YYY_norm(&w2);
FP_YYY_inv(&w2,&w2,NULL);
FP_YYY_mul(&w1,&w1,&w2); // w1=4v(u^2-1)/[(u^2-1)^2+4v^2]
FP_YYY_sub(&w2,&Y,&t); // w2=4v^2-(u^2-1)^2
FP_YYY_norm(&w2);
FP_YYY_mul(&w2,&w2,&X1); // w2=u(4v^2-(u^2-1)^2)
FP_YYY_mul(&t,&t,&X1); // t=u(u^2-1)^2
FP_YYY_copy(&X1,&w1); // X=4v(u^2-1)/[(u^2-1)^2+4v^2]
FP_YYY_div2(&Y,&Y); // 2v^2
FP_YYY_mul(&w1,&Y,&NY); // w1=2v^2(u^2+1)
FP_YYY_sub(&w1,&t,&w1); // w1=u(u^2-1)^2 - 2v^2(u^2+1)
FP_YYY_norm(&w1);
FP_YYY_inv(&w1,&w1,NULL);
FP_YYY_mul(&Y,&w2,&w1); // Y=u(4v^2-(u^2-1)*2) / u(u^2-1)^2 - 2v^2(u^2+1)
#else
FP_YYY_add(&w1,&X1,&one); FP_YYY_norm(&w1); // (s+1)
FP_YYY_sub(&w2,&X1,&one); FP_YYY_norm(&w2); // (s-1)
FP_YYY_mul(&t,&w1,&Y);
FP_YYY_inv(&t,&t,NULL);
FP_YYY_mul(&X1,&X1,&w1);
FP_YYY_mul(&X1,&X1,&t);
if (rfc)
FP_YYY_mul(&X1,&X1,&K);
FP_YYY_mul(&Y,&Y,&w2);
FP_YYY_mul(&Y,&Y,&t);
#endif
FP_YYY_redc(x,&X1);
FP_YYY_redc(y,&Y);
ECP_ZZZ_set(P,x,y);
return;
#endif
#if CURVETYPE_ZZZ==WEIERSTRASS
// SWU method.
int sgn,ne;
BIG_XXX a,x,y;
FP_YYY X1,X2,X3,t,w,one,A,B,Y,NY;
FP_YYY_one(&one);
FP_YYY_copy(&t,h);
sgn=FP_YYY_sign(&t);
#if CURVE_A_ZZZ != 0
FP_YYY_from_int(&A,CURVE_A_ZZZ);
FP_YYY_rcopy(&B,CURVE_B_ZZZ);
FP_YYY_sqr(&t,&t);
FP_YYY_imul(&t,&t,RIADZ_YYY);
FP_YYY_add(&w,&t,&one);
FP_YYY_norm(&w);
FP_YYY_mul(&w,&w,&t); // w=t2(t2+1)
FP_YYY_mul(&NY,&A,&w); // A=Aw
FP_YYY_inv(&NY,&NY,NULL);
FP_YYY_add(&w,&w,&one); FP_YYY_norm(&w);
FP_YYY_mul(&w,&w,&B);
FP_YYY_neg(&w,&w); // -B(w+1)
FP_YYY_norm(&w);
FP_YYY_mul(&X2,&w,&NY); // -B(w+1)/Aw
FP_YYY_mul(&X3,&t,&X2);
ECP_ZZZ_rhs(&w,&X3);
FP_YYY_cmove(&X2,&X3,FP_YYY_qr(&w,NULL));
ECP_ZZZ_rhs(&w,&X2);
FP_YYY_sqrt(&Y,&w,NULL);
FP_YYY_redc(x,&X2);
#else
// Shallue and van de Woestijne
FP_YYY_from_int(&Y,RIADZ_YYY);
ECP_ZZZ_rhs(&A,&Y); // A=g(Z)
FP_YYY_rcopy(&B,SQRTm3_YYY);
FP_YYY_imul(&B,&B,RIADZ_YYY); // Z*sqrt(-3)
FP_YYY_sqr(&t,&t);
FP_YYY_mul(&Y,&A,&t); // tv1=u^2*g(Z)
FP_YYY_add(&t,&one,&Y); FP_YYY_norm(&t); // tv2=1+tv1
FP_YYY_sub(&Y,&one,&Y); FP_YYY_norm(&Y); // tv1=1-tv1
FP_YYY_mul(&NY,&t,&Y);
FP_YYY_mul(&NY,&NY,&B);
FP_YYY_copy(&w,&A);
FP_YYY_tpo(&NY,&w); // tv3=inv0(tv1*tv2*z*sqrt(-3)) and sqrt(g(Z))
FP_YYY_mul(&w,&w,&B); // tv4=Z.sqrt(-3).sqrt(g(Z))
if (FP_YYY_sign(&w)==1)
{ // depends only on sign of constant RIADZ
FP_YYY_neg(&w,&w);
FP_YYY_norm(&w);
}
FP_YYY_mul(&w,&w,&B); // Z.sqrt(-3)
FP_YYY_mul(&w,&w,h);
FP_YYY_mul(&w,&w,&Y);
FP_YYY_mul(&w,&w,&NY); // tv5=u*tv1*tv3*tv4*Z*sqrt(-3)
FP_YYY_from_int(&X1,RIADZ_YYY);
FP_YYY_copy(&X3,&X1);
FP_YYY_neg(&X1,&X1); FP_YYY_norm(&X1); FP_YYY_div2(&X1,&X1); // -Z/2
FP_YYY_copy(&X2,&X1);
FP_YYY_sub(&X1,&X1,&w); FP_YYY_norm(&X1);
FP_YYY_add(&X2,&X2,&w); FP_YYY_norm(&X2);
FP_YYY_add(&A,&A,&A);
FP_YYY_add(&A,&A,&A);
FP_YYY_norm(&A); // -4*g(Z)
FP_YYY_sqr(&t,&t);
FP_YYY_mul(&t,&t,&NY);
FP_YYY_sqr(&t,&t); // (tv2^2*tv3)^2
FP_YYY_mul(&A,&A,&t); // -4*g(Z)*(tv2^2*tv3)^2
FP_YYY_add(&X3,&X3,&A); FP_YYY_norm(&X3);
ECP_ZZZ_rhs(&w,&X2);
FP_YYY_cmove(&X3,&X2,FP_YYY_qr(&w,NULL));
ECP_ZZZ_rhs(&w,&X1);
FP_YYY_cmove(&X3,&X1,FP_YYY_qr(&w,NULL));
ECP_ZZZ_rhs(&w,&X3);
FP_YYY_sqrt(&Y,&w,NULL);
FP_YYY_redc(x,&X3);
#endif
ne=FP_YYY_sign(&Y)^sgn;
FP_YYY_neg(&NY,&Y); FP_YYY_norm(&NY);
FP_YYY_cmove(&Y,&NY,ne);
FP_YYY_redc(y,&Y);
ECP_ZZZ_set(P,x,y);
#endif
}
/* Map octet to point */
/*
void ECP_ZZZ_mapit(ECP_ZZZ *P, octet *W)
{
BIG_XXX q, x;
DBIG_XXX dx;
BIG_XXX_rcopy(q, Modulus_YYY);
BIG_XXX_dfromBytesLen(dx, W->val,W->len);
BIG_XXX_dmod(x, dx, q);
ECP_ZZZ_hap2point(P,x);
ECP_ZZZ_cfp(P);
}
*/
/* Convert P to Affine, from (x,y,z) to (x,y) */
/* SU=160 */
void ECP_ZZZ_affine(ECP_ZZZ *P)
{
FP_YYY one, iz;
if (ECP_ZZZ_isinf(P)) return;
FP_YYY_one(&one);
if (FP_YYY_equals(&(P->z), &one)) return;
FP_YYY_inv(&iz, &(P->z),NULL);
FP_YYY_mul(&(P->x), &(P->x), &iz);
#if CURVETYPE_ZZZ==EDWARDS || CURVETYPE_ZZZ==WEIERSTRASS
FP_YYY_mul(&(P->y), &(P->y), &iz);
FP_YYY_reduce(&(P->y));
#endif
FP_YYY_reduce(&(P->x));
FP_YYY_copy(&(P->z), &one);
}
/* SU=120 */
void ECP_ZZZ_outputxyz(ECP_ZZZ *P)
{
BIG_XXX x, z;
if (ECP_ZZZ_isinf(P))
{
printf("Infinity\n");
return;
}
FP_YYY_reduce(&(P->x));
FP_YYY_redc(x, &(P->x));
FP_YYY_reduce(&(P->z));
FP_YYY_redc(z, &(P->z));
#if CURVETYPE_ZZZ!=MONTGOMERY
BIG_XXX y;
FP_YYY_reduce(&(P->y));
FP_YYY_redc(y, &(P->y));
printf("(");
BIG_XXX_output(x);
printf(",");
BIG_XXX_output(y);
printf(",");
BIG_XXX_output(z);
printf(")\n");
#else
printf("(");
BIG_XXX_output(x);
printf(",");
BIG_XXX_output(z);
printf(")\n");
#endif
}
/* SU=16 */
/* Output point P */
void ECP_ZZZ_output(ECP_ZZZ *P)
{
BIG_XXX x;
if (ECP_ZZZ_isinf(P))
{
printf("Infinity\n");
return;
}
ECP_ZZZ_affine(P);
#if CURVETYPE_ZZZ!=MONTGOMERY
BIG_XXX y;
FP_YYY_redc(x, &(P->x));
FP_YYY_redc(y, &(P->y));
printf("(");
BIG_XXX_output(x);
printf(",");
BIG_XXX_output(y);
printf(")\n");
#else
FP_YYY_redc(x, &(P->x));
printf("(");
BIG_XXX_output(x);
printf(")\n");
#endif
}
/* SU=16 */
/* Output point P */
void ECP_ZZZ_rawoutput(ECP_ZZZ *P)
{
BIG_XXX x, z;
#if CURVETYPE_ZZZ!=MONTGOMERY
BIG_XXX y;
FP_YYY_redc(x, &(P->x));
FP_YYY_redc(y, &(P->y));
FP_YYY_redc(z, &(P->z));
printf("(");
BIG_XXX_output(x);
printf(",");
BIG_XXX_output(y);
printf(",");
BIG_XXX_output(z);
printf(")\n");
#else
FP_YYY_redc(x, &(P->x));
FP_YYY_redc(z, &(P->z));
printf("(");
BIG_XXX_output(x);
printf(",");
BIG_XXX_output(z);
printf(")\n");
#endif
}
/* SU=88 */
/* Convert P to octet string */
void ECP_ZZZ_toOctet(octet *W, ECP_ZZZ *P, bool compress)
{
#if CURVETYPE_ZZZ==MONTGOMERY
BIG_XXX x;
ECP_ZZZ_get(x, P);
W->len = MODBYTES_XXX;// + 1;
//W->val[0] = 6;
BIG_XXX_toBytes(&(W->val[0]), x);
#else
BIG_XXX x, y;
ECP_ZZZ_get(x, y, P);
if (compress)
{
W->val[0] = 0x02;
if (BIG_XXX_parity(y) == 1) W->val[0] = 0x03;
W->len = MODBYTES_XXX + 1;
BIG_XXX_toBytes(&(W->val[1]), x);
}
else
{
W->val[0] = 0x04;
W->len = 2 * MODBYTES_XXX + 1;
BIG_XXX_toBytes(&(W->val[1]), x);
BIG_XXX_toBytes(&(W->val[MODBYTES_XXX + 1]), y);
}
#endif
}
/* SU=88 */
/* Restore P from octet string */
int ECP_ZZZ_fromOctet(ECP_ZZZ *P, octet *W)
{
#if CURVETYPE_ZZZ==MONTGOMERY
BIG_XXX x;
BIG_XXX_fromBytes(x, &(W->val[0]));
if (ECP_ZZZ_set(P, x)) return 1;
return 0;
#else
BIG_XXX x, y;
int typ = W->val[0];
BIG_XXX_fromBytes(x, &(W->val[1]));
if (typ == 0x04)
{
BIG_XXX_fromBytes(y, &(W->val[MODBYTES_XXX + 1]));
if (ECP_ZZZ_set(P, x, y)) return 1;
}
if (typ == 0x02 || typ == 0x03)
{
if (ECP_ZZZ_setx(P, x, typ & 1)) return 1;
}
return 0;
#endif
}
/* Set P=2P */
/* SU=272 */
void ECP_ZZZ_dbl(ECP_ZZZ *P)
{
#if CURVETYPE_ZZZ==WEIERSTRASS
FP_YYY t0, t1, t2, t3, x3, y3, z3, b;
#if CURVE_A_ZZZ == 0
FP_YYY_sqr(&t0, &(P->y)); //t0.sqr();
FP_YYY_mul(&t1, &(P->y), &(P->z)); //t1.mul(z);
FP_YYY_sqr(&t2, &(P->z)); //t2.sqr();
FP_YYY_add(&(P->z), &t0, &t0); //z.add(t0);
FP_YYY_norm(&(P->z)); //z.norm();
FP_YYY_add(&(P->z), &(P->z), &(P->z)); //z.add(z);
FP_YYY_add(&(P->z), &(P->z), &(P->z)); //z.add(z);
FP_YYY_norm(&(P->z)); //z.norm();
FP_YYY_imul(&t2, &t2, 3 * CURVE_B_I_ZZZ); //t2.imul(3*ROM.CURVE_B_I);
FP_YYY_mul(&x3, &t2, &(P->z)); //x3.mul(z);
FP_YYY_add(&y3, &t0, &t2); //y3.add(t2);
FP_YYY_norm(&y3); //y3.norm();
FP_YYY_mul(&(P->z), &(P->z), &t1); //z.mul(t1);
FP_YYY_add(&t1, &t2, &t2); //t1.add(t2);
FP_YYY_add(&t2, &t2, &t1); //t2.add(t1);
FP_YYY_sub(&t0, &t0, &t2); //t0.sub(t2);
FP_YYY_norm(&t0); //t0.norm();
FP_YYY_mul(&y3, &y3, &t0); //y3.mul(t0);
FP_YYY_add(&y3, &y3, &x3); //y3.add(x3);
FP_YYY_mul(&t1, &(P->x), &(P->y)); //t1.mul(y);
FP_YYY_norm(&t0); //x.norm();
FP_YYY_mul(&(P->x), &t0, &t1); //x.mul(t1);
FP_YYY_add(&(P->x), &(P->x), &(P->x)); //x.add(x);
FP_YYY_norm(&(P->x)); //x.norm();
FP_YYY_copy(&(P->y), &y3); //y.copy(y3);
FP_YYY_norm(&(P->y)); //y.norm();
#else
if (CURVE_B_I_ZZZ == 0) //if (ROM.CURVE_B_I==0)
FP_YYY_rcopy(&b, CURVE_B_ZZZ); //b.copy(new FP(new BIG(ROM.CURVE_B)));
FP_YYY_sqr(&t0, &(P->x)); //t0.sqr(); //1 x^2
FP_YYY_sqr(&t1, &(P->y)); //t1.sqr(); //2 y^2
FP_YYY_sqr(&t2, &(P->z)); //t2.sqr(); //3
FP_YYY_mul(&t3, &(P->x), &(P->y)); //t3.mul(y); //4
FP_YYY_add(&t3, &t3, &t3); //t3.add(t3);
FP_YYY_norm(&t3); //t3.norm();//5
FP_YYY_mul(&z3, &(P->z), &(P->x)); //z3.mul(x); //6
FP_YYY_add(&z3, &z3, &z3); //z3.add(z3);
FP_YYY_norm(&z3); //z3.norm();//7
if (CURVE_B_I_ZZZ == 0) //if (ROM.CURVE_B_I==0)
FP_YYY_mul(&y3, &t2, &b); //y3.mul(b); //8
else
FP_YYY_imul(&y3, &t2, CURVE_B_I_ZZZ); //y3.imul(ROM.CURVE_B_I);
FP_YYY_sub(&y3, &y3, &z3); //y3.sub(z3); //y3.norm(); //9 ***
FP_YYY_add(&x3, &y3, &y3); //x3.add(y3);
FP_YYY_norm(&x3); //x3.norm();//10
FP_YYY_add(&y3, &y3, &x3); //y3.add(x3); //y3.norm();//11
FP_YYY_sub(&x3, &t1, &y3); //x3.sub(y3);
FP_YYY_norm(&x3); //x3.norm();//12
FP_YYY_add(&y3, &y3, &t1); //y3.add(t1);
FP_YYY_norm(&y3); //y3.norm();//13
FP_YYY_mul(&y3, &y3, &x3); //y3.mul(x3); //14
FP_YYY_mul(&x3, &x3, &t3); //x3.mul(t3); //15
FP_YYY_add(&t3, &t2, &t2); //t3.add(t2); //16
FP_YYY_add(&t2, &t2, &t3); //t2.add(t3); //17
if (CURVE_B_I_ZZZ == 0) //if (ROM.CURVE_B_I==0)
FP_YYY_mul(&z3, &z3, &b); //z3.mul(b); //18
else
FP_YYY_imul(&z3, &z3, CURVE_B_I_ZZZ); //z3.imul(ROM.CURVE_B_I);
FP_YYY_sub(&z3, &z3, &t2); //z3.sub(t2); //z3.norm();//19
FP_YYY_sub(&z3, &z3, &t0); //z3.sub(t0);
FP_YYY_norm(&z3); //z3.norm();//20 ***
FP_YYY_add(&t3, &z3, &z3); //t3.add(z3); //t3.norm();//21
FP_YYY_add(&z3, &z3, &t3); //z3.add(t3);
FP_YYY_norm(&z3); //z3.norm(); //22
FP_YYY_add(&t3, &t0, &t0); //t3.add(t0); //t3.norm(); //23
FP_YYY_add(&t0, &t0, &t3); //t0.add(t3); //t0.norm();//24
FP_YYY_sub(&t0, &t0, &t2); //t0.sub(t2);
FP_YYY_norm(&t0); //t0.norm();//25
FP_YYY_mul(&t0, &t0, &z3); //t0.mul(z3);//26
FP_YYY_add(&y3, &y3, &t0); //y3.add(t0); //y3.norm();//27
FP_YYY_mul(&t0, &(P->y), &(P->z)); //t0.mul(z);//28
FP_YYY_add(&t0, &t0, &t0); //t0.add(t0);
FP_YYY_norm(&t0); //t0.norm(); //29
FP_YYY_mul(&z3, &z3, &t0); //z3.mul(t0);//30
FP_YYY_sub(&(P->x), &x3, &z3); //x3.sub(z3); //x3.norm();//31
FP_YYY_add(&t0, &t0, &t0); //t0.add(t0);
FP_YYY_norm(&t0); //t0.norm();//32
FP_YYY_add(&t1, &t1, &t1); //t1.add(t1);
FP_YYY_norm(&t1); //t1.norm();//33
FP_YYY_mul(&(P->z), &t0, &t1); //z3.mul(t1);//34
FP_YYY_norm(&(P->x)); //x.norm();
FP_YYY_copy(&(P->y), &y3); //y.copy(y3);
FP_YYY_norm(&(P->y)); //y.norm();
FP_YYY_norm(&(P->z)); //z.norm();
#endif
#endif
#if CURVETYPE_ZZZ==EDWARDS
/* Not using square for multiplication swap, as (1) it needs more adds, and (2) it triggers more reductions */
FP_YYY C, D, H, J;
FP_YYY_sqr(&C, &(P->x)); //C.sqr();
FP_YYY_mul(&(P->x), &(P->x), &(P->y)); //x.mul(y);
FP_YYY_add(&(P->x), &(P->x), &(P->x)); //x.add(x);
FP_YYY_norm(&(P->x)); //x.norm();
FP_YYY_sqr(&D, &(P->y)); //D.sqr();
#if CURVE_A_ZZZ == -1
FP_YYY_neg(&C, &C); // C.neg();
#endif
FP_YYY_add(&(P->y), &C, &D); //y.add(D);
FP_YYY_norm(&(P->y)); //y.norm();
FP_YYY_sqr(&H, &(P->z)); //H.sqr();
FP_YYY_add(&H, &H, &H); //H.add(H);
FP_YYY_sub(&J, &(P->y), &H); //J.sub(H);
FP_YYY_norm(&J); //J.norm();
FP_YYY_mul(&(P->x), &(P->x), &J); //x.mul(J);
FP_YYY_sub(&C, &C, &D); //C.sub(D);
FP_YYY_norm(&C); //C.norm();
FP_YYY_mul(&(P->z), &(P->y), &J); //z.mul(J);
FP_YYY_mul(&(P->y), &(P->y), &C); //y.mul(C);
#endif
#if CURVETYPE_ZZZ==MONTGOMERY
FP_YYY A, B, AA, BB, C;
FP_YYY_add(&A, &(P->x), &(P->z)); //A.add(z);
FP_YYY_norm(&A); //A.norm();
FP_YYY_sqr(&AA, &A); //AA.sqr();
FP_YYY_sub(&B, &(P->x), &(P->z)); //B.sub(z);
FP_YYY_norm(&B); //B.norm();
FP_YYY_sqr(&BB, &B); //BB.sqr();
FP_YYY_sub(&C, &AA, &BB); //C.sub(BB);
FP_YYY_norm(&C); //C.norm();
FP_YYY_mul(&(P->x), &AA, &BB); //x.mul(BB);
FP_YYY_imul(&A, &C, (CURVE_A_ZZZ + 2) / 4); //A.imul((ROM.CURVE_A+2)/4);
FP_YYY_add(&BB, &BB, &A); //BB.add(A);
FP_YYY_norm(&BB); //BB.norm();
FP_YYY_mul(&(P->z), &BB, &C); //z.mul(C);
#endif
}
#if CURVETYPE_ZZZ==MONTGOMERY
/* Set P+=Q. W is difference between P and Q and is affine */
void ECP_ZZZ_add(ECP_ZZZ *P, ECP_ZZZ *Q, ECP_ZZZ *W)
{
FP_YYY A, B, C, D, DA, CB;
FP_YYY_add(&A, &(P->x), &(P->z)); //A.add(z);
FP_YYY_sub(&B, &(P->x), &(P->z)); //B.sub(z);
FP_YYY_add(&C, &(Q->x), &(Q->z)); //C.add(Q.z);
FP_YYY_sub(&D, &(Q->x), &(Q->z)); //D.sub(Q.z);
FP_YYY_norm(&A); //A.norm();
FP_YYY_norm(&D); //D.norm();
FP_YYY_mul(&DA, &D, &A); //DA.mul(A);
FP_YYY_norm(&C); //C.norm();
FP_YYY_norm(&B); //B.norm();
FP_YYY_mul(&CB, &C, &B); //CB.mul(B);
FP_YYY_add(&A, &DA, &CB); //A.add(CB);
FP_YYY_norm(&A); //A.norm();
FP_YYY_sqr(&(P->x), &A); //A.sqr();
FP_YYY_sub(&B, &DA, &CB); //B.sub(CB);
FP_YYY_norm(&B); //B.norm();
FP_YYY_sqr(&B, &B); //B.sqr();
FP_YYY_mul(&(P->z), &(W->x), &B); //z.mul(B);
}
#else
/* Set P+=Q */
/* SU=248 */
void ECP_ZZZ_add(ECP_ZZZ *P, ECP_ZZZ *Q)
{
#if CURVETYPE_ZZZ==WEIERSTRASS
int b3;
FP_YYY t0, t1, t2, t3, t4, x3, y3, z3, b;
#if CURVE_A_ZZZ == 0
b3 = 3 * CURVE_B_I_ZZZ; //int b=3*ROM.CURVE_B_I;
FP_YYY_mul(&t0, &(P->x), &(Q->x)); //t0.mul(Q.x);
FP_YYY_mul(&t1, &(P->y), &(Q->y)); //t1.mul(Q.y);
FP_YYY_mul(&t2, &(P->z), &(Q->z)); //t2.mul(Q.z);
FP_YYY_add(&t3, &(P->x), &(P->y)); //t3.add(y);
FP_YYY_norm(&t3); //t3.norm();
FP_YYY_add(&t4, &(Q->x), &(Q->y)); //t4.add(Q.y);
FP_YYY_norm(&t4); //t4.norm();
FP_YYY_mul(&t3, &t3, &t4); //t3.mul(t4);
FP_YYY_add(&t4, &t0, &t1); //t4.add(t1);
FP_YYY_sub(&t3, &t3, &t4); //t3.sub(t4);
FP_YYY_norm(&t3); //t3.norm();
FP_YYY_add(&t4, &(P->y), &(P->z)); //t4.add(z);
FP_YYY_norm(&t4); //t4.norm();
FP_YYY_add(&x3, &(Q->y), &(Q->z)); //x3.add(Q.z);
FP_YYY_norm(&x3); //x3.norm();
FP_YYY_mul(&t4, &t4, &x3); //t4.mul(x3);
FP_YYY_add(&x3, &t1, &t2); //x3.add(t2);
FP_YYY_sub(&t4, &t4, &x3); //t4.sub(x3);
FP_YYY_norm(&t4); //t4.norm();
FP_YYY_add(&x3, &(P->x), &(P->z)); //x3.add(z);
FP_YYY_norm(&x3); //x3.norm();
FP_YYY_add(&y3, &(Q->x), &(Q->z)); //y3.add(Q.z);
FP_YYY_norm(&y3); //y3.norm();
FP_YYY_mul(&x3, &x3, &y3); //x3.mul(y3);
FP_YYY_add(&y3, &t0, &t2); //y3.add(t2);
FP_YYY_sub(&y3, &x3, &y3); //y3.rsub(x3);
FP_YYY_norm(&y3); //y3.norm();
FP_YYY_add(&x3, &t0, &t0); //x3.add(t0);
FP_YYY_add(&t0, &t0, &x3); //t0.add(x3);
FP_YYY_norm(&t0); //t0.norm();
FP_YYY_imul(&t2, &t2, b3); //t2.imul(b);
FP_YYY_add(&z3, &t1, &t2); //z3.add(t2);
FP_YYY_norm(&z3); //z3.norm();
FP_YYY_sub(&t1, &t1, &t2); //t1.sub(t2);
FP_YYY_norm(&t1); //t1.norm();
FP_YYY_imul(&y3, &y3, b3); //y3.imul(b);
FP_YYY_mul(&x3, &y3, &t4); //x3.mul(t4);
FP_YYY_mul(&t2, &t3, &t1); //t2.mul(t1);
FP_YYY_sub(&(P->x), &t2, &x3); //x3.rsub(t2);
FP_YYY_mul(&y3, &y3, &t0); //y3.mul(t0);
FP_YYY_mul(&t1, &t1, &z3); //t1.mul(z3);
FP_YYY_add(&(P->y), &y3, &t1); //y3.add(t1);
FP_YYY_mul(&t0, &t0, &t3); //t0.mul(t3);
FP_YYY_mul(&z3, &z3, &t4); //z3.mul(t4);
FP_YYY_add(&(P->z), &z3, &t0); //z3.add(t0);
FP_YYY_norm(&(P->x)); //x.norm();
FP_YYY_norm(&(P->y)); //y.norm();
FP_YYY_norm(&(P->z)); //z.norm();
#else
if (CURVE_B_I_ZZZ == 0) //if (ROM.CURVE_B_I==0)
FP_YYY_rcopy(&b, CURVE_B_ZZZ); //b.copy(new FP(new BIG(ROM.CURVE_B)));
FP_YYY_mul(&t0, &(P->x), &(Q->x)); //t0.mul(Q.x); //1
FP_YYY_mul(&t1, &(P->y), &(Q->y)); //t1.mul(Q.y); //2
FP_YYY_mul(&t2, &(P->z), &(Q->z)); //t2.mul(Q.z); //3
FP_YYY_add(&t3, &(P->x), &(P->y)); //t3.add(y);
FP_YYY_norm(&t3); //t3.norm(); //4
FP_YYY_add(&t4, &(Q->x), &(Q->y)); //t4.add(Q.y);
FP_YYY_norm(&t4); //t4.norm();//5
FP_YYY_mul(&t3, &t3, &t4); //t3.mul(t4);//6
FP_YYY_add(&t4, &t0, &t1); //t4.add(t1); //t4.norm(); //7
FP_YYY_sub(&t3, &t3, &t4); //t3.sub(t4);
FP_YYY_norm(&t3); //t3.norm(); //8
FP_YYY_add(&t4, &(P->y), &(P->z)); //t4.add(z);
FP_YYY_norm(&t4); //t4.norm();//9
FP_YYY_add(&x3, &(Q->y), &(Q->z)); //x3.add(Q.z);
FP_YYY_norm(&x3); //x3.norm();//10
FP_YYY_mul(&t4, &t4, &x3); //t4.mul(x3); //11
FP_YYY_add(&x3, &t1, &t2); //x3.add(t2); //x3.norm();//12
FP_YYY_sub(&t4, &t4, &x3); //t4.sub(x3);
FP_YYY_norm(&t4); //t4.norm();//13
FP_YYY_add(&x3, &(P->x), &(P->z)); //x3.add(z);
FP_YYY_norm(&x3); //x3.norm(); //14
FP_YYY_add(&y3, &(Q->x), &(Q->z)); //y3.add(Q.z);
FP_YYY_norm(&y3); //y3.norm();//15
FP_YYY_mul(&x3, &x3, &y3); //x3.mul(y3); //16
FP_YYY_add(&y3, &t0, &t2); //y3.add(t2); //y3.norm();//17
FP_YYY_sub(&y3, &x3, &y3); //y3.rsub(x3);
FP_YYY_norm(&y3); //y3.norm(); //18
if (CURVE_B_I_ZZZ == 0) //if (ROM.CURVE_B_I==0)
FP_YYY_mul(&z3, &t2, &b); //z3.mul(b); //18
else
FP_YYY_imul(&z3, &t2, CURVE_B_I_ZZZ); //z3.imul(ROM.CURVE_B_I);
FP_YYY_sub(&x3, &y3, &z3); //x3.sub(z3);
FP_YYY_norm(&x3); //x3.norm(); //20
FP_YYY_add(&z3, &x3, &x3); //z3.add(x3); //z3.norm(); //21
FP_YYY_add(&x3, &x3, &z3); //x3.add(z3); //x3.norm(); //22
FP_YYY_sub(&z3, &t1, &x3); //z3.sub(x3);
FP_YYY_norm(&z3); //z3.norm(); //23
FP_YYY_add(&x3, &x3, &t1); //x3.add(t1);
FP_YYY_norm(&x3); //x3.norm(); //24
if (CURVE_B_I_ZZZ == 0) //if (ROM.CURVE_B_I==0)
FP_YYY_mul(&y3, &y3, &b); //y3.mul(b); //18
else
FP_YYY_imul(&y3, &y3, CURVE_B_I_ZZZ); //y3.imul(ROM.CURVE_B_I);
FP_YYY_add(&t1, &t2, &t2); //t1.add(t2); //t1.norm();//26
FP_YYY_add(&t2, &t2, &t1); //t2.add(t1); //t2.norm();//27
FP_YYY_sub(&y3, &y3, &t2); //y3.sub(t2); //y3.norm(); //28
FP_YYY_sub(&y3, &y3, &t0); //y3.sub(t0);
FP_YYY_norm(&y3); //y3.norm(); //29
FP_YYY_add(&t1, &y3, &y3); //t1.add(y3); //t1.norm();//30
FP_YYY_add(&y3, &y3, &t1); //y3.add(t1);
FP_YYY_norm(&y3); //y3.norm(); //31
FP_YYY_add(&t1, &t0, &t0); //t1.add(t0); //t1.norm(); //32
FP_YYY_add(&t0, &t0, &t1); //t0.add(t1); //t0.norm();//33
FP_YYY_sub(&t0, &t0, &t2); //t0.sub(t2);
FP_YYY_norm(&t0); //t0.norm();//34
FP_YYY_mul(&t1, &t4, &y3); //t1.mul(y3);//35
FP_YYY_mul(&t2, &t0, &y3); //t2.mul(y3);//36
FP_YYY_mul(&y3, &x3, &z3); //y3.mul(z3);//37
FP_YYY_add(&(P->y), &y3, &t2); //y3.add(t2); //y3.norm();//38
FP_YYY_mul(&x3, &x3, &t3); //x3.mul(t3);//39
FP_YYY_sub(&(P->x), &x3, &t1); //x3.sub(t1);//40
FP_YYY_mul(&z3, &z3, &t4); //z3.mul(t4);//41
FP_YYY_mul(&t1, &t3, &t0); //t1.mul(t0);//42
FP_YYY_add(&(P->z), &z3, &t1); //z3.add(t1);
FP_YYY_norm(&(P->x)); //x.norm();
FP_YYY_norm(&(P->y)); //y.norm();
FP_YYY_norm(&(P->z)); //z.norm();
#endif
#else
FP_YYY A, B, C, D, E, F, G, b;
FP_YYY_mul(&A, &(P->z), &(Q->z)); //A.mul(Q.z);
FP_YYY_sqr(&B, &A); //B.sqr();
FP_YYY_mul(&C, &(P->x), &(Q->x)); //C.mul(Q.x);
FP_YYY_mul(&D, &(P->y), &(Q->y)); //D.mul(Q.y);
FP_YYY_mul(&E, &C, &D); //E.mul(D);
if (CURVE_B_I_ZZZ == 0) //if (ROM.CURVE_B_I==0)
{
FP_YYY_rcopy(&b, CURVE_B_ZZZ); //FP b=new FP(new BIG(ROM.CURVE_B));
FP_YYY_mul(&E, &E, &b); //E.mul(b);
}
else
FP_YYY_imul(&E, &E, CURVE_B_I_ZZZ); //E.imul(ROM.CURVE_B_I);
FP_YYY_sub(&F, &B, &E); //F.sub(E);
FP_YYY_add(&G, &B, &E); //G.add(E);
#if CURVE_A_ZZZ == 1
FP_YYY_sub(&E, &D, &C); //E.sub(C);
#endif
FP_YYY_add(&C, &C, &D); //C.add(D);
FP_YYY_add(&B, &(P->x), &(P->y)); //B.add(y);
FP_YYY_add(&D, &(Q->x), &(Q->y)); //D.add(Q.y);
FP_YYY_norm(&B); //B.norm();
FP_YYY_norm(&D); //D.norm();
FP_YYY_mul(&B, &B, &D); //B.mul(D);
FP_YYY_sub(&B, &B, &C); //B.sub(C);
FP_YYY_norm(&B); //B.norm();
FP_YYY_norm(&F); //F.norm();
FP_YYY_mul(&B, &B, &F); //B.mul(F);
FP_YYY_mul(&(P->x), &A, &B); //x.mul(B);
FP_YYY_norm(&G); //G.norm();
#if CURVE_A_ZZZ == 1
FP_YYY_norm(&E); //E.norm();
FP_YYY_mul(&C, &E, &G); //C.mul(G);
#endif
#if CURVE_A_ZZZ == -1
FP_YYY_norm(&C); //C.norm();
FP_YYY_mul(&C, &C, &G); //C.mul(G);
#endif
FP_YYY_mul(&(P->y), &A, &C); //y.mul(C);
FP_YYY_mul(&(P->z), &F, &G); //z.mul(G);
#endif
}
/* Set P-=Q */
/* SU=16 */
void ECP_ZZZ_sub(ECP_ZZZ *P, ECP_ZZZ *Q)
{
ECP_ZZZ NQ;
ECP_ZZZ_copy(&NQ, Q);
ECP_ZZZ_neg(&NQ);
ECP_ZZZ_add(P, &NQ);
}
#endif
#if CURVETYPE_ZZZ!=MONTGOMERY
/* constant time multiply by small integer of length bts - use ladder */
void ECP_ZZZ_pinmul(ECP_ZZZ *P, int e, int bts)
{
int i, b;
ECP_ZZZ R0, R1;
ECP_ZZZ_affine(P);
ECP_ZZZ_inf(&R0);
ECP_ZZZ_copy(&R1, P);
for (i = bts - 1; i >= 0; i--)
{
b = (e >> i) & 1;
ECP_ZZZ_copy(P, &R1);
ECP_ZZZ_add(P, &R0);
ECP_ZZZ_cswap(&R0, &R1, b);
ECP_ZZZ_copy(&R1, P);
ECP_ZZZ_dbl(&R0);
ECP_ZZZ_cswap(&R0, &R1, b);
}
ECP_ZZZ_copy(P, &R0);
}
#endif
/* Set P=r*P */
/* SU=424 */
void ECP_ZZZ_mul(ECP_ZZZ *P, BIG_XXX e)
{
#if CURVETYPE_ZZZ==MONTGOMERY
/* Montgomery ladder */
int nb, i, b;
ECP_ZZZ R0, R1, D;
if (ECP_ZZZ_isinf(P)) return;
if (BIG_XXX_iszilch(e))
{
ECP_ZZZ_inf(P);
return;
}
ECP_ZZZ_copy(&R0, P);
ECP_ZZZ_copy(&R1, P);
ECP_ZZZ_dbl(&R1);
ECP_ZZZ_copy(&D, P);
nb = BIG_XXX_nbits(e);
for (i = nb - 2; i >= 0; i--)
{
b = BIG_XXX_bit(e, i);
ECP_ZZZ_copy(P, &R1);
ECP_ZZZ_add(P, &R0, &D);
ECP_ZZZ_cswap(&R0, &R1, b);
ECP_ZZZ_copy(&R1, P);
ECP_ZZZ_dbl(&R0);
ECP_ZZZ_cswap(&R0, &R1, b);
}
ECP_ZZZ_copy(P, &R0);
#else
/* fixed size windows */
int i, nb, s, ns;
BIG_XXX mt, t;
ECP_ZZZ Q, W[8], C;
sign8 w[1 + (NLEN_XXX * BASEBITS_XXX + 3) / 4];
if (ECP_ZZZ_isinf(P)) return;
if (BIG_XXX_iszilch(e))
{
ECP_ZZZ_inf(P);
return;
}
/* precompute table */
ECP_ZZZ_copy(&Q, P);
ECP_ZZZ_dbl(&Q);
ECP_ZZZ_copy(&W[0], P);
for (i = 1; i < 8; i++)
{
ECP_ZZZ_copy(&W[i], &W[i - 1]);
ECP_ZZZ_add(&W[i], &Q);
}
//printf("W[1]= ");ECP_output(&W[1]); printf("\n");
/* make exponent odd - add 2P if even, P if odd */
BIG_XXX_copy(t, e);
s = BIG_XXX_parity(t);
BIG_XXX_inc(t, 1);
BIG_XXX_norm(t);
ns = BIG_XXX_parity(t);
BIG_XXX_copy(mt, t);
BIG_XXX_inc(mt, 1);
BIG_XXX_norm(mt);
BIG_XXX_cmove(t, mt, s);
ECP_ZZZ_cmove(&Q, P, ns);
ECP_ZZZ_copy(&C, &Q);
nb = 1 + (BIG_XXX_nbits(t) + 3) / 4;
/* convert exponent to signed 4-bit window */
for (i = 0; i < nb; i++)
{
w[i] = BIG_XXX_lastbits(t, 5) - 16;
BIG_XXX_dec(t, w[i]);
BIG_XXX_norm(t);
BIG_XXX_fshr(t, 4);
}
w[nb] = BIG_XXX_lastbits(t, 5);
ECP_ZZZ_copy(P, &W[(w[nb] - 1) / 2]);
for (i = nb - 1; i >= 0; i--)
{
ECP_ZZZ_select(&Q, W, w[i]);
ECP_ZZZ_dbl(P);
ECP_ZZZ_dbl(P);
ECP_ZZZ_dbl(P);
ECP_ZZZ_dbl(P);
ECP_ZZZ_add(P, &Q);
}
ECP_ZZZ_sub(P, &C); /* apply correction */
#endif
}
#if CURVETYPE_ZZZ!=MONTGOMERY
/* Set P=eP+fQ double multiplication */
/* constant time - as useful for GLV method in pairings */
/* SU=456 */
void ECP_ZZZ_mul2(ECP_ZZZ *P, ECP_ZZZ *Q, BIG_XXX e, BIG_XXX f)
{
BIG_XXX te, tf, mt;
ECP_ZZZ S, T, W[8], C;
sign8 w[1 + (NLEN_XXX * BASEBITS_XXX + 1) / 2];
int i, a, b, s, ns, nb;
BIG_XXX_copy(te, e);
BIG_XXX_copy(tf, f);
/* precompute table */
ECP_ZZZ_copy(&W[1], P);
ECP_ZZZ_sub(&W[1], Q); /* P+Q */
ECP_ZZZ_copy(&W[2], P);
ECP_ZZZ_add(&W[2], Q); /* P-Q */
ECP_ZZZ_copy(&S, Q);
ECP_ZZZ_dbl(&S); /* S=2Q */
ECP_ZZZ_copy(&W[0], &W[1]);
ECP_ZZZ_sub(&W[0], &S);
ECP_ZZZ_copy(&W[3], &W[2]);
ECP_ZZZ_add(&W[3], &S);
ECP_ZZZ_copy(&T, P);
ECP_ZZZ_dbl(&T); /* T=2P */
ECP_ZZZ_copy(&W[5], &W[1]);
ECP_ZZZ_add(&W[5], &T);
ECP_ZZZ_copy(&W[6], &W[2]);
ECP_ZZZ_add(&W[6], &T);
ECP_ZZZ_copy(&W[4], &W[5]);
ECP_ZZZ_sub(&W[4], &S);
ECP_ZZZ_copy(&W[7], &W[6]);
ECP_ZZZ_add(&W[7], &S);
/* if multiplier is odd, add 2, else add 1 to multiplier, and add 2P or P to correction */
s = BIG_XXX_parity(te);
BIG_XXX_inc(te, 1);
BIG_XXX_norm(te);
ns = BIG_XXX_parity(te);
BIG_XXX_copy(mt, te);
BIG_XXX_inc(mt, 1);
BIG_XXX_norm(mt);
BIG_XXX_cmove(te, mt, s);
ECP_ZZZ_cmove(&T, P, ns);
ECP_ZZZ_copy(&C, &T);
s = BIG_XXX_parity(tf);
BIG_XXX_inc(tf, 1);
BIG_XXX_norm(tf);
ns = BIG_XXX_parity(tf);
BIG_XXX_copy(mt, tf);
BIG_XXX_inc(mt, 1);
BIG_XXX_norm(mt);
BIG_XXX_cmove(tf, mt, s);
ECP_ZZZ_cmove(&S, Q, ns);
ECP_ZZZ_add(&C, &S);
BIG_XXX_add(mt, te, tf);
BIG_XXX_norm(mt);
nb = 1 + (BIG_XXX_nbits(mt) + 1) / 2;
/* convert exponent to signed 2-bit window */
for (i = 0; i < nb; i++)
{
a = BIG_XXX_lastbits(te, 3) - 4;
BIG_XXX_dec(te, a);
BIG_XXX_norm(te);
BIG_XXX_fshr(te, 2);
b = BIG_XXX_lastbits(tf, 3) - 4;
BIG_XXX_dec(tf, b);
BIG_XXX_norm(tf);
BIG_XXX_fshr(tf, 2);
w[i] = 4 * a + b;
}
w[nb] = (4 * BIG_XXX_lastbits(te, 3) + BIG_XXX_lastbits(tf, 3));
ECP_ZZZ_copy(P, &W[(w[nb] - 1) / 2]);
for (i = nb - 1; i >= 0; i--)
{
ECP_ZZZ_select(&T, W, w[i]);
ECP_ZZZ_dbl(P);
ECP_ZZZ_dbl(P);
ECP_ZZZ_add(P, &T);
}
ECP_ZZZ_sub(P, &C); /* apply correction */
}
#endif
int ECP_ZZZ_generator(ECP_ZZZ *G)
{
BIG_XXX x, y;
BIG_XXX_rcopy(x, CURVE_Gx_ZZZ);
#if CURVETYPE_ZZZ!=MONTGOMERY
BIG_XXX_rcopy(y, CURVE_Gy_ZZZ);
return ECP_ZZZ_set(G, x, y);
#else
return ECP_ZZZ_set(G, x);
#endif
}
#ifdef HAS_MAIN
int main()
{
int i;
ECP_ZZZ G, P;
csprng RNG;
BIG_XXX r, s, x, y, b, m, w, q;
BIG_XXX_rcopy(x, CURVE_Gx);
#if CURVETYPE_ZZZ!=MONTGOMERY
BIG_XXX_rcopy(y, CURVE_Gy);
#endif
BIG_XXX_rcopy(m, Modulus_YYY);
printf("x= ");
BIG_XXX_output(x);
printf("\n");
#if CURVETYPE_ZZZ!=MONTGOMERY
printf("y= ");
BIG_XXX_output(y);
printf("\n");
#endif
RNG_seed(&RNG, 3, "abc");
#if CURVETYPE_ZZZ!=MONTGOMERY
ECP_ZZZ_set(&G, x, y);
#else
ECP_ZZZ_set(&G, x);
#endif
if (ECP_ZZZ_isinf(&G)) printf("Failed to set - point not on curve\n");
else printf("set success\n");
ECP_ZZZ_output(&G);
BIG_XXX_rcopy(r, CURVE_Order); //BIG_dec(r,7);
printf("r= ");
BIG_XXX_output(r);
printf("\n");
ECP_ZZZ_copy(&P, &G);
ECP_ZZZ_mul(&P, r);
ECP_ZZZ_output(&P);
//exit(0);
BIG_XXX_randomnum(w, &RNG);
BIG_XXX_mod(w, r);
ECP_ZZZ_copy(&P, &G);
ECP_ZZZ_mul(&P, w);
ECP_ZZZ_output(&P);
return 0;
}
#endif
|
824146.c | // This file contains tests for the system arguments (argv).
#include "tests.h"
#include <stdio.h>
int main(int argc, const char** argv)
{
plan(2);
// When this file is converted to go it is run through "go test" that needs
// some extra arguments before the standard C arguments. We need to adjust
// an offset so that the C program and the Go program read the same index
// for the first index of the real arguments.
int offset = 0;
// More than three arguments means it must be run under "go test". If not
// the assertion immediately below will fail.
if (argc > 3) {
offset = argc - 3;
}
// We cannot compare the zeroth argument because it will be different for C
// and Go.
// is_streq(argv[0], "build/go.out");
is_streq(argv[1 + offset], "some");
is_streq(argv[2 + offset], "args");
int os = 9;
(void)(os);
done_testing();
}
void os() {}
|
803600.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.
*/
#include <assert.h>
#include <stdio.h>
#include <apr_lib.h>
#include <apr_buckets.h>
#include <apr_file_info.h>
#include <apr_file_io.h>
#include <apr_fnmatch.h>
#include <apr_hash.h>
#include <apr_strings.h>
#include <apr_tables.h>
#include "md.h"
#include "md_crypt.h"
#include "md_json.h"
#include "md_http.h"
#include "md_log.h"
#include "md_jws.h"
#include "md_result.h"
#include "md_store.h"
#include "md_util.h"
#include "md_acme.h"
#include "md_acme_authz.h"
md_acme_authz_t *md_acme_authz_create(apr_pool_t *p)
{
md_acme_authz_t *authz;
authz = apr_pcalloc(p, sizeof(*authz));
return authz;
}
/**************************************************************************************************/
/* Register a new authorization */
typedef struct {
size_t index;
const char *type;
const char *uri;
const char *token;
const char *key_authz;
} md_acme_authz_cha_t;
typedef struct {
apr_pool_t *p;
md_acme_t *acme;
const char *domain;
md_acme_authz_t *authz;
md_acme_authz_cha_t *challenge;
} authz_req_ctx;
static void authz_req_ctx_init(authz_req_ctx *ctx, md_acme_t *acme,
const char *domain, md_acme_authz_t *authz, apr_pool_t *p)
{
memset(ctx, 0, sizeof(*ctx));
ctx->p = p;
ctx->acme = acme;
ctx->domain = domain;
ctx->authz = authz;
}
/**************************************************************************************************/
/* Update an existing authorization */
apr_status_t md_acme_authz_retrieve(md_acme_t *acme, apr_pool_t *p, const char *url,
md_acme_authz_t **pauthz)
{
md_acme_authz_t *authz;
apr_status_t rv;
authz = apr_pcalloc(p, sizeof(*authz));
authz->url = apr_pstrdup(p, url);
rv = md_acme_authz_update(authz, acme, p);
*pauthz = (APR_SUCCESS == rv)? authz : NULL;
return rv;
}
typedef struct {
apr_pool_t *p;
md_acme_authz_t *authz;
} error_ctx_t;
static int copy_challenge_error(void *baton, size_t index, md_json_t *json)
{
error_ctx_t *ctx = baton;
(void)index;
if (md_json_has_key(json, MD_KEY_ERROR, NULL)) {
ctx->authz->error_type = md_json_dups(ctx->p, json, MD_KEY_ERROR, MD_KEY_TYPE, NULL);
ctx->authz->error_detail = md_json_dups(ctx->p, json, MD_KEY_ERROR, MD_KEY_DETAIL, NULL);
ctx->authz->error_subproblems = md_json_dupj(ctx->p, json, MD_KEY_ERROR, MD_KEY_SUBPROBLEMS, NULL);
}
return 1;
}
apr_status_t md_acme_authz_update(md_acme_authz_t *authz, md_acme_t *acme, apr_pool_t *p)
{
md_json_t *json;
const char *s, *err;
md_log_level_t log_level;
apr_status_t rv;
error_ctx_t ctx;
assert(acme);
assert(acme->http);
assert(authz);
assert(authz->url);
authz->state = MD_ACME_AUTHZ_S_UNKNOWN;
json = NULL;
authz->error_type = authz->error_detail = NULL;
authz->error_subproblems = NULL;
err = "unable to parse response";
log_level = MD_LOG_ERR;
if (APR_SUCCESS == (rv = md_acme_get_json(&json, acme, authz->url, p))
&& (s = md_json_gets(json, MD_KEY_STATUS, NULL))) {
authz->domain = md_json_gets(json, MD_KEY_IDENTIFIER, MD_KEY_VALUE, NULL);
authz->resource = json;
if (!strcmp(s, "pending")) {
authz->state = MD_ACME_AUTHZ_S_PENDING;
err = "challenge 'pending'";
log_level = MD_LOG_DEBUG;
}
else if (!strcmp(s, "valid")) {
authz->state = MD_ACME_AUTHZ_S_VALID;
err = "challenge 'valid'";
log_level = MD_LOG_DEBUG;
}
else if (!strcmp(s, "invalid")) {
ctx.p = p;
ctx.authz = authz;
authz->state = MD_ACME_AUTHZ_S_INVALID;
md_json_itera(copy_challenge_error, &ctx, json, MD_KEY_CHALLENGES, NULL);
err = "challenge 'invalid'";
}
}
if (json && authz->state == MD_ACME_AUTHZ_S_UNKNOWN) {
err = "unable to understand response";
rv = APR_EINVAL;
}
if (md_log_is_level(p, log_level)) {
md_log_perror(MD_LOG_MARK, log_level, rv, p, "ACME server authz: %s for %s at %s. "
"Exact response was: %s", err, authz->domain, authz->url,
json? md_json_writep(json, p, MD_JSON_FMT_COMPACT) : "not available");
}
return rv;
}
/**************************************************************************************************/
/* response to a challenge */
static md_acme_authz_cha_t *cha_from_json(apr_pool_t *p, size_t index, md_json_t *json)
{
md_acme_authz_cha_t * cha;
cha = apr_pcalloc(p, sizeof(*cha));
cha->index = index;
cha->type = md_json_dups(p, json, MD_KEY_TYPE, NULL);
if (md_json_has_key(json, MD_KEY_URL, NULL)) { /* ACMEv2 */
cha->uri = md_json_dups(p, json, MD_KEY_URL, NULL);
}
else { /* ACMEv1 */
cha->uri = md_json_dups(p, json, MD_KEY_URI, NULL);
}
cha->token = md_json_dups(p, json, MD_KEY_TOKEN, NULL);
cha->key_authz = md_json_dups(p, json, MD_KEY_KEYAUTHZ, NULL);
return cha;
}
static apr_status_t on_init_authz_resp(md_acme_req_t *req, void *baton)
{
md_json_t *jpayload;
(void)baton;
jpayload = md_json_create(req->p);
return md_acme_req_body_init(req, jpayload);
}
static apr_status_t authz_http_set(md_acme_t *acme, apr_pool_t *p, const apr_table_t *hdrs,
md_json_t *body, void *baton)
{
authz_req_ctx *ctx = baton;
(void)acme;
(void)p;
(void)hdrs;
(void)body;
md_log_perror(MD_LOG_MARK, MD_LOG_TRACE1, 0, ctx->p, "updated authz %s", ctx->authz->url);
return APR_SUCCESS;
}
static apr_status_t setup_key_authz(md_acme_authz_cha_t *cha, md_acme_authz_t *authz,
md_acme_t *acme, apr_pool_t *p, int *pchanged)
{
const char *thumb64, *key_authz;
apr_status_t rv;
(void)authz;
assert(cha);
assert(cha->token);
*pchanged = 0;
if (APR_SUCCESS == (rv = md_jws_pkey_thumb(&thumb64, p, acme->acct_key))) {
key_authz = apr_psprintf(p, "%s.%s", cha->token, thumb64);
if (cha->key_authz) {
if (strcmp(key_authz, cha->key_authz)) {
/* Hu? Did the account change key? */
cha->key_authz = NULL;
}
}
if (!cha->key_authz) {
cha->key_authz = key_authz;
*pchanged = 1;
}
}
return rv;
}
static apr_status_t cha_http_01_setup(md_acme_authz_cha_t *cha, md_acme_authz_t *authz,
md_acme_t *acme, md_store_t *store,
md_pkeys_spec_t *key_specs,
apr_array_header_t *acme_tls_1_domains, const char *mdomain,
apr_table_t *env, md_result_t *result, apr_pool_t *p)
{
const char *data;
apr_status_t rv;
int notify_server;
(void)key_specs;
(void)env;
(void)acme_tls_1_domains;
(void)mdomain;
if (APR_SUCCESS != (rv = setup_key_authz(cha, authz, acme, p, ¬ify_server))) {
goto out;
}
rv = md_store_load(store, MD_SG_CHALLENGES, authz->domain, MD_FN_HTTP01,
MD_SV_TEXT, (void**)&data, p);
if ((APR_SUCCESS == rv && strcmp(cha->key_authz, data)) || APR_STATUS_IS_ENOENT(rv)) {
const char *content = apr_psprintf(p, "%s\n", cha->key_authz);
rv = md_store_save(store, p, MD_SG_CHALLENGES, authz->domain, MD_FN_HTTP01,
MD_SV_TEXT, (void*)content, 0);
notify_server = 1;
}
if (APR_SUCCESS == rv && notify_server) {
authz_req_ctx ctx;
const char *event;
/* Raise event that challenge data has been set up before we tell the
ACME server. Clusters might want to distribute it. */
event = apr_psprintf(p, "challenge-setup:%s:%s", MD_AUTHZ_TYPE_HTTP01, authz->domain);
rv = md_result_raise(result, event, p);
if (APR_SUCCESS != rv) {
md_log_perror(MD_LOG_MARK, MD_LOG_DEBUG, rv, p,
"%s: event '%s' failed. aborting challenge setup",
authz->domain, event);
goto out;
}
/* challenge is setup or was changed from previous data, tell ACME server
* so it may (re)try verification */
authz_req_ctx_init(&ctx, acme, NULL, authz, p);
ctx.challenge = cha;
rv = md_acme_POST(acme, cha->uri, on_init_authz_resp, authz_http_set, NULL, NULL, &ctx);
}
out:
return rv;
}
void tls_alpn01_fnames(apr_pool_t *p, md_pkey_spec_t *kspec, char **keyfn, char **certfn )
{
*keyfn = apr_pstrcat(p, "acme-tls-alpn-01-", md_pkey_filename(kspec, p), NULL);
*certfn = apr_pstrcat(p, "acme-tls-alpn-01-", md_chain_filename(kspec, p), NULL);
}
static apr_status_t cha_tls_alpn_01_setup(md_acme_authz_cha_t *cha, md_acme_authz_t *authz,
md_acme_t *acme, md_store_t *store,
md_pkeys_spec_t *key_specs,
apr_array_header_t *acme_tls_1_domains, const char *mdomain,
apr_table_t *env, md_result_t *result, apr_pool_t *p)
{
const char *acme_id, *token;
apr_status_t rv;
int notify_server;
md_data_t data;
int i;
(void)env;
(void)mdomain;
if (md_array_str_index(acme_tls_1_domains, authz->domain, 0, 0) < 0) {
rv = APR_ENOTIMPL;
if (acme_tls_1_domains->nelts) {
md_log_perror(MD_LOG_MARK, MD_LOG_DEBUG, 0, p,
"%s: protocol 'acme-tls/1' seems not enabled for this domain, "
"but is enabled for other associated domains. "
"Continuing with fingers crossed.", authz->domain);
}
else {
md_log_perror(MD_LOG_MARK, MD_LOG_INFO, 0, p,
"%s: protocol 'acme-tls/1' seems not enabled for this or "
"any other associated domain. Not attempting challenge "
"type tls-alpn-01.", authz->domain);
goto out;
}
}
if (APR_SUCCESS != (rv = setup_key_authz(cha, authz, acme, p, ¬ify_server))) {
goto out;
}
/* Create a "tls-alpn-01" certificate for the domain we want to authenticate.
* The server will need to answer a TLS connection with SNI == authz->domain
* and ALPN procotol "acme-tls/1" with this certificate.
*/
md_data_init_str(&data, cha->key_authz);
rv = md_crypt_sha256_digest_hex(&token, p, &data);
if (APR_SUCCESS != rv) {
md_log_perror(MD_LOG_MARK, MD_LOG_ERR, rv, p, "%s: create tls-alpn-01 validation token",
authz->domain);
goto out;
}
acme_id = apr_psprintf(p, "critical,DER:04:20:%s", token);
/* Each configured key type must be generated to ensure:
* that any fallback certs already given to mod_ssl are replaced.
* We expect that the validation client (at the CA) can deal with at
* least one of them.
*/
for (i = 0; i < md_pkeys_spec_count(key_specs); ++i) {
char *kfn, *cfn;
md_cert_t *cha_cert;
md_pkey_t *cha_key;
md_pkey_spec_t *key_spec;
key_spec = md_pkeys_spec_get(key_specs, i);
tls_alpn01_fnames(p, key_spec, &kfn, &cfn);
rv = md_store_load(store, MD_SG_CHALLENGES, authz->domain, cfn,
MD_SV_CERT, (void**)&cha_cert, p);
if ((APR_SUCCESS == rv && !md_cert_covers_domain(cha_cert, authz->domain))
|| APR_STATUS_IS_ENOENT(rv)) {
if (APR_SUCCESS != (rv = md_pkey_gen(&cha_key, p, key_spec))) {
md_log_perror(MD_LOG_MARK, MD_LOG_ERR, rv, p, "%s: create tls-alpn-01 %s challenge key",
authz->domain, md_pkey_spec_name(key_spec));
goto out;
}
if (APR_SUCCESS != (rv = md_cert_make_tls_alpn_01(&cha_cert, authz->domain, acme_id, cha_key,
apr_time_from_sec(7 * MD_SECS_PER_DAY), p))) {
md_log_perror(MD_LOG_MARK, MD_LOG_ERR, rv, p, "%s: create tls-alpn-01 %s challenge cert",
authz->domain, md_pkey_spec_name(key_spec));
goto out;
}
if (APR_SUCCESS == (rv = md_store_save(store, p, MD_SG_CHALLENGES, authz->domain, kfn,
MD_SV_PKEY, (void*)cha_key, 0))) {
rv = md_store_save(store, p, MD_SG_CHALLENGES, authz->domain, cfn,
MD_SV_CERT, (void*)cha_cert, 0);
}
++notify_server;
}
}
if (APR_SUCCESS == rv && notify_server) {
authz_req_ctx ctx;
const char *event;
/* Raise event that challenge data has been set up before we tell the
ACME server. Clusters might want to distribute it. */
event = apr_psprintf(p, "challenge-setup:%s:%s", MD_AUTHZ_TYPE_TLSALPN01, authz->domain);
rv = md_result_raise(result, event, p);
if (APR_SUCCESS != rv) {
md_log_perror(MD_LOG_MARK, MD_LOG_DEBUG, rv, p,
"%s: event '%s' failed. aborting challenge setup",
authz->domain, event);
goto out;
}
/* challenge is setup or was changed from previous data, tell ACME server
* so it may (re)try verification */
authz_req_ctx_init(&ctx, acme, NULL, authz, p);
ctx.challenge = cha;
rv = md_acme_POST(acme, cha->uri, on_init_authz_resp, authz_http_set, NULL, NULL, &ctx);
}
out:
return rv;
}
static apr_status_t cha_dns_01_setup(md_acme_authz_cha_t *cha, md_acme_authz_t *authz,
md_acme_t *acme, md_store_t *store,
md_pkeys_spec_t *key_specs,
apr_array_header_t *acme_tls_1_domains, const char *mdomain,
apr_table_t *env, md_result_t *result, apr_pool_t *p)
{
const char *token;
const char * const *argv;
const char *cmdline, *dns01_cmd;
apr_status_t rv;
int exit_code, notify_server;
authz_req_ctx ctx;
md_data_t data;
const char *event;
(void)store;
(void)key_specs;
(void)acme_tls_1_domains;
dns01_cmd = apr_table_get(env, MD_KEY_CMD_DNS01);
if (!dns01_cmd) {
rv = APR_ENOTIMPL;
md_log_perror(MD_LOG_MARK, MD_LOG_DEBUG, rv, p, "%s: dns-01 command not set",
authz->domain);
goto out;
}
if (APR_SUCCESS != (rv = setup_key_authz(cha, authz, acme, p, ¬ify_server))) {
goto out;
}
md_data_init_str(&data, cha->key_authz);
rv = md_crypt_sha256_digest64(&token, p, &data);
if (APR_SUCCESS != rv) {
md_log_perror(MD_LOG_MARK, MD_LOG_ERR, rv, p, "%s: create dns-01 token for %s",
mdomain, authz->domain);
goto out;
}
cmdline = apr_psprintf(p, "%s setup %s %s", dns01_cmd, authz->domain, token);
md_log_perror(MD_LOG_MARK, MD_LOG_DEBUG, 0, p,
"%s: dns-01 setup command: %s", authz->domain, cmdline);
apr_tokenize_to_argv(cmdline, (char***)&argv, p);
if (APR_SUCCESS != (rv = md_util_exec(p, argv[0], argv, NULL, &exit_code))) {
md_log_perror(MD_LOG_MARK, MD_LOG_WARNING, rv, p,
"%s: dns-01 setup command failed to execute for %s", mdomain, authz->domain);
goto out;
}
if (exit_code) {
rv = APR_EGENERAL;
md_log_perror(MD_LOG_MARK, MD_LOG_INFO, rv, p,
"%s: dns-01 setup command returns %d for %s", mdomain, exit_code, authz->domain);
goto out;
}
/* Raise event that challenge data has been set up before we tell the
ACME server. Clusters might want to distribute it. */
event = apr_psprintf(p, "challenge-setup:%s:%s", MD_AUTHZ_TYPE_DNS01, authz->domain);
rv = md_result_raise(result, event, p);
if (APR_SUCCESS != rv) {
md_log_perror(MD_LOG_MARK, MD_LOG_DEBUG, rv, p,
"%s: event '%s' failed. aborting challenge setup",
authz->domain, event);
goto out;
}
/* challenge is setup, tell ACME server so it may (re)try verification */
md_log_perror(MD_LOG_MARK, MD_LOG_DEBUG, rv, p, "%s: dns-01 setup succeeded for %s",
mdomain, authz->domain);
authz_req_ctx_init(&ctx, acme, NULL, authz, p);
ctx.challenge = cha;
rv = md_acme_POST(acme, cha->uri, on_init_authz_resp, authz_http_set, NULL, NULL, &ctx);
out:
return rv;
}
static apr_status_t cha_dns_01_teardown(md_store_t *store, const char *domain, const char *mdomain,
apr_table_t *env, apr_pool_t *p)
{
const char * const *argv;
const char *cmdline, *dns01_cmd;
apr_status_t rv;
int exit_code;
(void)store;
dns01_cmd = apr_table_get(env, MD_KEY_CMD_DNS01);
if (!dns01_cmd) {
rv = APR_ENOTIMPL;
md_log_perror(MD_LOG_MARK, MD_LOG_DEBUG, 0, p, "%s: dns-01 command not set for %s",
mdomain, domain);
goto out;
}
cmdline = apr_psprintf(p, "%s teardown %s", dns01_cmd, domain);
apr_tokenize_to_argv(cmdline, (char***)&argv, p);
if (APR_SUCCESS != (rv = md_util_exec(p, argv[0], argv, NULL, &exit_code)) || exit_code) {
md_log_perror(MD_LOG_MARK, MD_LOG_WARNING, rv, p,
"%s: dns-01 teardown command failed (exit code=%d) for %s",
mdomain, exit_code, domain);
}
out:
return rv;
}
static apr_status_t cha_teardown_dir(md_store_t *store, const char *domain, const char *mdomain,
apr_table_t *env, apr_pool_t *p)
{
(void)env;
(void)mdomain;
return md_store_purge(store, p, MD_SG_CHALLENGES, domain);
}
typedef apr_status_t cha_setup(md_acme_authz_cha_t *cha, md_acme_authz_t *authz,
md_acme_t *acme, md_store_t *store,
md_pkeys_spec_t *key_specs,
apr_array_header_t *acme_tls_1_domains, const char *mdomain,
apr_table_t *env, md_result_t *result, apr_pool_t *p);
typedef apr_status_t cha_teardown(md_store_t *store, const char *domain, const char *mdomain,
apr_table_t *env, apr_pool_t *p);
typedef struct {
const char *name;
cha_setup *setup;
cha_teardown *teardown;
} cha_type;
static const cha_type CHA_TYPES[] = {
{ MD_AUTHZ_TYPE_HTTP01, cha_http_01_setup, cha_teardown_dir },
{ MD_AUTHZ_TYPE_TLSALPN01, cha_tls_alpn_01_setup, cha_teardown_dir },
{ MD_AUTHZ_TYPE_DNS01, cha_dns_01_setup, cha_dns_01_teardown },
};
static const apr_size_t CHA_TYPES_LEN = (sizeof(CHA_TYPES)/sizeof(CHA_TYPES[0]));
typedef struct {
apr_pool_t *p;
const char *type;
md_acme_authz_cha_t *accepted;
apr_array_header_t *offered;
} cha_find_ctx;
static apr_status_t collect_offered(void *baton, size_t index, md_json_t *json)
{
cha_find_ctx *ctx = baton;
const char *ctype;
(void)index;
if ((ctype = md_json_gets(json, MD_KEY_TYPE, NULL))) {
APR_ARRAY_PUSH(ctx->offered, const char*) = apr_pstrdup(ctx->p, ctype);
}
return 1;
}
static apr_status_t find_type(void *baton, size_t index, md_json_t *json)
{
cha_find_ctx *ctx = baton;
const char *ctype = md_json_gets(json, MD_KEY_TYPE, NULL);
if (ctype && !apr_strnatcasecmp(ctx->type, ctype)) {
ctx->accepted = cha_from_json(ctx->p, index, json);
return 0;
}
return 1;
}
apr_status_t md_acme_authz_respond(md_acme_authz_t *authz, md_acme_t *acme, md_store_t *store,
apr_array_header_t *challenges, md_pkeys_spec_t *key_specs,
apr_array_header_t *acme_tls_1_domains, const char *mdomain,
apr_table_t *env, apr_pool_t *p, const char **psetup_token,
md_result_t *result)
{
apr_status_t rv;
int i, j;
cha_find_ctx fctx;
const char *challenge_setup;
assert(acme);
assert(authz);
assert(authz->resource);
fctx.p = p;
fctx.accepted = NULL;
/* Look in the order challenge types are defined:
* - if they are offered by the CA, try to set it up
* - if setup was successful, we are done and the CA will evaluate us
* - if setup failed, continue to look for another supported challenge type
* - if there is no overlap in types, tell the user that she has to configure
* either more types (dns, tls-alpn-01), make ports available or refrain
* from using wildcard domains when dns is not available. etc.
* - if there was an overlap, but no setup was successful, report that. We
* will retry this, maybe the failure is temporary (e.g. command to setup DNS
*/
md_result_printf(result, 0, "%s: selecting suitable authorization challenge "
"type, this domain supports %s",
authz->domain, apr_array_pstrcat(p, challenges, ' '));
rv = APR_ENOTIMPL;
challenge_setup = NULL;
for (i = 0; i < challenges->nelts; ++i) {
fctx.type = APR_ARRAY_IDX(challenges, i, const char *);
fctx.accepted = NULL;
md_json_itera(find_type, &fctx, authz->resource, MD_KEY_CHALLENGES, NULL);
md_log_perror(MD_LOG_MARK, MD_LOG_TRACE1, 0, p,
"%s: challenge type '%s' for %s: %s",
authz->domain, fctx.type, mdomain,
fctx.accepted? "maybe acceptable" : "not applicable");
if (fctx.accepted) {
for (j = 0; j < (int)CHA_TYPES_LEN; ++j) {
if (!apr_strnatcasecmp(CHA_TYPES[j].name, fctx.accepted->type)) {
md_result_activity_printf(result, "Setting up challenge '%s' for domain %s",
fctx.accepted->type, authz->domain);
rv = CHA_TYPES[j].setup(fctx.accepted, authz, acme, store, key_specs,
acme_tls_1_domains, mdomain, env, result, p);
if (APR_SUCCESS == rv) {
md_log_perror(MD_LOG_MARK, MD_LOG_DEBUG, rv, p,
"%s: set up challenge '%s' for %s",
authz->domain, fctx.accepted->type, mdomain);
challenge_setup = CHA_TYPES[i].name;
goto out;
}
md_result_printf(result, rv, "error setting up challenge '%s' for %s, "
"for domain %s, looking for other option",
fctx.accepted->type, authz->domain, mdomain);
md_result_log(result, MD_LOG_INFO);
}
}
}
}
out:
*psetup_token = (APR_SUCCESS == rv)? apr_psprintf(p, "%s:%s", challenge_setup, authz->domain) : NULL;
if (!fctx.accepted || APR_ENOTIMPL == rv) {
rv = APR_EINVAL;
fctx.offered = apr_array_make(p, 5, sizeof(const char*));
md_json_itera(collect_offered, &fctx, authz->resource, MD_KEY_CHALLENGES, NULL);
md_result_printf(result, rv, "None of offered challenge types for domain %s are supported. "
"The server offered '%s' and available are: '%s'.",
authz->domain,
apr_array_pstrcat(p, fctx.offered, ' '),
apr_array_pstrcat(p, challenges, ' '));
result->problem = "challenge-mismatch";
md_result_log(result, MD_LOG_ERR);
}
else if (APR_SUCCESS != rv) {
fctx.offered = apr_array_make(p, 5, sizeof(const char*));
md_json_itera(collect_offered, &fctx, authz->resource, MD_KEY_CHALLENGES, NULL);
md_result_printf(result, rv, "None of the offered challenge types %s offered "
"for domain %s could be setup successfully. Please check the "
"log for errors.", authz->domain,
apr_array_pstrcat(p, fctx.offered, ' '));
result->problem = "challenge-setup-failure";
md_result_log(result, MD_LOG_ERR);
}
return rv;
}
apr_status_t md_acme_authz_teardown(struct md_store_t *store, const char *token,
const char *mdomain, apr_table_t *env, apr_pool_t *p)
{
char *challenge, *domain;
int i;
if (strchr(token, ':')) {
challenge = apr_pstrdup(p, token);
domain = strchr(challenge, ':');
*domain = '\0'; domain++;
for (i = 0; i < (int)CHA_TYPES_LEN; ++i) {
if (!apr_strnatcasecmp(CHA_TYPES[i].name, challenge)) {
if (CHA_TYPES[i].teardown) {
return CHA_TYPES[i].teardown(store, domain, mdomain, env, p);
}
break;
}
}
}
return APR_SUCCESS;
}
|
596278.c | /*-------------------------------------------------------------------------
*
* varchar.c
* Functions for the built-in types char(n) and varchar(n).
*
* Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/backend/utils/adt/varchar.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "access/detoast.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_type.h"
#include "libpq/pqformat.h"
#include "nodes/nodeFuncs.h"
#include "nodes/supportnodes.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/hashutils.h"
#include "utils/lsyscache.h"
#include "utils/pg_locale.h"
#include "utils/varlena.h"
#include "mb/pg_wchar.h"
/* common code for bpchartypmodin and varchartypmodin */
static int32
anychar_typmodin(ArrayType *ta, const char *typename)
{
int32 typmod;
int32 *tl;
int n;
tl = ArrayGetIntegerTypmods(ta, &n);
/*
* we're not too tense about good error message here because grammar
* shouldn't allow wrong number of modifiers for CHAR
*/
if (n != 1)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("invalid type modifier")));
if (*tl < 1)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("length for type %s must be at least 1", typename)));
if (*tl > MaxAttrSize)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("length for type %s cannot exceed %d",
typename, MaxAttrSize)));
/*
* For largely historical reasons, the typmod is VARHDRSZ plus the number
* of characters; there is enough client-side code that knows about that
* that we'd better not change it.
*/
typmod = VARHDRSZ + *tl;
return typmod;
}
/* common code for bpchartypmodout and varchartypmodout */
static char *
anychar_typmodout(int32 typmod)
{
char *res = (char *) palloc(64);
if (typmod > VARHDRSZ)
snprintf(res, 64, "(%d)", (int) (typmod - VARHDRSZ));
else
*res = '\0';
return res;
}
/*
* CHAR() and VARCHAR() types are part of the SQL standard. CHAR()
* is for blank-padded string whose length is specified in CREATE TABLE.
* VARCHAR is for storing string whose length is at most the length specified
* at CREATE TABLE time.
*
* It's hard to implement these types because we cannot figure out
* the length of the type from the type itself. I changed (hopefully all) the
* fmgr calls that invoke input functions of a data type to supply the
* length also. (eg. in INSERTs, we have the tupleDescriptor which contains
* the length of the attributes and hence the exact length of the char() or
* varchar(). We pass this to bpcharin() or varcharin().) In the case where
* we cannot determine the length, we pass in -1 instead and the input
* converter does not enforce any length check.
*
* We actually implement this as a varlena so that we don't have to pass in
* the length for the comparison functions. (The difference between these
* types and "text" is that we truncate and possibly blank-pad the string
* at insertion time.)
*
* - ay 6/95
*/
/*****************************************************************************
* bpchar - char() *
*****************************************************************************/
/*
* bpchar_input -- common guts of bpcharin and bpcharrecv
*
* s is the input text of length len (may not be null-terminated)
* atttypmod is the typmod value to apply
*
* Note that atttypmod is measured in characters, which
* is not necessarily the same as the number of bytes.
*
* If the input string is too long, raise an error, unless the extra
* characters are spaces, in which case they're truncated. (per SQL)
*/
static BpChar *
bpchar_input(const char *s, size_t len, int32 atttypmod)
{
BpChar *result;
char *r;
size_t maxlen;
/* If typmod is -1 (or invalid), use the actual string length */
if (atttypmod < (int32) VARHDRSZ)
maxlen = len;
else
{
size_t charlen; /* number of CHARACTERS in the input */
maxlen = atttypmod - VARHDRSZ;
charlen = pg_mbstrlen_with_len(s, len);
if (charlen > maxlen)
{
/* Verify that extra characters are spaces, and clip them off */
size_t mbmaxlen = pg_mbcharcliplen(s, len, maxlen);
size_t j;
/*
* at this point, len is the actual BYTE length of the input
* string, maxlen is the max number of CHARACTERS allowed for this
* bpchar type, mbmaxlen is the length in BYTES of those chars.
*/
for (j = mbmaxlen; j < len; j++)
{
if (s[j] != ' ')
ereport(ERROR,
(errcode(ERRCODE_STRING_DATA_RIGHT_TRUNCATION),
errmsg("value too long for type character(%d)",
(int) maxlen)));
}
/*
* Now we set maxlen to the necessary byte length, not the number
* of CHARACTERS!
*/
maxlen = len = mbmaxlen;
}
else
{
/*
* Now we set maxlen to the necessary byte length, not the number
* of CHARACTERS!
*/
maxlen = len + (maxlen - charlen);
}
}
result = (BpChar *) palloc(maxlen + VARHDRSZ);
SET_VARSIZE(result, maxlen + VARHDRSZ);
r = VARDATA(result);
memcpy(r, s, len);
/* blank pad the string if necessary */
if (maxlen > len)
memset(r + len, ' ', maxlen - len);
return result;
}
/*
* Convert a C string to CHARACTER internal representation. atttypmod
* is the declared length of the type plus VARHDRSZ.
*/
Datum
bpcharin(PG_FUNCTION_ARGS)
{
char *s = PG_GETARG_CSTRING(0);
#ifdef NOT_USED
Oid typelem = PG_GETARG_OID(1);
#endif
int32 atttypmod = PG_GETARG_INT32(2);
BpChar *result;
result = bpchar_input(s, strlen(s), atttypmod);
PG_RETURN_BPCHAR_P(result);
}
/*
* Convert a CHARACTER value to a C string.
*
* Uses the text conversion functions, which is only appropriate if BpChar
* and text are equivalent types.
*/
Datum
bpcharout(PG_FUNCTION_ARGS)
{
Datum txt = PG_GETARG_DATUM(0);
PG_RETURN_CSTRING(TextDatumGetCString(txt));
}
/*
* bpcharrecv - converts external binary format to bpchar
*/
Datum
bpcharrecv(PG_FUNCTION_ARGS)
{
StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
#ifdef NOT_USED
Oid typelem = PG_GETARG_OID(1);
#endif
int32 atttypmod = PG_GETARG_INT32(2);
BpChar *result;
char *str;
int nbytes;
str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
result = bpchar_input(str, nbytes, atttypmod);
pfree(str);
PG_RETURN_BPCHAR_P(result);
}
/*
* bpcharsend - converts bpchar to binary format
*/
Datum
bpcharsend(PG_FUNCTION_ARGS)
{
/* Exactly the same as textsend, so share code */
return textsend(fcinfo);
}
/*
* Converts a CHARACTER type to the specified size.
*
* maxlen is the typmod, ie, declared length plus VARHDRSZ bytes.
* isExplicit is true if this is for an explicit cast to char(N).
*
* Truncation rules: for an explicit cast, silently truncate to the given
* length; for an implicit cast, raise error unless extra characters are
* all spaces. (This is sort-of per SQL: the spec would actually have us
* raise a "completion condition" for the explicit cast case, but Postgres
* hasn't got such a concept.)
*/
Datum
bpchar(PG_FUNCTION_ARGS)
{
BpChar *source = PG_GETARG_BPCHAR_PP(0);
int32 maxlen = PG_GETARG_INT32(1);
bool isExplicit = PG_GETARG_BOOL(2);
BpChar *result;
int32 len;
char *r;
char *s;
int i;
int charlen; /* number of characters in the input string +
* VARHDRSZ */
/* No work if typmod is invalid */
if (maxlen < (int32) VARHDRSZ)
PG_RETURN_BPCHAR_P(source);
maxlen -= VARHDRSZ;
len = VARSIZE_ANY_EXHDR(source);
s = VARDATA_ANY(source);
charlen = pg_mbstrlen_with_len(s, len);
/* No work if supplied data matches typmod already */
if (charlen == maxlen)
PG_RETURN_BPCHAR_P(source);
if (charlen > maxlen)
{
/* Verify that extra characters are spaces, and clip them off */
size_t maxmblen;
maxmblen = pg_mbcharcliplen(s, len, maxlen);
if (!isExplicit)
{
for (i = maxmblen; i < len; i++)
if (s[i] != ' ')
ereport(ERROR,
(errcode(ERRCODE_STRING_DATA_RIGHT_TRUNCATION),
errmsg("value too long for type character(%d)",
maxlen)));
}
len = maxmblen;
/*
* At this point, maxlen is the necessary byte length, not the number
* of CHARACTERS!
*/
maxlen = len;
}
else
{
/*
* At this point, maxlen is the necessary byte length, not the number
* of CHARACTERS!
*/
maxlen = len + (maxlen - charlen);
}
Assert(maxlen >= len);
result = palloc(maxlen + VARHDRSZ);
SET_VARSIZE(result, maxlen + VARHDRSZ);
r = VARDATA(result);
memcpy(r, s, len);
/* blank pad the string if necessary */
if (maxlen > len)
memset(r + len, ' ', maxlen - len);
PG_RETURN_BPCHAR_P(result);
}
/* char_bpchar()
* Convert char to bpchar(1).
*/
Datum
char_bpchar(PG_FUNCTION_ARGS)
{
char c = PG_GETARG_CHAR(0);
BpChar *result;
result = (BpChar *) palloc(VARHDRSZ + 1);
SET_VARSIZE(result, VARHDRSZ + 1);
*(VARDATA(result)) = c;
PG_RETURN_BPCHAR_P(result);
}
/* bpchar_name()
* Converts a bpchar() type to a NameData type.
*/
Datum
bpchar_name(PG_FUNCTION_ARGS)
{
BpChar *s = PG_GETARG_BPCHAR_PP(0);
char *s_data;
Name result;
int len;
len = VARSIZE_ANY_EXHDR(s);
s_data = VARDATA_ANY(s);
/* Truncate oversize input */
if (len >= NAMEDATALEN)
len = pg_mbcliplen(s_data, len, NAMEDATALEN - 1);
/* Remove trailing blanks */
while (len > 0)
{
if (s_data[len - 1] != ' ')
break;
len--;
}
/* We use palloc0 here to ensure result is zero-padded */
result = (Name) palloc0(NAMEDATALEN);
memcpy(NameStr(*result), s_data, len);
PG_RETURN_NAME(result);
}
/* name_bpchar()
* Converts a NameData type to a bpchar type.
*
* Uses the text conversion functions, which is only appropriate if BpChar
* and text are equivalent types.
*/
Datum
name_bpchar(PG_FUNCTION_ARGS)
{
Name s = PG_GETARG_NAME(0);
BpChar *result;
result = (BpChar *) cstring_to_text(NameStr(*s));
PG_RETURN_BPCHAR_P(result);
}
Datum
bpchartypmodin(PG_FUNCTION_ARGS)
{
ArrayType *ta = PG_GETARG_ARRAYTYPE_P(0);
PG_RETURN_INT32(anychar_typmodin(ta, "char"));
}
Datum
bpchartypmodout(PG_FUNCTION_ARGS)
{
int32 typmod = PG_GETARG_INT32(0);
PG_RETURN_CSTRING(anychar_typmodout(typmod));
}
/*****************************************************************************
* varchar - varchar(n)
*
* Note: varchar piggybacks on type text for most operations, and so has no
* C-coded functions except for I/O and typmod checking.
*****************************************************************************/
/*
* varchar_input -- common guts of varcharin and varcharrecv
*
* s is the input text of length len (may not be null-terminated)
* atttypmod is the typmod value to apply
*
* Note that atttypmod is measured in characters, which
* is not necessarily the same as the number of bytes.
*
* If the input string is too long, raise an error, unless the extra
* characters are spaces, in which case they're truncated. (per SQL)
*
* Uses the C string to text conversion function, which is only appropriate
* if VarChar and text are equivalent types.
*/
static VarChar *
varchar_input(const char *s, size_t len, int32 atttypmod)
{
VarChar *result;
size_t maxlen;
maxlen = atttypmod - VARHDRSZ;
if (atttypmod >= (int32) VARHDRSZ && len > maxlen)
{
/* Verify that extra characters are spaces, and clip them off */
size_t mbmaxlen = pg_mbcharcliplen(s, len, maxlen);
size_t j;
for (j = mbmaxlen; j < len; j++)
{
if (s[j] != ' ')
ereport(ERROR,
(errcode(ERRCODE_STRING_DATA_RIGHT_TRUNCATION),
errmsg("value too long for type character varying(%d)",
(int) maxlen)));
}
len = mbmaxlen;
}
result = (VarChar *) cstring_to_text_with_len(s, len);
return result;
}
/*
* Convert a C string to VARCHAR internal representation. atttypmod
* is the declared length of the type plus VARHDRSZ.
*/
Datum
varcharin(PG_FUNCTION_ARGS)
{
char *s = PG_GETARG_CSTRING(0);
#ifdef NOT_USED
Oid typelem = PG_GETARG_OID(1);
#endif
int32 atttypmod = PG_GETARG_INT32(2);
VarChar *result;
result = varchar_input(s, strlen(s), atttypmod);
PG_RETURN_VARCHAR_P(result);
}
/*
* Convert a VARCHAR value to a C string.
*
* Uses the text to C string conversion function, which is only appropriate
* if VarChar and text are equivalent types.
*/
Datum
varcharout(PG_FUNCTION_ARGS)
{
Datum txt = PG_GETARG_DATUM(0);
PG_RETURN_CSTRING(TextDatumGetCString(txt));
}
/*
* varcharrecv - converts external binary format to varchar
*/
Datum
varcharrecv(PG_FUNCTION_ARGS)
{
StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
#ifdef NOT_USED
Oid typelem = PG_GETARG_OID(1);
#endif
int32 atttypmod = PG_GETARG_INT32(2);
VarChar *result;
char *str;
int nbytes;
str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
result = varchar_input(str, nbytes, atttypmod);
pfree(str);
PG_RETURN_VARCHAR_P(result);
}
/*
* varcharsend - converts varchar to binary format
*/
Datum
varcharsend(PG_FUNCTION_ARGS)
{
/* Exactly the same as textsend, so share code */
return textsend(fcinfo);
}
/*
* varchar_support()
*
* Planner support function for the varchar() length coercion function.
*
* Currently, the only interesting thing we can do is flatten calls that set
* the new maximum length >= the previous maximum length. We can ignore the
* isExplicit argument, since that only affects truncation cases.
*/
Datum
varchar_support(PG_FUNCTION_ARGS)
{
Node *rawreq = (Node *) PG_GETARG_POINTER(0);
Node *ret = NULL;
if (IsA(rawreq, SupportRequestSimplify))
{
SupportRequestSimplify *req = (SupportRequestSimplify *) rawreq;
FuncExpr *expr = req->fcall;
Node *typmod;
Assert(list_length(expr->args) >= 2);
typmod = (Node *) lsecond(expr->args);
if (IsA(typmod, Const) &&!((Const *) typmod)->constisnull)
{
Node *source = (Node *) linitial(expr->args);
int32 old_typmod = exprTypmod(source);
int32 new_typmod = DatumGetInt32(((Const *) typmod)->constvalue);
int32 old_max = old_typmod - VARHDRSZ;
int32 new_max = new_typmod - VARHDRSZ;
if (new_typmod < 0 || (old_typmod >= 0 && old_max <= new_max))
ret = relabel_to_typmod(source, new_typmod);
}
}
PG_RETURN_POINTER(ret);
}
/*
* Converts a VARCHAR type to the specified size.
*
* maxlen is the typmod, ie, declared length plus VARHDRSZ bytes.
* isExplicit is true if this is for an explicit cast to varchar(N).
*
* Truncation rules: for an explicit cast, silently truncate to the given
* length; for an implicit cast, raise error unless extra characters are
* all spaces. (This is sort-of per SQL: the spec would actually have us
* raise a "completion condition" for the explicit cast case, but Postgres
* hasn't got such a concept.)
*/
Datum
varchar(PG_FUNCTION_ARGS)
{
VarChar *source = PG_GETARG_VARCHAR_PP(0);
int32 typmod = PG_GETARG_INT32(1);
bool isExplicit = PG_GETARG_BOOL(2);
int32 len,
maxlen;
size_t maxmblen;
int i;
char *s_data;
len = VARSIZE_ANY_EXHDR(source);
s_data = VARDATA_ANY(source);
maxlen = typmod - VARHDRSZ;
/* No work if typmod is invalid or supplied data fits it already */
if (maxlen < 0 || len <= maxlen)
PG_RETURN_VARCHAR_P(source);
/* only reach here if string is too long... */
/* truncate multibyte string preserving multibyte boundary */
maxmblen = pg_mbcharcliplen(s_data, len, maxlen);
if (!isExplicit)
{
for (i = maxmblen; i < len; i++)
if (s_data[i] != ' ')
ereport(ERROR,
(errcode(ERRCODE_STRING_DATA_RIGHT_TRUNCATION),
errmsg("value too long for type character varying(%d)",
maxlen)));
}
PG_RETURN_VARCHAR_P((VarChar *) cstring_to_text_with_len(s_data,
maxmblen));
}
Datum
varchartypmodin(PG_FUNCTION_ARGS)
{
ArrayType *ta = PG_GETARG_ARRAYTYPE_P(0);
PG_RETURN_INT32(anychar_typmodin(ta, "varchar"));
}
Datum
varchartypmodout(PG_FUNCTION_ARGS)
{
int32 typmod = PG_GETARG_INT32(0);
PG_RETURN_CSTRING(anychar_typmodout(typmod));
}
/*****************************************************************************
* Exported functions
*****************************************************************************/
/* "True" length (not counting trailing blanks) of a BpChar */
static inline int
bcTruelen(BpChar *arg)
{
return bpchartruelen(VARDATA_ANY(arg), VARSIZE_ANY_EXHDR(arg));
}
int
bpchartruelen(char *s, int len)
{
int i;
/*
* Note that we rely on the assumption that ' ' is a singleton unit on
* every supported multibyte server encoding.
*/
for (i = len - 1; i >= 0; i--)
{
if (s[i] != ' ')
break;
}
return i + 1;
}
Datum
bpcharlen(PG_FUNCTION_ARGS)
{
BpChar *arg = PG_GETARG_BPCHAR_PP(0);
int len;
/* get number of bytes, ignoring trailing spaces */
len = bcTruelen(arg);
/* in multibyte encoding, convert to number of characters */
if (pg_database_encoding_max_length() != 1)
len = pg_mbstrlen_with_len(VARDATA_ANY(arg), len);
PG_RETURN_INT32(len);
}
Datum
bpcharoctetlen(PG_FUNCTION_ARGS)
{
Datum arg = PG_GETARG_DATUM(0);
/* We need not detoast the input at all */
PG_RETURN_INT32(toast_raw_datum_size(arg) - VARHDRSZ);
}
/*****************************************************************************
* Comparison Functions used for bpchar
*
* Note: btree indexes need these routines not to leak memory; therefore,
* be careful to free working copies of toasted datums. Most places don't
* need to be so careful.
*****************************************************************************/
static void
check_collation_set(Oid collid)
{
if (!OidIsValid(collid))
{
/*
* This typically means that the parser could not resolve a conflict
* of implicit collations, so report it that way.
*/
ereport(ERROR,
(errcode(ERRCODE_INDETERMINATE_COLLATION),
errmsg("could not determine which collation to use for string comparison"),
errhint("Use the COLLATE clause to set the collation explicitly.")));
}
}
Datum
bpchareq(PG_FUNCTION_ARGS)
{
BpChar *arg1 = PG_GETARG_BPCHAR_PP(0);
BpChar *arg2 = PG_GETARG_BPCHAR_PP(1);
int len1,
len2;
bool result;
Oid collid = PG_GET_COLLATION();
check_collation_set(collid);
len1 = bcTruelen(arg1);
len2 = bcTruelen(arg2);
if (lc_collate_is_c(collid) ||
collid == DEFAULT_COLLATION_OID ||
pg_newlocale_from_collation(collid)->deterministic)
{
/*
* Since we only care about equality or not-equality, we can avoid all
* the expense of strcoll() here, and just do bitwise comparison.
*/
if (len1 != len2)
result = false;
else
result = (memcmp(VARDATA_ANY(arg1), VARDATA_ANY(arg2), len1) == 0);
}
else
{
result = (varstr_cmp(VARDATA_ANY(arg1), len1, VARDATA_ANY(arg2), len2,
collid) == 0);
}
PG_FREE_IF_COPY(arg1, 0);
PG_FREE_IF_COPY(arg2, 1);
PG_RETURN_BOOL(result);
}
Datum
bpcharne(PG_FUNCTION_ARGS)
{
BpChar *arg1 = PG_GETARG_BPCHAR_PP(0);
BpChar *arg2 = PG_GETARG_BPCHAR_PP(1);
int len1,
len2;
bool result;
Oid collid = PG_GET_COLLATION();
len1 = bcTruelen(arg1);
len2 = bcTruelen(arg2);
if (lc_collate_is_c(collid) ||
collid == DEFAULT_COLLATION_OID ||
pg_newlocale_from_collation(collid)->deterministic)
{
/*
* Since we only care about equality or not-equality, we can avoid all
* the expense of strcoll() here, and just do bitwise comparison.
*/
if (len1 != len2)
result = true;
else
result = (memcmp(VARDATA_ANY(arg1), VARDATA_ANY(arg2), len1) != 0);
}
else
{
result = (varstr_cmp(VARDATA_ANY(arg1), len1, VARDATA_ANY(arg2), len2,
collid) != 0);
}
PG_FREE_IF_COPY(arg1, 0);
PG_FREE_IF_COPY(arg2, 1);
PG_RETURN_BOOL(result);
}
Datum
bpcharlt(PG_FUNCTION_ARGS)
{
BpChar *arg1 = PG_GETARG_BPCHAR_PP(0);
BpChar *arg2 = PG_GETARG_BPCHAR_PP(1);
int len1,
len2;
int cmp;
len1 = bcTruelen(arg1);
len2 = bcTruelen(arg2);
cmp = varstr_cmp(VARDATA_ANY(arg1), len1, VARDATA_ANY(arg2), len2,
PG_GET_COLLATION());
PG_FREE_IF_COPY(arg1, 0);
PG_FREE_IF_COPY(arg2, 1);
PG_RETURN_BOOL(cmp < 0);
}
Datum
bpcharle(PG_FUNCTION_ARGS)
{
BpChar *arg1 = PG_GETARG_BPCHAR_PP(0);
BpChar *arg2 = PG_GETARG_BPCHAR_PP(1);
int len1,
len2;
int cmp;
len1 = bcTruelen(arg1);
len2 = bcTruelen(arg2);
cmp = varstr_cmp(VARDATA_ANY(arg1), len1, VARDATA_ANY(arg2), len2,
PG_GET_COLLATION());
PG_FREE_IF_COPY(arg1, 0);
PG_FREE_IF_COPY(arg2, 1);
PG_RETURN_BOOL(cmp <= 0);
}
Datum
bpchargt(PG_FUNCTION_ARGS)
{
BpChar *arg1 = PG_GETARG_BPCHAR_PP(0);
BpChar *arg2 = PG_GETARG_BPCHAR_PP(1);
int len1,
len2;
int cmp;
len1 = bcTruelen(arg1);
len2 = bcTruelen(arg2);
cmp = varstr_cmp(VARDATA_ANY(arg1), len1, VARDATA_ANY(arg2), len2,
PG_GET_COLLATION());
PG_FREE_IF_COPY(arg1, 0);
PG_FREE_IF_COPY(arg2, 1);
PG_RETURN_BOOL(cmp > 0);
}
Datum
bpcharge(PG_FUNCTION_ARGS)
{
BpChar *arg1 = PG_GETARG_BPCHAR_PP(0);
BpChar *arg2 = PG_GETARG_BPCHAR_PP(1);
int len1,
len2;
int cmp;
len1 = bcTruelen(arg1);
len2 = bcTruelen(arg2);
cmp = varstr_cmp(VARDATA_ANY(arg1), len1, VARDATA_ANY(arg2), len2,
PG_GET_COLLATION());
PG_FREE_IF_COPY(arg1, 0);
PG_FREE_IF_COPY(arg2, 1);
PG_RETURN_BOOL(cmp >= 0);
}
Datum
bpcharcmp(PG_FUNCTION_ARGS)
{
BpChar *arg1 = PG_GETARG_BPCHAR_PP(0);
BpChar *arg2 = PG_GETARG_BPCHAR_PP(1);
int len1,
len2;
int cmp;
len1 = bcTruelen(arg1);
len2 = bcTruelen(arg2);
cmp = varstr_cmp(VARDATA_ANY(arg1), len1, VARDATA_ANY(arg2), len2,
PG_GET_COLLATION());
PG_FREE_IF_COPY(arg1, 0);
PG_FREE_IF_COPY(arg2, 1);
PG_RETURN_INT32(cmp);
}
Datum
bpchar_sortsupport(PG_FUNCTION_ARGS)
{
SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0);
Oid collid = ssup->ssup_collation;
MemoryContext oldcontext;
oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt);
/* Use generic string SortSupport */
varstr_sortsupport(ssup, BPCHAROID, collid);
MemoryContextSwitchTo(oldcontext);
PG_RETURN_VOID();
}
Datum
bpchar_larger(PG_FUNCTION_ARGS)
{
BpChar *arg1 = PG_GETARG_BPCHAR_PP(0);
BpChar *arg2 = PG_GETARG_BPCHAR_PP(1);
int len1,
len2;
int cmp;
len1 = bcTruelen(arg1);
len2 = bcTruelen(arg2);
cmp = varstr_cmp(VARDATA_ANY(arg1), len1, VARDATA_ANY(arg2), len2,
PG_GET_COLLATION());
PG_RETURN_BPCHAR_P((cmp >= 0) ? arg1 : arg2);
}
Datum
bpchar_smaller(PG_FUNCTION_ARGS)
{
BpChar *arg1 = PG_GETARG_BPCHAR_PP(0);
BpChar *arg2 = PG_GETARG_BPCHAR_PP(1);
int len1,
len2;
int cmp;
len1 = bcTruelen(arg1);
len2 = bcTruelen(arg2);
cmp = varstr_cmp(VARDATA_ANY(arg1), len1, VARDATA_ANY(arg2), len2,
PG_GET_COLLATION());
PG_RETURN_BPCHAR_P((cmp <= 0) ? arg1 : arg2);
}
/*
* bpchar needs a specialized hash function because we want to ignore
* trailing blanks in comparisons.
*/
Datum
hashbpchar(PG_FUNCTION_ARGS)
{
BpChar *key = PG_GETARG_BPCHAR_PP(0);
Oid collid = PG_GET_COLLATION();
char *keydata;
int keylen;
pg_locale_t mylocale = 0;
Datum result;
if (!collid)
ereport(ERROR,
(errcode(ERRCODE_INDETERMINATE_COLLATION),
errmsg("could not determine which collation to use for string hashing"),
errhint("Use the COLLATE clause to set the collation explicitly.")));
keydata = VARDATA_ANY(key);
keylen = bcTruelen(key);
if (!lc_collate_is_c(collid) && collid != DEFAULT_COLLATION_OID)
mylocale = pg_newlocale_from_collation(collid);
if (!mylocale || mylocale->deterministic)
{
result = hash_any((unsigned char *) keydata, keylen);
}
else
{
#ifdef USE_ICU
if (mylocale->provider == COLLPROVIDER_ICU)
{
int32_t ulen = -1;
UChar *uchar = NULL;
Size bsize;
uint8_t *buf;
ulen = icu_to_uchar(&uchar, keydata, keylen);
bsize = ucol_getSortKey(mylocale->info.icu.ucol,
uchar, ulen, NULL, 0);
buf = palloc(bsize);
ucol_getSortKey(mylocale->info.icu.ucol,
uchar, ulen, buf, bsize);
result = hash_any(buf, bsize);
pfree(buf);
}
else
#endif
/* shouldn't happen */
elog(ERROR, "unsupported collprovider: %c", mylocale->provider);
}
/* Avoid leaking memory for toasted inputs */
PG_FREE_IF_COPY(key, 0);
return result;
}
Datum
hashbpcharextended(PG_FUNCTION_ARGS)
{
BpChar *key = PG_GETARG_BPCHAR_PP(0);
Oid collid = PG_GET_COLLATION();
char *keydata;
int keylen;
pg_locale_t mylocale = 0;
Datum result;
if (!collid)
ereport(ERROR,
(errcode(ERRCODE_INDETERMINATE_COLLATION),
errmsg("could not determine which collation to use for string hashing"),
errhint("Use the COLLATE clause to set the collation explicitly.")));
keydata = VARDATA_ANY(key);
keylen = bcTruelen(key);
if (!lc_collate_is_c(collid) && collid != DEFAULT_COLLATION_OID)
mylocale = pg_newlocale_from_collation(collid);
if (!mylocale || mylocale->deterministic)
{
result = hash_any_extended((unsigned char *) keydata, keylen,
PG_GETARG_INT64(1));
}
else
{
#ifdef USE_ICU
if (mylocale->provider == COLLPROVIDER_ICU)
{
int32_t ulen = -1;
UChar *uchar = NULL;
Size bsize;
uint8_t *buf;
ulen = icu_to_uchar(&uchar, VARDATA_ANY(key), VARSIZE_ANY_EXHDR(key));
bsize = ucol_getSortKey(mylocale->info.icu.ucol,
uchar, ulen, NULL, 0);
buf = palloc(bsize);
ucol_getSortKey(mylocale->info.icu.ucol,
uchar, ulen, buf, bsize);
result = hash_any_extended(buf, bsize, PG_GETARG_INT64(1));
pfree(buf);
}
else
#endif
/* shouldn't happen */
elog(ERROR, "unsupported collprovider: %c", mylocale->provider);
}
PG_FREE_IF_COPY(key, 0);
return result;
}
/*
* The following operators support character-by-character comparison
* of bpchar datums, to allow building indexes suitable for LIKE clauses.
* Note that the regular bpchareq/bpcharne comparison operators, and
* regular support functions 1 and 2 with "C" collation are assumed to be
* compatible with these!
*/
static int
internal_bpchar_pattern_compare(BpChar *arg1, BpChar *arg2, Oid collid)
{
int result;
int len1,
len2;
check_collation_set(collid);
/*
* see internal_text_pattern_compare()
*/
if (!get_collation_isdeterministic(collid))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("nondeterministic collations are not supported for operator class \"%s\"",
"bpchar_pattern_ops")));
len1 = bcTruelen(arg1);
len2 = bcTruelen(arg2);
result = memcmp(VARDATA_ANY(arg1), VARDATA_ANY(arg2), Min(len1, len2));
if (result != 0)
return result;
else if (len1 < len2)
return -1;
else if (len1 > len2)
return 1;
else
return 0;
}
Datum
bpchar_pattern_lt(PG_FUNCTION_ARGS)
{
BpChar *arg1 = PG_GETARG_BPCHAR_PP(0);
BpChar *arg2 = PG_GETARG_BPCHAR_PP(1);
int result;
result = internal_bpchar_pattern_compare(arg1, arg2, PG_GET_COLLATION());
PG_FREE_IF_COPY(arg1, 0);
PG_FREE_IF_COPY(arg2, 1);
PG_RETURN_BOOL(result < 0);
}
Datum
bpchar_pattern_le(PG_FUNCTION_ARGS)
{
BpChar *arg1 = PG_GETARG_BPCHAR_PP(0);
BpChar *arg2 = PG_GETARG_BPCHAR_PP(1);
int result;
result = internal_bpchar_pattern_compare(arg1, arg2, PG_GET_COLLATION());
PG_FREE_IF_COPY(arg1, 0);
PG_FREE_IF_COPY(arg2, 1);
PG_RETURN_BOOL(result <= 0);
}
Datum
bpchar_pattern_ge(PG_FUNCTION_ARGS)
{
BpChar *arg1 = PG_GETARG_BPCHAR_PP(0);
BpChar *arg2 = PG_GETARG_BPCHAR_PP(1);
int result;
result = internal_bpchar_pattern_compare(arg1, arg2, PG_GET_COLLATION());
PG_FREE_IF_COPY(arg1, 0);
PG_FREE_IF_COPY(arg2, 1);
PG_RETURN_BOOL(result >= 0);
}
Datum
bpchar_pattern_gt(PG_FUNCTION_ARGS)
{
BpChar *arg1 = PG_GETARG_BPCHAR_PP(0);
BpChar *arg2 = PG_GETARG_BPCHAR_PP(1);
int result;
result = internal_bpchar_pattern_compare(arg1, arg2, PG_GET_COLLATION());
PG_FREE_IF_COPY(arg1, 0);
PG_FREE_IF_COPY(arg2, 1);
PG_RETURN_BOOL(result > 0);
}
Datum
btbpchar_pattern_cmp(PG_FUNCTION_ARGS)
{
BpChar *arg1 = PG_GETARG_BPCHAR_PP(0);
BpChar *arg2 = PG_GETARG_BPCHAR_PP(1);
int result;
result = internal_bpchar_pattern_compare(arg1, arg2, PG_GET_COLLATION());
PG_FREE_IF_COPY(arg1, 0);
PG_FREE_IF_COPY(arg2, 1);
PG_RETURN_INT32(result);
}
Datum
btbpchar_pattern_sortsupport(PG_FUNCTION_ARGS)
{
SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0);
Oid collid = ssup->ssup_collation;
MemoryContext oldcontext;
check_collation_set(collid);
if (!get_collation_isdeterministic(collid))
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("nondeterministic collations are not supported for operator class \"%s\"",
"bpchar_pattern_ops")));
oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt);
/* Use generic string SortSupport, forcing "C" collation */
varstr_sortsupport(ssup, BPCHAROID, C_COLLATION_OID);
MemoryContextSwitchTo(oldcontext);
PG_RETURN_VOID();
}
|
299573.c | /****************************************************************************
* arch/arm/src/lpc43xx/lpc43_start.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.
*
****************************************************************************/
/* Power-Up Reset Overview
* -----------------------
*
* The ARM core starts executing code on reset with the program counter set
* to 0x0000:0000. The LPC43xx contains a shadow pointer register that
* allows areas of memory to be mapped to address 0x0000:0000. The default,
* reset value of the shadow pointer is 0x1040:0000 so that on reset code in
* the boot ROM is always executed first.
*
* The boot starts after reset is released. The IRC is selected as CPU clock
* and the Cortex-M4 starts the boot loader. By default the JTAG access to
* the chip is disabled at reset. The boot ROM determines the boot mode
* based on the OTP BOOT_SRC value or reset state pins. For flash-based
* parts, the part boots from internal flash by default. Otherwise, the boot
* ROM copies the image to internal SRAM at location 0x1000:0000, sets the
* ARM's shadow pointer to 0x1000:0000, and jumps to that location.
*
* However, using JTAG the executable image can be also loaded directly into
* and executed from SRAM.
*/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <stdint.h>
#include <assert.h>
#include <debug.h>
#include <nuttx/init.h>
#include <arch/irq.h>
#include "arm_internal.h"
#include "nvic.h"
#include "hardware/lpc43_creg.h"
#include "lpc43_rgu.h"
#include "lpc43_cgu.h"
#include "lpc43_emc.h"
#include "lpc43_uart.h"
#include "lpc43_userspace.h"
#include "lpc43_start.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/****************************************************************************
* Name: showprogress
*
* Description:
* Print a character on the UART to show boot status.
*
****************************************************************************/
#ifdef CONFIG_DEBUG_FEATURES
# define showprogress(c) arm_lowputc(c)
#else
# define showprogress(c)
#endif
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: lpc43_setbootrom
*
* Description:
* Set the shadow register to 0x1040:0000 and the VTOR to 0x0000:0000 so
* that any exceptions (particularly things like hard faults) that occur
* before we are initialized are caught by the BOOT ROM.
*
****************************************************************************/
static inline void lpc43_setbootrom(void)
{
/* Set the shadow register to the beginning of the boot ROM
* (Only bits 12-31)
*/
putreg32(LPC43_ROM_BASE, LPC43_CREG_M4MEMMAP);
/* Address zero now maps to the Boot ROM. Make sure that the VTOR will
* use the ROM vector table at that address.
*/
putreg32(0, NVIC_VECTAB);
}
/****************************************************************************
* Name: lpc43_enabuffering
*
* Description:
* If we are executing from external FLASH, then enable buffering.
*
****************************************************************************/
#if defined(CONFIG_LPC43_BOOT_CS0FLASH) || defined(CONFIG_LPC43_BOOT_CS1FLASH) || \
defined(CONFIG_LPC43_BOOT_CS2FLASH) || defined(CONFIG_LPC43_BOOT_CS3FLASH)
static inline void lpc43_enabuffering(void)
{
uint32_t regval;
#ifdef CONFIG_LPC43_BOOT_CS0FLASH
regval = getreg32(LPC43_EMC_STATCONFIG0);
regval |= EMC_STATCONFIG_BENA
putreg32(regval, LPC43_EMC_STATCONFIG0);
#endif
#ifdef CONFIG_LPC43_BOOT_CS1FLASH
regval = getreg32(LPC43_EMC_STATCONFIG1);
regval |= EMC_STATCONFIG_BENA
putreg32(regval, LPC43_EMC_STATCONFIG1);
#endif
#ifdef CONFIG_LPC43_BOOT_CS2FLASH
regval = getreg32(LPC43_EMC_STATCONFIG2);
regval |= EMC_STATCONFIG_BENA
putreg32(regval, LPC43_EMC_STATCONFIG2);
#endif
#ifdef CONFIG_LPC43_BOOT_CS3FLASH
regval = getreg32(LPC43_EMC_STATCONFIG3);
regval |= EMC_STATCONFIG_BENA
putreg32(regval, LPC43_EMC_STATCONFIG3);
#endif
}
#else
# define lpc43_enabuffering()
#endif
/****************************************************************************
* Name: lpc43_fpuconfig
*
* Description:
* Configure the FPU. Relative bit settings:
*
* CPACR: Enables access to CP10 and CP11
* CONTROL.FPCA: Determines whether the FP extension is active in the
* current context:
* FPCCR.ASPEN: Enables automatic FP state preservation, then the
* processor sets this bit to 1 on successful completion of any FP
* instruction.
* FPCCR.LSPEN: Enables lazy context save of FP state. When this is
* done, the processor reserves space on the stack for the FP state,
* but does not save that state information to the stack.
*
* Software must not change the value of the ASPEN bit or LSPEN bit while
* either:
* - the CPACR permits access to CP10 and CP11, that give access to the FP
* extension, or
* - the CONTROL.FPCA bit is set to 1
*
****************************************************************************/
#ifdef CONFIG_ARCH_FPU
#ifndef CONFIG_ARMV7M_LAZYFPU
static inline void lpc43_fpuconfig(void)
{
uint32_t regval;
/* Set CONTROL.FPCA so that we always get the extended context frame
* with the volatile FP registers stacked above the basic context.
*/
regval = getcontrol();
regval |= CONTROL_FPCA;
setcontrol(regval);
/* Ensure that FPCCR.LSPEN is disabled, so that we don't have to contend
* with the lazy FP context save behaviour. Clear FPCCR.ASPEN since we
* are going to turn on CONTROL.FPCA for all contexts.
*/
regval = getreg32(NVIC_FPCCR);
regval &= ~(NVIC_FPCCR_ASPEN | NVIC_FPCCR_LSPEN);
putreg32(regval, NVIC_FPCCR);
/* Enable full access to CP10 and CP11 */
regval = getreg32(NVIC_CPACR);
regval |= NVIC_CPACR_CP_FULL(10) | NVIC_CPACR_CP_FULL(11);
putreg32(regval, NVIC_CPACR);
}
#else
static inline void lpc43_fpuconfig(void)
{
uint32_t regval;
/* Clear CONTROL.FPCA so that we do not get the extended context frame
* with the volatile FP registers stacked in the saved context.
*/
regval = getcontrol();
regval &= ~CONTROL_FPCA;
setcontrol(regval);
/* Ensure that FPCCR.LSPEN is disabled, so that we don't have to contend
* with the lazy FP context save behaviour. Clear FPCCR.ASPEN since we
* are going to keep CONTROL.FPCA off for all contexts.
*/
regval = getreg32(NVIC_FPCCR);
regval &= ~(NVIC_FPCCR_ASPEN | NVIC_FPCCR_LSPEN);
putreg32(regval, NVIC_FPCCR);
/* Enable full access to CP10 and CP11 */
regval = getreg32(NVIC_CPACR);
regval |= NVIC_CPACR_CP_FULL(10) | NVIC_CPACR_CP_FULL(11);
putreg32(regval, NVIC_CPACR);
}
#endif
#else
# define lpc43_fpuconfig()
#endif
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: _start
*
* Description:
* This is the reset entry point.
*
****************************************************************************/
void __start(void)
{
const uint32_t *src;
uint32_t *dest;
/* Reset as many of the LPC43 peripherals as possible. This is necessary
* because the LPC43 does not provide any way of performing a full system
* reset under debugger control. So, if CONFIG_DEBUG_FEATURES is set
* (indicating that a debugger is being used?), the boot logic will call
* this function on all restarts.
*/
#ifdef CONFIG_DEBUG_FEATURES
lpc43_softreset();
#endif
/* Make sure that any exceptions (such as hard faults) that occur before
* we are initialized are caught by the BOOT ROM.
*/
lpc43_setbootrom();
/* Configure the CGU clocking and the console uart so that we can get
* debug output as soon as possible.
*/
lpc43_clockconfig();
lpc43_lowsetup();
showprogress('A');
/* If we are executing from external FLASH, then enable buffering */
lpc43_enabuffering();
/* Clear .bss. We'll do this inline (vs. calling memset) just to be
* certain that there are no issues with the state of global variables.
*/
for (dest = &_sbss; dest < &_ebss; )
{
*dest++ = 0;
}
showprogress('B');
/* Move the initialized data section from his temporary holding spot in
* FLASH into the correct place in SRAM. The correct place in SRAM is
* give by _sdata and _edata. The temporary location is in FLASH at the
* end of all of the other read-only data (.text, .rodata) at _eronly.
*/
for (src = &_eronly, dest = &_sdata; dest < &_edata; )
{
*dest++ = *src++;
}
showprogress('C');
/* Initialize the FPU (if configured) */
lpc43_fpuconfig();
showprogress('D');
/* Perform early serial initialization */
#ifdef USE_EARLYSERIALINIT
arm_earlyserialinit();
#endif
showprogress('E');
/* For the case of the separate user-/kernel-space build, perform whatever
* platform specific initialization of the user memory is required.
* Normally this just means initializing the user space .data and .bss
* segments.
*/
#ifdef CONFIG_BUILD_PROTECTED
lpc43_userspace();
showprogress('F');
#endif
/* Initialize onboard resources */
lpc43_boardinitialize();
showprogress('G');
/* Then start NuttX */
showprogress('\r');
showprogress('\n');
nx_start();
/* Shouldn't get here */
for (; ; );
}
|
357706.c | /**
* \file imageio.c
* \brief Implements read_image and write_image functions
* \author Pascal Getreuer <[email protected]>
*
* Two high-level functions are provided, #read_image() and #write_image(),
* for reading and writing image BMP, JPEG, PNG, and TIFF files. The desired
* format of the image data can be specified to \c read_image for how to
* return the data (and similarly to \c write_image for how it should
* interpret the data). formatting options allow specifying the datatype of
* the components, conversion to grayscale, channel ordering, interleaved vs.
* planar, and row-major vs. column-major.
*
* \c read_image automatically detects the format of the image being read so
* that the format does not need to be supplied explicitly. \c write_image
* infers the file format from the file extension.
*
* Also included is a function #identify_image_type() to guess the file type
* (BMP, JPEG, PNG, TIFF, and a few other formats) from the file header's
* magic numbers without reading the image.
*
* Support for BMP reading and writing is native: BMP reading supports 1-, 2-,
* 4-, 8-, 16-, 32-bit uncompressed, RLE, and bitfield images; BMP writing is
* limited to 8- and 24-bit uncompressed. The implementation calls libjpeg,
* libpng, and libtiff to handle JPEG, PNG, and TIFF images.
*
*
* Copyright (c) 2010-2013, Pascal Getreuer
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it
* under, at your option, 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, or the terms of the
* simplified BSD license.
*
* You should have received a copy of these licenses along this program.
* If not, see <http://www.gnu.org/licenses/> and
* <http://www.opensource.org/licenses/bsd-license.html>.
*/
#include "imageio.h"
#include <string.h>
#include <ctype.h>
#ifdef USE_LIBPNG
#include <zlib.h>
#include <png.h>
#if PNG_LIBPNG_VER < 10400
/* For compatibility with older libpng */
#define png_set_expand_gray_1_2_4_to_8 png_set_gray_1_2_4_to_8
#endif
#endif
#ifdef USE_LIBTIFF
#include <tiffio.h>
#endif
#ifdef USE_LIBJPEG
#include <jpeglib.h>
#include <setjmp.h>
#endif
/** \brief buffer size to use for BMP file I/O */
#define FILE_BUFFER_CAPACITY (1024*4)
#define ROUNDCLAMPF(x) ((x < 0.0f) ? 0 : \
((x > 1.0f) ? 255 : (uint8_t)(255.0f*(x) + 0.5f)))
#define ROUNDCLAMP(x) ((x < 0.0) ? 0 : \
((x > 1.0) ? 255 : (uint8_t)(255.0*(x) + 0.5)))
/** \brief Case-insensitive test to see if string ends with suffix */
static int string_ends_with(const char *string, const char *suffix)
{
unsigned string_length = strlen(string), suffix_length = strlen(suffix);
unsigned i;
if(string_length < suffix_length)
return 0;
string += string_length - suffix_length;
for(i = 0; i < suffix_length; i++)
if(tolower(string[i]) != tolower(suffix[i]))
return 0;
return 1;
}
/** \brief Fill an image with a color */
static void fill_image(uint32_t *image, int width, int height, uint32_t color)
{
int x, y;
if(image)
for(y = 0; y < height; y++, image += width)
for(x = 0; x < width; x++)
image[x] = color;
}
/**
* \brief Check use of color and alpha, and count number of distinct colors
* \param num_colors set by the routine to the number of unique colors
* \param use_color set to 1 if the image is not grayscale
* \param use_alpha set to 1 if the image alpha is not constant 255
* \param image pointer to U8 RGBA interleaved image data
* \param width, height dimensions of the image
* \return pointer to a color palette with num_colors entries or NULL if the
* number of distinct colors exceeds 256.
*
* This routine checks whether an RGBA image makes use of color and alpha, and
* constructs a palette if the number of distinct colors is 256 or fewer. This
* information is useful for writing image files with smaller file size.
*/
static uint32_t *get_image_palette(int *num_colors, int *use_color,
int *use_alpha, const uint32_t *image, int width, int height)
{
const int max_colors = 256;
uint32_t *palette = NULL;
uint32_t pixel;
int x, y, i, red, green, blue, alpha;
if(!use_color || !num_colors || !use_alpha)
return NULL;
else if(!image
|| !(palette = (uint32_t *)malloc(sizeof(uint32_t)*max_colors)))
{
*num_colors = -1;
*use_color = *use_alpha = 1;
return NULL;
}
*num_colors = *use_color = *use_alpha = 0;
for(y = 0; y < height; y++)
{
for(x = 0; x < width; x++)
{
pixel = *(image++);
red = ((uint8_t *)&pixel)[0];
green = ((uint8_t *)&pixel)[1];
blue = ((uint8_t *)&pixel)[2];
alpha = ((uint8_t *)&pixel)[3];
if(red != green || red != blue) /* Check color */
*use_color = 1;
if(alpha != 255) /* Check alpha */
*use_alpha = 1;
/* Check palette colors (if *num_colors != -1) */
for(i = 0; i < *num_colors; i++)
if(pixel == palette[i])
break;
if(i == *num_colors)
{
if(i < max_colors)
{ /* Add new color to palette */
palette[i] = pixel;
(*num_colors)++;
}
else
{ /* Maximum size for palette exceeded */
free(palette);
palette = NULL;
*num_colors = -1; /* Don't check palette colors */
}
}
}
}
return palette;
}
/** \brief Read a 16-bit little Endian word from file */
static uint16_t read_u16_le(FILE *file)
{
uint16_t w;
w = (uint16_t) getc(file);
w |= ((uint16_t) getc(file) << 8);
return w;
}
/** \brief Read a 32-bit little Endian double word from file */
static uint32_t read_u32_le(FILE *file)
{
uint32_t dw;
dw = (uint32_t) getc(file);
dw |= ((uint32_t) getc(file) << 8);
dw |= ((uint32_t) getc(file) << 16);
dw |= ((uint32_t) getc(file) << 24);
return dw;
}
/** \brief Write a 16-bit word in little Endian format */
static void write_u16_le(uint16_t w, FILE *file)
{
putc(w & 0xFF, file);
putc((w & 0xFF00) >> 8, file);
}
/** \brief Write a 32-bit double word in little Endian format */
static void write_u32_le(uint32_t dw, FILE *file)
{
putc(dw & 0xFF, file);
putc((dw & 0xFF00) >> 8, file);
putc((dw & 0xFF0000) >> 16, file);
putc((dw & 0xFF000000) >> 24, file);
}
/** \brief Internal function for reading 1-bpp BMP */
static int read_bmp_1bpp(uint32_t *image, int width, int height,
FILE *file, const uint32_t *palette)
{
int row_padding = (-(width+7)/8)&3;
int x, y, bit;
unsigned code;
image += ((long int)width)*((long int)height - 1);
for(y = height; y; y--, image -= width)
{
if(feof(file))
return 0;
for(x = 0; x < width;)
{
code = getc(file);
for(bit = 7; bit >= 0 && x < width; bit--, code <<= 1)
image[x++] = palette[(code & 0x80) ? 1:0];
}
for(x = row_padding; x; x--)
getc(file); /* Skip padding bytes at the end of the row */
}
return 1;
}
/** \brief Internal function for reading 4-bpp BMP */
static int read_bmp_4bpp(uint32_t *image, int width, int height,
FILE *file, const uint32_t *palette)
{
int row_padding = (-(width+1)/2)&3;
int x, y;
unsigned code;
image += ((long int)width)*((long int)height - 1);
for(y = height; y; y--, image -= width)
{
if(feof(file))
return 0;
for(x = 0; x < width;)
{
code = getc(file);
image[x++] = palette[(code & 0xF0) >> 4];
if(x < width)
image[x++] = palette[code & 0x0F];
}
for(x = row_padding; x; x--)
getc(file); /* Skip padding bytes at the end of the row */
}
return 1;
}
/** \brief Internal function for reading 4-bpp RLE-compressed BMP */
static int read_bmp_4bpp_rle(uint32_t *image, int width, int height,
FILE *file, const uint32_t *palette)
{
int x, y, dy, k;
unsigned count, value;
uint32_t color_high, color_low;
fill_image(image, width, height, palette[0]);
image += ((long int)width)*((long int)height - 1);
for(x = 0, y = height; y;)
{
if(feof(file))
return 0;
count = getc(file);
value = getc(file);
if(!count)
{ /* count = 0 is the escape code */
switch(value)
{
case 0: /* End of line */
image -= width;
x = 0;
y--;
break;
case 1: /* End of bitmap */
return 1;
case 2: /* Delta */
x += getc(file);
dy = getc(file);
y -= dy;
image -= dy*width;
if(x >= width || y < 0)
return 0;
break;
default:
/* Read a run of uncompressed data (value = length of run) */
count = k = value;
if(x >= width)
return 0;
do
{
value = getc(file);
image[x++] = palette[(value & 0xF0) >> 4];
if(x >= width)
break;
if(--k)
{
image[x++] = palette[value & 0x0F];
k--;
if(x >= width)
break;
}
}while(k);
if(((count + 1)/2) & 1)
getc(file); /* Padding for word align */
}
}
else
{ /* Run of pixels (count = length of run) */
color_high = palette[(value & 0xF0) >> 4];
color_low = palette[value & 0xF];
if(x >= width)
return 0;
do
{
image[x++] = color_high;
count--;
if(x >= width)
break;
if(count)
{
image[x++] = color_low;
count--;
if(x >= width)
break;
}
}while(count);
}
}
return 1;
}
/** \brief Internal function for reading 8-bpp BMP */
static int read_bmp_8bpp(uint32_t *image, int width, int height,
FILE *file, const uint32_t *palette)
{
int row_padding = (-width)&3;
int x, y;
image += ((long int)width)*((long int)height - 1);
for(y = height; y; y--, image -= width)
{
if(feof(file))
return 0;
for(x = 0; x < width; x++)
image[x] = palette[getc(file) & 0xFF];
for(x = row_padding; x; x--)
getc(file); /* Skip padding bytes at the end of the row */
}
return 1;
}
/** \brief Internal function for reading 8-bpp RLE-compressed BMP */
static int read_bmp_8bpp_rle(uint32_t *image, int width, int height,
FILE *file, const uint32_t *palette)
{
int x, y, dy, k;
unsigned count, value;
uint32_t color;
fill_image(image, width, height, palette[0]);
image += ((long int)width)*((long int)height - 1);
for(x = 0, y = height; y;)
{
if(feof(file))
return 0;
count = getc(file);
value = getc(file);
if(!count)
{ /* count = 0 is the escape code */
switch(value)
{
case 0: /* End of line */
image -= width;
x = 0;
y--;
break;
case 1: /* End of bitmap */
return 1;
case 2: /* Delta */
x += getc(file);
dy = getc(file);
y -= dy;
image -= dy*width;
if(x >= width || y < 0)
return 0;
break;
default:
/* Read a run of uncompressed data (value = length of run) */
count = k = value;
do
{
if(x >= width)
break;
image[x++] = palette[getc(file) & 0xFF];
}while(--k);
if(count&1)
getc(file); /* Padding for word align */
}
}
else
{ /* Run of pixels equal to value (count = length of run) */
color = palette[value & 0xFF];
do
{
if(x >= width)
break;
image[x++] = color;
}while(--count);
}
}
return 1;
}
/** \brief Internal function for reading 24-bpp BMP */
static int read_bmp_24bpp(uint32_t *image, int width, int height, FILE *file)
{
uint8_t *image_ptr = (uint8_t *)image;
int row_padding = (-3*width)&3;
int x, y;
width <<= 2;
image_ptr += ((long int)width)*((long int)height - 1);
for(y = height; y; y--, image_ptr -= width)
{
if(feof(file))
return 0;
for(x = 0; x < width; x += 4)
{
image_ptr[x+3] = 255; /* Set alpha */
image_ptr[x+2] = getc(file); /* Read blue component */
image_ptr[x+1] = getc(file); /* Read green component */
image_ptr[x+0] = getc(file); /* Read red component */
}
for(x = row_padding; x; x--)
getc(file); /* Skip padding bytes at the end of the row */
}
return 1;
}
/** \brief Internal function for determining bit shifts in bitfield BMP */
static void get_mask_shifts(uint32_t mask, int *left_shift, int *right_shift)
{
int shift = 0, bitcount = 0;
if(!mask)
{
*left_shift = 0;
*right_shift = 0;
return;
}
while(!(mask & 1)) /* Find the first true bit */
{
mask >>= 1;
++shift;
}
/* Adjust the result for scaling to 8-bit quantities */
while(mask & 1) /* count the number of true bits */
{
mask >>= 1;
++bitcount;
}
/* Compute a signed shift (right is positive) */
shift += bitcount - 8;
if(shift >= 0)
{
*left_shift = 0;
*right_shift = shift;
}
else
{
*left_shift = -shift;
*right_shift = 0;
}
}
/** \brief Internal function for reading 16-bpp BMP */
static int read_bmp_16bpp(uint32_t *image, int width, int height, FILE *file,
uint32_t redmask, uint32_t greenmask,
uint32_t bluemask, uint32_t alphamask)
{
uint8_t *image_ptr = (uint8_t *)image;
uint32_t code;
int row_padding = (-2*width)&3;
int redleft_shift, greenleft_shift, blueleft_shift, alphaleft_shift;
int redright_shift, greenright_shift, blueright_shift, alpharight_shift;
int x, y;
get_mask_shifts(redmask, &redleft_shift, &redright_shift);
get_mask_shifts(greenmask, &greenleft_shift, &greenright_shift);
get_mask_shifts(bluemask, &blueleft_shift, &blueright_shift);
get_mask_shifts(alphamask, &alphaleft_shift, &alpharight_shift);
width <<= 2;
image_ptr += ((long int)width)*((long int)height - 1);
for(y = height; y; y--, image_ptr -= width)
{
if(feof(file))
return 0;
for(x = 0; x < width; x += 4)
{
code = read_u16_le(file);
/* By the Windows 4.x BMP specification, masks must be contiguous
<http://www.fileformat.info/format/bmp/egff.htm>. So we can
decode bitfields by bitshifting and bitwise AND. */
image_ptr[x + 3] = ((code & alphamask) >> alpharight_shift)
<< alphaleft_shift;
image_ptr[x + 2] = ((code & bluemask ) >> blueright_shift )
<< blueleft_shift;
image_ptr[x + 1] = ((code & greenmask) >> greenright_shift)
<< greenleft_shift;
image_ptr[x + 0] = ((code & redmask ) >> redright_shift )
<< redleft_shift;
}
for(x = row_padding; x; x--)
getc(file); /* Skip padding bytes at the end of the row */
}
return 1;
}
/** \brief Internal function for reading 32-bpp BMP */
static int read_bmp_32bpp(uint32_t *image, int width, int height, FILE *file,
uint32_t redmask, uint32_t greenmask,
uint32_t bluemask, uint32_t alphamask)
{
uint8_t *image_ptr;
uint32_t code;
int redleft_shift, greenleft_shift, blueleft_shift, alphaleft_shift;
int redright_shift, greenright_shift, blueright_shift, alpharight_shift;
int x, y;
get_mask_shifts(redmask, &redleft_shift, &redright_shift);
get_mask_shifts(greenmask, &greenleft_shift, &greenright_shift);
get_mask_shifts(bluemask, &blueleft_shift, &blueright_shift);
get_mask_shifts(alphamask, &alphaleft_shift, &alpharight_shift);
width <<= 2;
image_ptr = (uint8_t *)image + ((long int)width)*((long int)height - 1);
for(y = height; y; y--, image_ptr -= width)
{
if(feof(file))
return 0;
for(x = 0; x < width; x += 4)
{
code = read_u32_le(file);
image_ptr[x + 3] = ((code & alphamask) >> alpharight_shift)
<< alphaleft_shift;
image_ptr[x + 2] = ((code & bluemask ) >> blueright_shift )
<< blueleft_shift;
image_ptr[x + 1] = ((code & greenmask) >> greenright_shift)
<< greenleft_shift;
image_ptr[x + 0] = ((code & redmask ) >> redright_shift )
<< redleft_shift;
}
}
return 1;
}
/**
* \brief Read a BMP (Windows Bitmap) image file as RGBA data
*
* \param image, width, height pointers to be filled with the pointer
* to the image data and the image dimensions.
* \param file stdio FILE pointer pointing to the beginning of the BMP file
*
* \return 1 on success, 0 on failure
*
* This function is called by \c read_image to read BMP images. Before calling
* \c read_bmp, the caller should open \c file as a FILE pointer in binary read
* mode. When \c read_bmp is complete, the caller should close \c file.
*/
static int read_bmp(uint32_t **image, int *width, int *height, FILE *file)
{
uint32_t *palette = NULL;
uint8_t *palette_ptr;
long int image_data_offset, info_size;
unsigned i, num_planes, bits_per_pixel, compression, num_colors;
uint32_t redmask, greenmask, bluemask, alphamask;
int success = 0, os2bmp;
uint8_t magic[2];
*image = NULL;
*width = *height = 0;
fseek(file, 0, SEEK_SET);
magic[0] = getc(file);
magic[1] = getc(file);
if(!(magic[0] == 0x42 && magic[1] == 0x4D) /* Verify the magic numbers */
|| fseek(file, 8, SEEK_CUR)) /* Skip the reserved fields */
{
fprintf(stderr, "Invalid BMP header.\n");
goto fail;
}
image_data_offset = read_u32_le(file);
info_size = read_u32_le(file);
/* Read the info header */
if(info_size < 12)
{
fprintf(stderr, "Invalid BMP info header.\n");
goto fail;
}
if((os2bmp = (info_size == 12))) /* This is an OS/2 V1 infoheader */
{
*width = (int)read_u16_le(file);
*height = (int)read_u16_le(file);
num_planes = (unsigned)read_u16_le(file);
bits_per_pixel = (unsigned)read_u16_le(file);
compression = 0;
num_colors = 0;
redmask = 0x00FF0000;
greenmask = 0x0000FF00;
bluemask = 0x000000FF;
alphamask = 0xFF000000;
}
else
{
*width = abs((int)read_u32_le(file));
*height = abs((int)read_u32_le(file));
num_planes = (unsigned)read_u16_le(file);
bits_per_pixel = (unsigned)read_u16_le(file);
compression = (unsigned)read_u32_le(file);
fseek(file, 12, SEEK_CUR);
num_colors = (unsigned)read_u32_le(file);
fseek(file, 4, SEEK_CUR);
redmask = read_u32_le(file);
greenmask = read_u32_le(file);
bluemask = read_u32_le(file);
alphamask = read_u32_le(file);
}
/* Check for problems or unsupported compression modes */
if(*width > MAX_IMAGE_SIZE || *height > MAX_IMAGE_SIZE)
{
fprintf(stderr, "image dimensions exceed MAX_IMAGE_SIZE.\n");
goto fail;
}
if(feof(file) || num_planes != 1 || compression > 3)
goto fail;
/* Allocate the image data */
if(!(*image = (uint32_t *)malloc(
sizeof(uint32_t)*((long int)*width)*((long int)*height))))
goto fail;
/* Read palette */
if(bits_per_pixel <= 8)
{
fseek(file, 14 + info_size, SEEK_SET);
if(!num_colors)
num_colors = 1 << bits_per_pixel;
if(!(palette = (uint32_t *)malloc(sizeof(uint32_t)*256)))
goto fail;
for(i = 0, palette_ptr = (uint8_t *)palette; i < num_colors; i++)
{
palette_ptr[3] = 255; /* Set alpha */
palette_ptr[2] = getc(file); /* Read blue component */
palette_ptr[1] = getc(file); /* Read green component */
palette_ptr[0] = getc(file); /* Read red component */
palette_ptr += 4;
if(!os2bmp)
getc(file); /* Skip extra byte (for non-OS/2 bitmaps) */
}
/* Fill the rest of the palette with the first color */
for(; i < 256; i++)
palette[i] = palette[0];
}
if(fseek(file, image_data_offset, SEEK_SET) || feof(file))
{
fprintf(stderr, "file error.\n");
goto fail;
}
/*** Read the bitmap image data ***/
switch(compression)
{
case 0: /* Uncompressed data */
switch(bits_per_pixel)
{
case 1: /* Read 1-bit uncompressed indexed data */
success = read_bmp_1bpp(
*image, *width, *height, file, palette);
break;
case 4: /* Read 4-bit uncompressed indexed data */
success = read_bmp_4bpp(
*image, *width, *height, file, palette);
break;
case 8: /* Read 8-bit uncompressed indexed data */
success = read_bmp_8bpp(
*image, *width, *height, file, palette);
break;
case 24: /* Read 24-bit BGR image data */
success = read_bmp_24bpp(*image, *width, *height, file);
break;
case 16: /* Read 16-bit data */
success = read_bmp_16bpp(*image, *width, *height, file,
0x001F << 10, 0x001F << 5, 0x0001F, 0);
break;
case 32: /* Read 32-bit BGRA image data */
success = read_bmp_32bpp(*image, *width, *height, file,
0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000);
break;
}
break;
case 1: /* 8-bit RLE */
if(bits_per_pixel == 8)
success = read_bmp_8bpp_rle(
*image, *width, *height, file, palette);
break;
case 2: /* 4-bit RLE */
if(bits_per_pixel == 4)
success = read_bmp_4bpp_rle(
*image, *width, *height, file, palette);
break;
case 3: /* bitfields data */
switch(bits_per_pixel)
{
case 16: /* Read 16-bit bitfields data */
success = read_bmp_16bpp(*image, *width, *height, file,
redmask, greenmask, bluemask, alphamask);
break;
case 32: /* Read 32-bit bitfields data */
success = read_bmp_32bpp(*image, *width, *height, file,
redmask, greenmask, bluemask, alphamask);
break;
}
break;
}
if(!success)
fprintf(stderr, "Error reading BMP data.\n");
fail: /* There was a problem, clean up and exit */
if(palette)
free(palette);
if(!success && *image)
free(*image);
return success;
}
/**
* \brief Write a BMP image
*
* \param image pointer to RGBA image data
* \param width, height the image dimensions
* \param file stdio FILE pointer
*
* \return 1 on success, 0 on failure
*
* This function is called by \c write_image to write BMP images. The caller
* should open \c file in binary write mode. When \c write_bmp is complete,
* the caller should close \c file.
*
* The image is generally saved in uncompressed 24-bit RGB format. But where
* possible, the image is saved using an 8-bit palette for a substantial
* decrease in file size. The image data is always saved losslessly.
*
* \note The alpha channel is lost when saving to BMP. It is possible to write
* the alpha channel in a 32-bit BMP image, however, such images are not
* widely supported. RGB 24-bit BMP on the other hand is well supported.
*/
static int write_bmp(const uint32_t *image, int width, int height, FILE *file)
{
const uint8_t *image_ptr = (uint8_t *)image;
uint32_t *palette = NULL;
uint32_t pixel;
long int imageSize;
int use_palette, num_colors, use_color, use_alpha;
int x, y, i, row_padding, success = 0;
if(!image)
return 0;
palette = get_image_palette(&num_colors, &use_color, &use_alpha,
image, width, height);
/* Decide whether to use 8-bit palette or 24-bit RGB format */
if(palette && 2*num_colors < width*height)
use_palette = 1;
else
use_palette = num_colors = 0;
/* Tell file to use buffering */
setvbuf(file, 0, _IOFBF, FILE_BUFFER_CAPACITY);
if(use_palette)
{
row_padding = (-width)&3;
imageSize = (width + row_padding)*((long int)height);
}
else
{
row_padding = (-3*width)&3;
imageSize = (3*width + row_padding)*((long int)height);
}
/*** Write the header ***/
/* Write the BMP header */
putc(0x42, file); /* magic numbers */
putc(0x4D, file);
/* filesize */
write_u32_le(54 + 4*num_colors + imageSize, file);
write_u32_le(0, file); /* Reserved fields */
write_u32_le(54 + 4*num_colors, file); /* image data offset */
/* Write the infoheader */
write_u32_le(40, file); /* infoheader size */
write_u32_le(width, file); /* image width */
write_u32_le(height, file); /* image height */
write_u16_le(1, file); /* Number of colorplanes */
write_u16_le((use_palette) ? 8:24, file); /* bits per pixel */
write_u32_le(0, file); /* compression method (none) */
write_u32_le(imageSize, file); /* image size */
write_u32_le(2835, file); /* HResolution (2835=72dpi) */
write_u32_le(2835, file); /* VResolution */
/* Number of colors */
write_u32_le((!use_palette || num_colors == 256) ? 0:num_colors, file);
write_u32_le(0, file); /* Important colors */
if(ferror(file))
{
fprintf(stderr, "Error during write to file.\n");
goto fail;
}
if(use_palette)
{ /* Write the palette */
for(i = 0; i < num_colors; i++)
{
pixel = palette[i];
putc(((uint8_t *)&pixel)[2], file); /* blue */
putc(((uint8_t *)&pixel)[1], file); /* green */
putc(((uint8_t *)&pixel)[0], file); /* red */
putc(0, file); /* Unused */
}
}
/* Write the image data */
width <<= 2;
image_ptr += ((long int)width)*((long int)height - 1);
for(y = height; y; y--, image_ptr -= width)
{
if(use_palette)
{ /* 8-bit palette image data */
for(x = 0; x < width; x += 4)
{
pixel = *((uint32_t *)(image_ptr + x));
for(i = 0; i < num_colors; i++)
if(pixel == palette[i])
break;
putc(i, file);
}
}
else
{ /* 24-bit RGB image data */
for(x = 0; x < width; x += 4)
{
putc(image_ptr[x+2], file); /* Write blue component */
putc(image_ptr[x+1], file); /* Write green component */
putc(image_ptr[x+0], file); /* Write red component */
}
}
for(x = row_padding; x; x--) /* Write row padding */
putc(0, file);
}
if(ferror(file))
{
fprintf(stderr, "Error during write to file.\n");
goto fail;
}
success = 1;
fail:
if(palette)
free(palette);
return success;
}
#ifdef USE_LIBJPEG
/**
* \brief Struct that assists in customizing libjpeg error management
*
* This struct is used in combination with jerr_exit to have control
* over how libjpeg errors are displayed.
*/
typedef struct{
struct jpeg_error_mgr pub;
jmp_buf jmpbuf;
} hooked_jerr;
/** \brief Callback for displaying libjpeg errors */
METHODDEF(void) jerr_exit(j_common_ptr cinfo)
{
hooked_jerr *jerr = (hooked_jerr *) cinfo->err;
(*cinfo->err->output_message)(cinfo);
longjmp(jerr->jmpbuf, 1);
}
/**
* \brief Read a JPEG (Joint Picture Experts Group) image file as RGBA data
*
* \param image, width, height pointers to be filled with the pointer
* to the image data and the image dimensions.
* \param file stdio FILE pointer pointing to the beginning of the BMP file
*
* \return 1 on success, 0 on failure
*
* This function is called by \c read_image to read JPEG images. Before
* calling \c read_jpeg, the caller should open \c file as a FILE pointer
* in binary read mode. When \c read_jpeg is complete, the caller should
* close \c file.
*/
static int read_jpeg(uint32_t **image, int *width, int *height, FILE *file)
{
struct jpeg_decompress_struct cinfo;
hooked_jerr jerr;
JSAMPARRAY buffer;
uint8_t *image_ptr;
unsigned i, row_size;
*image = 0;
*width = *height = 0;
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = jerr_exit;
if(setjmp(jerr.jmpbuf))
goto fail; /* If this code is reached, libjpeg has signaled an error. */
jpeg_create_decompress(&cinfo);
jpeg_stdio_src(&cinfo, file);
jpeg_read_header(&cinfo, 1);
cinfo.out_color_space = JCS_RGB; /* Ask for RGB image data */
jpeg_start_decompress(&cinfo);
*width = (int)cinfo.output_width;
*height = (int)cinfo.output_height;
if(*width > MAX_IMAGE_SIZE || *height > MAX_IMAGE_SIZE)
{
fprintf(stderr, "image dimensions exceed MAX_IMAGE_SIZE.\n");
jpeg_abort_decompress(&cinfo);
goto fail;
}
/* Allocate image memory */
if(!(*image = (uint32_t *)malloc(sizeof(uint32_t)
*((size_t)*width)*((size_t)*height))))
{
jpeg_abort_decompress(&cinfo);
goto fail;
}
/* Allocate a one-row-high array that will go away when done */
row_size = cinfo.output_width * cinfo.output_components;
buffer = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo,
JPOOL_IMAGE, row_size, 1);
image_ptr = (uint8_t *)*image;
while(cinfo.output_scanline < cinfo.output_height)
for(jpeg_read_scanlines(&cinfo, buffer, 1), i = 0;
i < row_size; i += 3)
{
*(image_ptr++) = buffer[0][i]; /* red */
*(image_ptr++) = buffer[0][i+1]; /* green */
*(image_ptr++) = buffer[0][i+2]; /* blue */
*(image_ptr++) = 0xFF;
}
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
return 1;
fail:
if(*image)
free(*image);
*width = *height = 0;
jpeg_destroy_decompress(&cinfo);
return 0;
}
/**
* \brief Write a JPEG image as RGB data
*
* \param image pointer to RGBA image data
* \param width, height the image dimensions
* \param file stdio FILE pointer
*
* \return 1 on success, 0 on failure
*
* This function is called by \c write_image to write JPEG images. The caller
* should open \c file in binary write mode. When \c write_jpeg is complete,
* the caller should close \c file.
*
* \note The alpha channel is lost when saving to JPEG since the JPEG format
* does not support RGBA images. (It is in principle possible to store
* four channels in a JPEG as a CMYK image, but storing alpha this way
* is strange.)
*/
static int write_jpeg(const uint32_t *image, int width, int height,
FILE *file, int quality)
{
struct jpeg_compress_struct cinfo;
hooked_jerr jerr;
uint8_t *buffer = 0, *image_ptr;
unsigned i, row_size;
if(!image)
return 0;
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = jerr_exit;
if(setjmp(jerr.jmpbuf))
goto fail; /* libjpeg has signaled an error */
jpeg_create_compress(&cinfo);
jpeg_stdio_dest(&cinfo, file);
cinfo.image_width = width;
cinfo.image_height = height;
cinfo.input_components = 3;
cinfo.in_color_space = JCS_RGB;
jpeg_set_defaults(&cinfo);
jpeg_set_quality(&cinfo, (quality < 100) ? quality : 100, 1);
jpeg_start_compress(&cinfo, 1);
row_size = 3*width;
image_ptr = (uint8_t *)image;
if(!(buffer = (uint8_t *)malloc(row_size)))
goto fail;
while(cinfo.next_scanline < cinfo.image_height)
{
for(i = 0; i < row_size; i += 3)
{
buffer[i] = image_ptr[0]; /* red */
buffer[i+1] = image_ptr[1]; /* green */
buffer[i+2] = image_ptr[2]; /* blue */
image_ptr += 4;
}
jpeg_write_scanlines(&cinfo, &buffer, 1);
}
if(buffer)
free(buffer);
jpeg_finish_compress(&cinfo);
jpeg_destroy_compress(&cinfo);
return 1;
fail:
if(buffer)
free(buffer);
jpeg_destroy_compress(&cinfo);
return 0;
}
#endif /* USE_LIBJPEG */
#ifdef USE_LIBPNG
/**
* \brief Read a PNG (Portable Network Graphics) image file as RGBA data
*
* \param image, width, height pointers to be filled with the pointer
* to the image data and the image dimensions.
* \param file stdio FILE pointer pointing to the beginning of the PNG file
*
* \return 1 on success, 0 on failure
*
* This function is called by \c read_image to read PNG images. Before calling
* \c read_png, the caller should open \c file as a FILE pointer in binary read
* mode. When \c read_png is complete, the caller should close \c file.
*/
static int read_png(uint32_t **image, int *width, int *height, FILE *file)
{
png_bytep *row_pointers;
png_byte header[8];
png_structp png;
png_infop info;
png_uint_32 png_width, png_height;
int bit_depth, color_type, interlace_type;
unsigned row;
*image = 0;
*width = *height = 0;
/* Check that file is a PNG file */
if(fread(header, 1, 8, file) != 8 || png_sig_cmp(header, 0, 8))
return 0;
/* Read the info header */
if(!(png = png_create_read_struct(
PNG_LIBPNG_VER_STRING, NULL, NULL, NULL))
|| !(info = png_create_info_struct(png)))
{
if(png)
png_destroy_read_struct(&png, (png_infopp)NULL, (png_infopp)NULL);
return 0;
}
if(setjmp(png_jmpbuf(png)))
goto fail; /* libpng has signaled an error */
png_init_io(png, file);
png_set_sig_bytes(png, 8);
png_set_user_limits(png, MAX_IMAGE_SIZE, MAX_IMAGE_SIZE);
png_read_info(png, info);
png_get_IHDR(png, info, &png_width, &png_height, &bit_depth, &color_type,
&interlace_type, (int*)NULL, (int*)NULL);
*width = (int)png_width;
*height = (int)png_height;
/* Tell libpng to convert everything to 32-bit RGBA */
if(color_type == PNG_COLOR_TYPE_PALETTE)
png_set_palette_to_rgb(png);
if(color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
png_set_expand_gray_1_2_4_to_8(png);
if(color_type == PNG_COLOR_TYPE_GRAY
|| color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
png_set_gray_to_rgb(png);
if(png_get_valid(png, info, PNG_INFO_tRNS))
png_set_tRNS_to_alpha(png);
png_set_strip_16(png);
png_set_filler(png, 0xFF, PNG_FILLER_AFTER);
png_set_interlace_handling(png);
png_read_update_info(png, info);
/* Allocate image memory and row pointers */
if(!(*image = (uint32_t *)malloc(sizeof(uint32_t)
*((size_t)*width)*((size_t)*height)))
|| !(row_pointers = (png_bytep *)malloc(sizeof(png_bytep)
*png_height)))
goto fail;
for(row = 0; row < png_height; row++)
row_pointers[row] = (png_bytep)(*image + png_width*row);
/* Read the image data */
png_read_image(png, row_pointers);
free(row_pointers);
png_destroy_read_struct(&png, &info, (png_infopp)NULL);
return 1;
fail:
if(*image)
free(*image);
*width = *height = 0;
png_destroy_read_struct(&png, &info, (png_infopp)NULL);
return 0;
}
/**
* \brief Write a PNG image
*
* \param image pointer to RGBA image data
* \param width, height the image dimensions
* \param file stdio FILE pointer
*
* \return 1 on success, 0 on failure
*
* This function is called by \c write_image to write PNG images. The caller
* should open \c file in binary write mode. When \c write_png is complete,
* the caller should close \c file.
*
* The image is written as 8-bit grayscale, indexed (PLTE), indexed with
* transparent colors (PLTE+tRNS), RGB, or RGBA data (in that order of
* preference) depending on the image data to encourage smaller file size. The
* image data is always saved losslessly. In principle, PNG can also make use
* of the pixel bit depth (1, 2, 4, 8, or 16) to reduce the file size further,
* but it is not done here.
*/
static int write_png(const uint32_t *image, int width, int height, FILE *file)
{
const uint32_t *image_ptr;
uint32_t *palette = NULL;
uint8_t *row_buffer;
png_structp png;
png_infop info;
png_color png_palette[256];
png_byte png_trans[256];
uint32_t pixel;
int png_color_type, num_colors, use_color, use_alpha;
int x, y, i, success = 0;
if(!image)
return 0;
if(!(row_buffer = (uint8_t *)malloc(4*width)))
return 0;
if(!(png = png_create_write_struct(PNG_LIBPNG_VER_STRING,
NULL, NULL, NULL))
|| !(info = png_create_info_struct(png)))
{
if(png)
png_destroy_write_struct(&png, (png_infopp)NULL);
free(row_buffer);
return 0;
}
if(setjmp(png_jmpbuf(png)))
{ /* If this code is reached, libpng has signaled an error. */
goto fail;
}
/* Configure PNG output */
png_init_io(png, file);
png_set_compression_level(png, Z_BEST_COMPRESSION);
palette = get_image_palette(&num_colors, &use_color, &use_alpha,
image, width, height);
/* The image is written according to the analysis of get_image_palette */
if(palette && use_color)
png_color_type = PNG_COLOR_TYPE_PALETTE;
else if(use_alpha)
png_color_type = PNG_COLOR_TYPE_RGB_ALPHA;
else if(use_color)
png_color_type = PNG_COLOR_TYPE_RGB;
else
png_color_type = PNG_COLOR_TYPE_GRAY;
png_set_IHDR(png, info, width, height, 8, png_color_type,
PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
if(png_color_type == PNG_COLOR_TYPE_PALETTE)
{
for(i = 0; i < num_colors; i++)
{
pixel = palette[i];
png_palette[i].red = ((uint8_t *)&pixel)[0];
png_palette[i].green = ((uint8_t *)&pixel)[1];
png_palette[i].blue = ((uint8_t *)&pixel)[2];
png_trans[i] = ((uint8_t *)&pixel)[3];
}
png_set_PLTE(png, info, png_palette, num_colors);
if(use_alpha)
png_set_tRNS(png, info, png_trans, num_colors, NULL);
}
png_write_info(png, info);
for(y = 0, image_ptr = image; y < height; y++, image_ptr += width)
{
switch(png_color_type)
{
case PNG_COLOR_TYPE_RGB_ALPHA:
png_write_row(png, (png_bytep)image_ptr);
break;
case PNG_COLOR_TYPE_RGB:
for(x = 0; x < width; x++)
{
pixel = image_ptr[x];
row_buffer[3*x + 0] = ((uint8_t *)&pixel)[0];
row_buffer[3*x + 1] = ((uint8_t *)&pixel)[1];
row_buffer[3*x + 2] = ((uint8_t *)&pixel)[2];
}
png_write_row(png, (png_bytep)row_buffer);
break;
case PNG_COLOR_TYPE_GRAY:
for(x = 0; x < width; x++)
{
pixel = image_ptr[x];
row_buffer[x] = ((uint8_t *)&pixel)[0];
}
png_write_row(png, (png_bytep)row_buffer);
break;
case PNG_COLOR_TYPE_PALETTE:
for(x = 0; x < width; x++)
{
pixel = image_ptr[x];
for(i = 0; i < num_colors; i++)
if(pixel == palette[i])
break;
row_buffer[x] = i;
}
png_write_row(png, (png_bytep)row_buffer);
break;
}
}
png_write_end(png, info);
success = 1;
fail:
if(palette)
free(palette);
png_destroy_write_struct(&png, &info);
free(row_buffer);
return success;
}
#endif /* USE_LIBPNG */
#ifdef USE_LIBTIFF
/**
* \brief Read a TIFF (Tagged information file format) image file as RGBA data
*
* \param image, width, height pointers to be filled with the pointer
* to the image data and the image dimensions.
* \param file stdio FILE pointer pointing to the beginning of the PNG file
*
* \return 1 on success, 0 on failure
*
* This function is called by \c read_image to read TIFF images. Before calling
* \c read_tiff, the caller should open \c file as a FILE pointer in binary read
* mode. When \c read_tiff is complete, the caller should close \c file.
*/
static int read_tiff(uint32_t **image, int *width, int *height,
const char *filename, unsigned directory)
{
TIFF *tiff;
uint32 image_width, image_height;
*image = 0;
*width = *height = 0;
if(!(tiff = TIFFOpen(filename, "r")))
{
fprintf(stderr, "TIFFOpen failed to open file.\n");
return 0;
}
TIFFSetDirectory(tiff, directory);
TIFFGetField(tiff, TIFFTAG_IMAGEWIDTH, &image_width);
TIFFGetField(tiff, TIFFTAG_IMAGELENGTH, &image_height);
*width = (int)image_width;
*height = (int)image_height;
if(*width > MAX_IMAGE_SIZE || *height > MAX_IMAGE_SIZE)
{
fprintf(stderr, "Image dimensions exceed MAX_IMAGE_SIZE.\n");
goto fail;
}
if(!(*image = (uint32_t *)malloc(
sizeof(uint32_t)*image_width*image_height)))
goto fail;
if(!TIFFReadRGBAImageOriented(tiff, image_width, image_height,
(uint32 *)*image, ORIENTATION_TOPLEFT, 1))
goto fail;
TIFFClose(tiff);
return 1;
fail:
if(*image)
free(*image);
*width = *height = 0;
TIFFClose(tiff);
return 0;
}
/**
* \brief Write a TIFF image as RGBA data
*
* \param image pointer to RGBA image data
* \param width, height the image dimensions
* \param file stdio FILE pointer
*
* \return 1 on success, 0 on failure
*
* This function is called by \c write_image to write TIFF images. The caller
* should open \c file in binary write mode. When \c write_tiff is complete,
* the caller should close \c file.
*/
static int write_tiff(const uint32_t *image, int width, int height,
const char *filename)
{
TIFF *tiff;
uint16 alpha = EXTRASAMPLE_ASSOCALPHA;
if(!image)
return 0;
if(!(tiff = TIFFOpen(filename, "w")))
{
fprintf(stderr, "TIFFOpen failed to open file.\n");
return 0;
}
if(TIFFSetField(tiff, TIFFTAG_IMAGEWIDTH, width) != 1
|| TIFFSetField(tiff, TIFFTAG_IMAGELENGTH, height) != 1
|| TIFFSetField(tiff, TIFFTAG_SAMPLESPERPIXEL, 4) != 1
|| TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB) != 1
|| TIFFSetField(tiff, TIFFTAG_EXTRASAMPLES, 1, &alpha) != 1
|| TIFFSetField(tiff, TIFFTAG_BITSPERSAMPLE, 8) != 1
|| TIFFSetField(tiff, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT) != 1
|| TIFFSetField(tiff, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG) != 1
/* compression can be COMPRESSION_NONE, COMPRESSION_DEFLATE,
COMPRESSION_LZW, or COMPRESSION_JPEG */
|| TIFFSetField(tiff, TIFFTAG_COMPRESSION, COMPRESSION_LZW) != 1)
{
fprintf(stderr, "TIFFSetField failed.\n");
TIFFClose(tiff);
return 0;
}
if(TIFFWriteEncodedStrip(tiff, 0, (tdata_t)image,
4*((size_t)width)*((size_t)height)) < 0)
{
fprintf(stderr, "Error writing data to file.\n");
TIFFClose(tiff);
return 0;
}
TIFFClose(tiff);
return 1;
}
#endif /* USE_LIBTIFF */
/** \brief Convert from RGBA U8 to a specified format */
static void *convert_to_format(uint32_t *src, int width, int height,
unsigned format)
{
const int num_pixels = width*height;
const int num_channels = (format & IMAGEIO_GRAYSCALE) ?
1 : ((format & IMAGEIO_STRIP_ALPHA) ? 3 : 4);
const int channel_stride = (format & IMAGEIO_PLANAR) ? num_pixels : 1;
const int channel_stride2 = 2*channel_stride;
const int channel_stride3 = 3*channel_stride;
double *dest_f64;
float *dest_f32;
uint8_t *dest_u8;
uint32_t pixel;
int order[4] = {0, 1, 2, 3};
int i, x, y, pixel_stride, row_stride;
pixel_stride = (format & IMAGEIO_PLANAR) ? 1 : num_channels;
if(format & IMAGEIO_COLUMNMAJOR)
{
row_stride = pixel_stride;
pixel_stride *= height;
}
else
row_stride = width*pixel_stride;
if(format & IMAGEIO_BGRFLIP)
{
order[0] = 2;
order[2] = 0;
}
if((format & IMAGEIO_AFLIP) && !(format & IMAGEIO_STRIP_ALPHA))
{
order[3] = order[2];
order[2] = order[1];
order[1] = order[0];
order[0] = 3;
}
switch(format & (IMAGEIO_U8 | IMAGEIO_SINGLE | IMAGEIO_DOUBLE))
{
case IMAGEIO_U8: /* destination type is uint8_t */
if(!(dest_u8 = (uint8_t *)malloc(
sizeof(uint8_t)*num_channels*num_pixels)))
return NULL;
switch(num_channels)
{
case 1: /* Convert RGBA U8 to grayscale U8 */
for(y = 0; y < height; y++, src += width)
for(x = 0, i = row_stride*y;
x < width; x++, i += pixel_stride)
{
pixel = src[x];
dest_u8[i] = (uint8_t)(0.299f*((uint8_t *)&pixel)[0]
+ 0.587f*((uint8_t *)&pixel)[1]
+ 0.114f*((uint8_t *)&pixel)[2] + 0.5f);
}
break;
case 3: /* Convert RGBA U8 to RGB (or BGR) U8 */
for(y = 0; y < height; y++, src += width)
for(x = 0, i = row_stride*y;
x < width; x++, i += pixel_stride)
{
pixel = src[x];
dest_u8[i] =
((uint8_t *)&pixel)[order[0]];
dest_u8[i + channel_stride] =
((uint8_t *)&pixel)[order[1]];
dest_u8[i + channel_stride2] =
((uint8_t *)&pixel)[order[2]];
}
break;
case 4: /* Convert RGBA U8 to RGBA (or BGRA, ARGB, or ABGR) U8 */
for(y = 0; y < height; y++, src += width)
for(x = 0, i = row_stride*y;
x < width; x++, i += pixel_stride)
{
pixel = src[x];
dest_u8[i] =
((uint8_t *)&pixel)[order[0]];
dest_u8[i + channel_stride] =
((uint8_t *)&pixel)[order[1]];
dest_u8[i + channel_stride2] =
((uint8_t *)&pixel)[order[2]];
dest_u8[i + channel_stride3] =
((uint8_t *)&pixel)[order[3]];
}
break;
}
return dest_u8;
case IMAGEIO_SINGLE: /* destination type is float */
if(!(dest_f32 = (float *)malloc(
sizeof(float)*num_channels*num_pixels)))
return NULL;
switch(num_channels)
{
case 1: /* Convert RGBA U8 to grayscale float */
for(y = 0; y < height; y++, src += width)
for(x = 0, i = row_stride*y;
x < width; x++, i += pixel_stride)
{
pixel = src[x];
dest_f32[i] =
1.172549019607843070675535e-3f*((uint8_t *)&pixel)[0]
+ 2.301960784313725357840079e-3f*((uint8_t *)&pixel)[1]
+ 4.470588235294117808150007e-4f*((uint8_t *)&pixel)[2];
}
break;
case 3: /* Convert RGBA U8 to RGB (or BGR) float */
for(y = 0; y < height; y++, src += width)
for(x = 0, i = row_stride*y; x < width;
x++, i += pixel_stride)
{
pixel = src[x];
dest_f32[i] =
((uint8_t *)&pixel)[order[0]]/255.0f;
dest_f32[i + channel_stride] =
((uint8_t *)&pixel)[order[1]]/255.0f;
dest_f32[i + channel_stride2] =
((uint8_t *)&pixel)[order[2]]/255.0f;
}
break;
case 4: /* Convert RGBA U8 to RGBA (or BGRA, ARGB, or ABGR) float */
for(y = 0; y < height; y++, src += width)
for(x = 0, i = row_stride*y;
x < width; x++, i += pixel_stride)
{
pixel = src[x];
dest_f32[i] =
((uint8_t *)&pixel)[order[0]]/255.0f;
dest_f32[i + channel_stride] =
((uint8_t *)&pixel)[order[1]]/255.0f;
dest_f32[i + channel_stride2] =
((uint8_t *)&pixel)[order[2]]/255.0f;
dest_f32[i + channel_stride3] =
((uint8_t *)&pixel)[order[3]]/255.0f;
}
break;
}
return dest_f32;
case IMAGEIO_DOUBLE: /* destination type is double */
if(!(dest_f64 = (double *)malloc(sizeof(double)*num_channels*num_pixels)))
return NULL;
switch(num_channels)
{
case 1: /* Convert RGBA U8 to grayscale double */
for(y = 0; y < height; y++, src += width)
for(x = 0, i = row_stride*y; x < width; x++, i += pixel_stride)
{
pixel = src[x];
dest_f64[i] = 1.172549019607843070675535e-3*((uint8_t *)&pixel)[0]
+ 2.301960784313725357840079e-3*((uint8_t *)&pixel)[1]
+ 4.470588235294117808150007e-4*((uint8_t *)&pixel)[2];
}
break;
case 3: /* Convert RGBA U8 to RGB (or BGR) double */
for(y = 0; y < height; y++, src += width)
for(x = 0, i = row_stride*y; x < width; x++, i += pixel_stride)
{
pixel = src[x];
dest_f64[i] =
((uint8_t *)&pixel)[order[0]]/255.0;
dest_f64[i + channel_stride] =
((uint8_t *)&pixel)[order[1]]/255.0;
dest_f64[i + channel_stride2] =
((uint8_t *)&pixel)[order[2]]/255.0;
}
break;
case 4: /* Convert RGBA U8 to RGBA (or BGRA, ARGB, or ABGR) double */
for(y = 0; y < height; y++, src += width)
for(x = 0, i = row_stride*y; x < width; x++, i += pixel_stride)
{
pixel = src[x];
dest_f64[i] =
((uint8_t *)&pixel)[order[0]]/255.0;
dest_f64[i + channel_stride] =
((uint8_t *)&pixel)[order[1]]/255.0;
dest_f64[i + channel_stride2] =
((uint8_t *)&pixel)[order[2]]/255.0;
dest_f64[i + channel_stride3] =
((uint8_t *)&pixel)[order[3]]/255.0;
}
break;
}
return dest_f64;
default:
return NULL;
}
}
/** \brief Convert from a specified format to RGBA U8 */
static uint32_t *convert_from_format(void *src, int width, int height,
unsigned format)
{
const int num_pixels = width*height;
const int num_channels = (format & IMAGEIO_GRAYSCALE) ?
1 : ((format & IMAGEIO_STRIP_ALPHA) ? 3 : 4);
const int channel_stride = (format & IMAGEIO_PLANAR) ? num_pixels : 1;
const int channel_stride2 = 2*channel_stride;
const int channel_stride3 = 3*channel_stride;
double *src_f64 = (double *)src;
float *src_f32 = (float *)src;
uint8_t *src_u8 = (uint8_t *)src;
uint8_t *dest, *dest_ptr;
int order[4] = {0, 1, 2, 3};
int i, x, y, pixel_stride, row_stride;
if(!(dest = (uint8_t *)malloc(sizeof(uint32_t)*num_pixels)))
return NULL;
dest_ptr = dest;
pixel_stride = (format & IMAGEIO_PLANAR) ? 1 : num_channels;
if(format & IMAGEIO_COLUMNMAJOR)
{
row_stride = pixel_stride;
pixel_stride *= height;
}
else
row_stride = width*pixel_stride;
if(format & IMAGEIO_BGRFLIP)
{
order[0] = 2;
order[2] = 0;
}
if((format & IMAGEIO_AFLIP) && !(format & IMAGEIO_STRIP_ALPHA))
{
order[3] = order[2];
order[2] = order[1];
order[1] = order[0];
order[0] = 3;
}
switch(format & (IMAGEIO_U8 | IMAGEIO_SINGLE | IMAGEIO_DOUBLE))
{
case IMAGEIO_U8: /* Source type is uint8_t */
switch(num_channels)
{
case 1: /* Convert grayscale U8 to RGBA U8 */
for(y = 0; y < height; y++, dest_ptr += 4*width)
for(x = 0, i = row_stride*y;
x < width; x++, i += pixel_stride)
{
dest_ptr[4*x] =
dest_ptr[4*x + 1] =
dest_ptr[4*x + 2] = src_u8[i];
dest_ptr[4*x + 3] = 255;
}
break;
case 3: /* Convert RGB (or BGR) U8 to RGBA U8 */
for(y = 0; y < height; y++, dest_ptr += 4*width)
for(x = 0, i = row_stride*y;
x < width; x++, i += pixel_stride)
{
dest_ptr[4*x + order[0]] = src_u8[i];
dest_ptr[4*x + order[1]] = src_u8[i + channel_stride];
dest_ptr[4*x + order[2]] = src_u8[i + channel_stride2];
dest_ptr[4*x + 3] = 255;
}
break;
case 4: /* Convert RGBA U8 to RGBA (or BGRA, ARGB, or ABGR) U8 */
for(y = 0; y < height; y++, dest_ptr += 4*width)
for(x = 0, i = row_stride*y;
x < width; x++, i += pixel_stride)
{
dest_ptr[4*x + order[0]] = src_u8[i];
dest_ptr[4*x + order[1]] = src_u8[i + channel_stride];
dest_ptr[4*x + order[2]] = src_u8[i + channel_stride2];
dest_ptr[4*x + order[3]] = src_u8[i + channel_stride3];
}
break;
}
break;
case IMAGEIO_SINGLE: /* Source type is float */
switch(num_channels)
{
case 1: /* Convert grayscale float to RGBA U8 */
for(y = 0; y < height; y++, dest_ptr += 4*width)
for(x = 0, i = row_stride*y;
x < width; x++, i += pixel_stride)
{
dest_ptr[4*x] =
dest_ptr[4*x + 1] =
dest_ptr[4*x + 2] = ROUNDCLAMPF(src_f32[i]);
dest_ptr[4*x + 3] = 255;
}
break;
case 3: /* Convert RGBA U8 to RGB (or BGR) float */
for(y = 0; y < height; y++, dest_ptr += 4*width)
for(x = 0, i = row_stride*y;
x < width; x++, i += pixel_stride)
{
dest_ptr[4*x + order[0]] =
ROUNDCLAMPF(src_f32[i]);
dest_ptr[4*x + order[1]] =
ROUNDCLAMPF(src_f32[i + channel_stride]);
dest_ptr[4*x + order[2]] =
ROUNDCLAMPF(src_f32[i + channel_stride2]);
dest_ptr[4*x + 3] = 255;
}
break;
case 4: /* Convert RGBA U8 to RGBA (or BGRA, ARGB, or ABGR) float */
for(y = 0; y < height; y++, dest_ptr += 4*width)
for(x = 0, i = row_stride*y;
x < width; x++, i += pixel_stride)
{
dest_ptr[4*x + order[0]] =
ROUNDCLAMPF(src_f32[i]);
dest_ptr[4*x + order[1]] =
ROUNDCLAMPF(src_f32[i + channel_stride]);
dest_ptr[4*x + order[2]] =
ROUNDCLAMPF(src_f32[i + channel_stride2]);
dest_ptr[4*x + order[3]] =
ROUNDCLAMPF(src_f32[i + channel_stride3]);
}
break;
}
break;
case IMAGEIO_DOUBLE: /* Source type is double */
switch(num_channels)
{
case 1: /* Convert grayscale double to RGBA U8 */
for(y = 0; y < height; y++, dest_ptr += 4*width)
for(x = 0, i = row_stride*y;
x < width; x++, i += pixel_stride)
{
dest_ptr[4*x] =
dest_ptr[4*x + 1] =
dest_ptr[4*x + 2] = ROUNDCLAMP(src_f64[i]);
dest_ptr[4*x + 3] = 255;
}
break;
case 3: /* Convert RGB (or BGR) double to RGBA U8 */
for(y = 0; y < height; y++, dest_ptr += 4*width)
for(x = 0, i = row_stride*y;
x < width; x++, i += pixel_stride)
{
dest_ptr[4*x + order[0]] =
ROUNDCLAMP(src_f64[i]);
dest_ptr[4*x + order[1]] =
ROUNDCLAMP(src_f64[i + channel_stride]);
dest_ptr[4*x + order[2]] =
ROUNDCLAMP(src_f64[i + channel_stride2]);
dest_ptr[4*x + 3] = 255;;
}
break;
case 4: /* Convert RGBA (or BGRA, ARGB, or ABGR) double to RGBA U8 */
for(y = 0; y < height; y++, dest_ptr += 4*width)
for(x = 0, i = row_stride*y; x < width; x++, i += pixel_stride)
{
dest_ptr[4*x + order[0]] =
ROUNDCLAMP(src_f64[i]);
dest_ptr[4*x + order[1]] =
ROUNDCLAMP(src_f64[i + channel_stride]);
dest_ptr[4*x + order[2]] =
ROUNDCLAMP(src_f64[i + channel_stride2]);
dest_ptr[4*x + order[3]] =
ROUNDCLAMP(src_f64[i + channel_stride3]);
}
break;
}
break;
default:
return NULL;
}
return (uint32_t *)dest;
}
/**
* \brief Identify the file type of an image file by its magic numbers
* \param type destination buffer with space for at least 5 chars
* \param filename image file name
* \return 1 on successful identification, 0 on failure.
*
* The routine fills type with an identifying string. If there is an error
* or the file type is unknown, type is set to a null string.
*/
int identify_image_type(char *type, const char *filename)
{
FILE *file;
uint32_t magic;
type[0] = '\0';
if(!(file = fopen(filename, "rb")))
return 0;
/* Determine the file format by reading the first 4 bytes */
magic = ((uint32_t)getc(file));
magic |= ((uint32_t)getc(file)) << 8;
magic |= ((uint32_t)getc(file)) << 16;
magic |= ((uint32_t)getc(file)) << 24;
/* Test for errors */
if(ferror(file))
{
fclose(file);
return 0;
}
fclose(file);
if((magic & 0x0000FFFFL) == 0x00004D42L) /* BMP */
strcpy(type, "BMP");
else if((magic & 0x00FFFFFFL) == 0x00FFD8FFL) /* JPEG/JFIF */
strcpy(type, "JPEG");
else if(magic == 0x474E5089L) /* PNG */
strcpy(type, "PNG");
else if(magic == 0x002A4949L || magic == 0x2A004D4DL) /* TIFF */
strcpy(type, "TIFF");
else if(magic == 0x38464947L) /* GIF */
strcpy(type, "GIF");
else if(magic == 0x474E4D8AL) /* MNG */
strcpy(type, "MNG");
else if((magic & 0xF0FF00FFL) == 0x0001000AL /* PCX */
&& ((magic >> 8) & 0xFF) < 6)
strcpy(type, "PCX");
else
return 0;
return 1;
}
/**
* \brief Read an image file as 32-bit RGBA data
*
* \param width, height pointers to be filled with the image dimensions
* \param filename image file name
* \param format specifies the desired format for the image
*
* \return Pointer to the image data, or null on failure
*
* The calling syntax is that the filename is the input and \c width,
* and \c height and the returned pointer are outputs. \c read_image allocates
* memory for the image as one contiguous block of memory and returns a
* pointer. It is the responsibility of the caller to call \c free on this
* pointer when done to release this memory.
*
* A non-null pointer indicates success. On failure, the returned pointer
* is null, and \c width and \c height are set to 0.
*
* The format argument is used by specifying one of the data type options
*
* - IMAGEIO_U8: unsigned 8-bit components
* - IMAGEIO_SINGLE: float components
* - IMAGEIO_DOUBLE: double components
*
* and one of the channel options
*
* - IMAGEIO_GRAYSCALE: grayscale data
* - IMAGEIO_RGB: RGB color data (red is the first channel)
* - IMAGEIO_BGR: BGR color data (blue is the first channel)
* - IMAGEIO_RGBA: RGBA color+alpha data
* - IMAGEIO_BGRA: BGRA color+alpha data
* - IMAGEIO_ARGB: ARGB color+alpha data
* - IMAGEIO_ABGR: ABGR color+alpha data
*
* and optionally either or both of the ordering options
*
* - IMAGEIO_PLANAR: planar order instead of interleaved components
* - IMAGEIO_COLUMNMAJOR: column major order instead of row major order
*
\code
uint32_t *image;
int width, height;
if(!(image = (uint32_t *)read_image(&width, &height, "myimage.bmp",
IMAGEIO_U8 | IMAGEIO_RGBA)))
return 0;
printf("Read image of size %dx%d\n", width, height);
...
free(image);
\endcode
*
* With the default formatting IMAGEIO_U8 | IMAGEIO_RGBA, the image is
* organized in standard row major top-down 32-bit RGBA order. The image
* is organized as
\verbatim
(Top left) (Top right)
image[0] image[1] ... image[width-1]
image[width] image[width+1] ... image[2*width]
... ... ... ...
image[width*(height-1)] ... ... image[width*height-1]
(Bottom left) (Bottom right)
\endverbatim
* Each element \c image[k] represents one RGBA pixel, which is a 32-bit
* bitfield. The components of pixel \c image[k] can be unpacked as
\code
uint8_t *Component = (uint8_t *)&image[k];
uint8_t red = Component[0];
uint8_t green = Component[1];
uint8_t blue = Component[2];
uint8_t alpha = Component[3];
\endcode
* Each component is an unsigned 8-bit integer value with range 0-255. Most
* images do not have alpha information, in which case the alpha component
* is set to value 255 (full opacity).
*
* With IMAGEIO_SINGLE or IMAGEIO_DOUBLE, the components are values in the
* range 0 to 1.
*/
void *read_image(int *width, int *height,
const char *filename, unsigned format)
{
void *image = NULL;
uint32_t *image_u8 = NULL;
FILE *file;
char type[8];
identify_image_type(type, filename);
if(!(file = fopen(filename, "rb")))
{
fprintf(stderr, "Unable to open file \"%s\".\n", filename);
return 0;
}
if(!strcmp(type, "BMP"))
{
if(!read_bmp(&image_u8, width, height, file))
fprintf(stderr, "Failed to read \"%s\".\n", filename);
}
else if(!strcmp(type, "JPEG"))
{
#ifdef USE_LIBJPEG
if(!(read_jpeg(&image_u8, width, height, file)))
fprintf(stderr, "Failed to read \"%s\".\n", filename);
#else
fprintf(stderr, "file \"%s\" is a JPEG image.\n"
"Compile with USE_LIBJPEG to enable JPEG reading.\n",
filename);
#endif
}
else if(!strcmp(type, "PNG"))
{
#ifdef USE_LIBPNG
if(!(read_png(&image_u8, width, height, file)))
fprintf(stderr, "Failed to read \"%s\".\n", filename);
#else
fprintf(stderr, "file \"%s\" is a PNG image.\n"
"Compile with USE_LIBPNG to enable PNG reading.\n",
filename);
#endif
}
else if(!strcmp(type, "TIFF"))
{
#ifdef USE_LIBTIFF
fclose(file);
if(!(read_tiff(&image_u8, width, height, filename, 0)))
fprintf(stderr, "Failed to read \"%s\".\n", filename);
file = NULL;
#else
fprintf(stderr, "file \"%s\" is a TIFF image.\n"
"Compile with USE_LIBTIFF to enable TIFF reading.\n",
filename);
#endif
}
else
{
/* file format is unsupported. */
if(type[0])
fprintf(stderr, "file \"%s\" is a %s image.", filename, type);
else
fprintf(stderr, "file \"%s\" is an unrecognized format.", filename);
fprintf(stderr, "\nSorry, only "
READIMAGE_FORMATS_SUPPORTED " reading is supported.\n");
}
if(file)
fclose(file);
if(image_u8 && format)
{
image = convert_to_format(image_u8, *width, *height, format);
free(image_u8);
}
else
image = image_u8;
return image;
}
/**
* \brief Write an image file from 8-bit RGBA image data
*
* \param image pointer to the image data
* \param width, height image dimensions
* \param filename image file name
* \param format specifies how the data is formatted (see read_image)
* \param quality the JPEG image quality (between 0 and 100)
*
* \return 1 on success, 0 on failure
*
* The input \c image should be a 32-bit RGBA image stored as in the
* description of \c read_image. \c write_image writes to \c filename in the
* file format specified by its extension. If saving a JPEG image, the
* \c quality argument specifies the quality factor (between 0 and 100).
* \c quality has no effect on other formats.
*
* The return value indicates success with 1 or failure with 0.
*/
int write_image(void *image, int width, int height,
const char *filename, unsigned format, int quality)
{
FILE *file;
uint32_t *image_u8;
enum {BMP_FORMAT, JPEG_FORMAT, PNG_FORMAT, TIFF_FORMAT} fileformat;
int success = 0;
if(!image || width <= 0 || height <= 0)
{
fprintf(stderr, "Null image.\n");
fprintf(stderr, "Failed to write \"%s\".\n", filename);
return 0;
}
if(string_ends_with(filename, ".bmp"))
fileformat = BMP_FORMAT;
else if(string_ends_with(filename, ".jpg")
|| string_ends_with(filename, ".jpeg"))
{
fileformat = JPEG_FORMAT;
#ifndef USE_LIBJPEG
fprintf(stderr, "Failed to write \"%s\".\n", filename);
fprintf(stderr, "Compile with USE_LIBJPEG to enable JPEG writing.\n");
return 0;
#endif
}
else if(string_ends_with(filename, ".png"))
{
fileformat = PNG_FORMAT;
#ifndef USE_LIBPNG
fprintf(stderr, "Failed to write \"%s\".\n", filename);
fprintf(stderr, "Compile with USE_LIBPNG to enable PNG writing.\n");
return 0;
#endif
}
else if(string_ends_with(filename, ".tif")
|| string_ends_with(filename, ".tiff"))
{
fileformat = TIFF_FORMAT;
#ifndef USE_LIBTIFF
fprintf(stderr, "Failed to write \"%s\".\n", filename);
fprintf(stderr, "Compile with USE_LIBTIFF to enable TIFF writing.\n");
return 0;
#endif
}
else
{
fprintf(stderr, "Failed to write \"%s\".\n", filename);
if(string_ends_with(filename, ".gif"))
fprintf(stderr, "GIF is not supported. ");
else if(string_ends_with(filename, ".mng"))
fprintf(stderr, "MNG is not supported. ");
else if(string_ends_with(filename, ".pcx"))
fprintf(stderr, "PCX is not supported. ");
else
fprintf(stderr, "Unable to determine format from extension.\n");
fprintf(stderr, "Sorry, only "
WRITEIMAGE_FORMATS_SUPPORTED " writing is supported.\n");
return 0;
}
if(!(file = fopen(filename, "wb")))
{
fprintf(stderr, "Unable to write to file \"%s\".\n", filename);
return 0;
}
if(!(image_u8 = convert_from_format(image, width, height, format)))
return 0;
switch(fileformat)
{
case BMP_FORMAT:
success = write_bmp(image_u8, width, height, file);
break;
case JPEG_FORMAT:
#ifdef USE_LIBJPEG
success = write_jpeg(image_u8, width, height, file, quality);
#else
/* Dummy operation to avoid unused variable warning if compiled
without libjpeg. Note that execution returns above if
format == JPEG_FORMAT and USE_LIBJPEG is undefined. */
success = quality;
#endif
break;
case PNG_FORMAT:
#ifdef USE_LIBPNG
success = write_png(image_u8, width, height, file);
#endif
break;
case TIFF_FORMAT:
#ifdef USE_LIBTIFF
fclose(file);
success = write_tiff(image_u8, width, height, filename);
file = 0;
#endif
break;
}
if(!success)
fprintf(stderr, "Failed to write \"%s\".\n", filename);
free(image_u8);
if(file)
fclose(file);
return success;
}
|
370040.c | // SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) 2012 Samsung Electronics Co.Ltd
* Authors:
* YoungJun Cho <[email protected]>
* Eunchul Kim <[email protected]>
*/
#include <linux/clk.h>
#include <linux/component.h>
#include <linux/err.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/of_device.h>
#include <linux/platform_device.h>
#include <linux/pm_runtime.h>
#include <linux/sizes.h>
#include <drm/drm_fourcc.h>
#include <drm/exynos_drm.h>
#include "exynos_drm_drv.h"
#include "exynos_drm_ipp.h"
#include "regs-rotator.h"
/*
* Rotator supports image crop/rotator and input/output DMA operations.
* input DMA reads image data from the memory.
* output DMA writes image data to memory.
*/
#define ROTATOR_AUTOSUSPEND_DELAY 2000
#define rot_read(offset) readl(rot->regs + (offset))
#define rot_write(cfg, offset) writel(cfg, rot->regs + (offset))
enum rot_irq_status {
ROT_IRQ_STATUS_COMPLETE = 8,
ROT_IRQ_STATUS_ILLEGAL = 9,
};
struct rot_variant {
const struct exynos_drm_ipp_formats *formats;
unsigned int num_formats;
};
/*
* A structure of rotator context.
* @ippdrv: prepare initialization using ippdrv.
* @regs: memory mapped io registers.
* @clock: rotator gate clock.
* @limit_tbl: limitation of rotator.
* @irq: irq number.
*/
struct rot_context {
struct exynos_drm_ipp ipp;
struct drm_device *drm_dev;
void *dma_priv;
struct device *dev;
void __iomem *regs;
struct clk *clock;
const struct exynos_drm_ipp_formats *formats;
unsigned int num_formats;
struct exynos_drm_ipp_task *task;
};
static void rotator_reg_set_irq(struct rot_context *rot, bool enable)
{
u32 val = rot_read(ROT_CONFIG);
if (enable == true)
val |= ROT_CONFIG_IRQ;
else
val &= ~ROT_CONFIG_IRQ;
rot_write(val, ROT_CONFIG);
}
static enum rot_irq_status rotator_reg_get_irq_status(struct rot_context *rot)
{
u32 val = rot_read(ROT_STATUS);
val = ROT_STATUS_IRQ(val);
if (val == ROT_STATUS_IRQ_VAL_COMPLETE)
return ROT_IRQ_STATUS_COMPLETE;
return ROT_IRQ_STATUS_ILLEGAL;
}
static irqreturn_t rotator_irq_handler(int irq, void *arg)
{
struct rot_context *rot = arg;
enum rot_irq_status irq_status;
u32 val;
/* Get execution result */
irq_status = rotator_reg_get_irq_status(rot);
/* clear status */
val = rot_read(ROT_STATUS);
val |= ROT_STATUS_IRQ_PENDING((u32)irq_status);
rot_write(val, ROT_STATUS);
if (rot->task) {
struct exynos_drm_ipp_task *task = rot->task;
rot->task = NULL;
pm_runtime_mark_last_busy(rot->dev);
pm_runtime_put_autosuspend(rot->dev);
exynos_drm_ipp_task_done(task,
irq_status == ROT_IRQ_STATUS_COMPLETE ? 0 : -EINVAL);
}
return IRQ_HANDLED;
}
static void rotator_src_set_fmt(struct rot_context *rot, u32 fmt)
{
u32 val;
val = rot_read(ROT_CONTROL);
val &= ~ROT_CONTROL_FMT_MASK;
switch (fmt) {
case DRM_FORMAT_NV12:
val |= ROT_CONTROL_FMT_YCBCR420_2P;
break;
case DRM_FORMAT_XRGB8888:
val |= ROT_CONTROL_FMT_RGB888;
break;
}
rot_write(val, ROT_CONTROL);
}
static void rotator_src_set_buf(struct rot_context *rot,
struct exynos_drm_ipp_buffer *buf)
{
u32 val;
/* Set buffer size configuration */
val = ROT_SET_BUF_SIZE_H(buf->buf.height) |
ROT_SET_BUF_SIZE_W(buf->buf.pitch[0] / buf->format->cpp[0]);
rot_write(val, ROT_SRC_BUF_SIZE);
/* Set crop image position configuration */
val = ROT_CROP_POS_Y(buf->rect.y) | ROT_CROP_POS_X(buf->rect.x);
rot_write(val, ROT_SRC_CROP_POS);
val = ROT_SRC_CROP_SIZE_H(buf->rect.h) |
ROT_SRC_CROP_SIZE_W(buf->rect.w);
rot_write(val, ROT_SRC_CROP_SIZE);
/* Set buffer DMA address */
rot_write(buf->dma_addr[0], ROT_SRC_BUF_ADDR(0));
rot_write(buf->dma_addr[1], ROT_SRC_BUF_ADDR(1));
}
static void rotator_dst_set_transf(struct rot_context *rot,
unsigned int rotation)
{
u32 val;
/* Set transform configuration */
val = rot_read(ROT_CONTROL);
val &= ~ROT_CONTROL_FLIP_MASK;
if (rotation & DRM_MODE_REFLECT_X)
val |= ROT_CONTROL_FLIP_VERTICAL;
if (rotation & DRM_MODE_REFLECT_Y)
val |= ROT_CONTROL_FLIP_HORIZONTAL;
val &= ~ROT_CONTROL_ROT_MASK;
if (rotation & DRM_MODE_ROTATE_90)
val |= ROT_CONTROL_ROT_90;
else if (rotation & DRM_MODE_ROTATE_180)
val |= ROT_CONTROL_ROT_180;
else if (rotation & DRM_MODE_ROTATE_270)
val |= ROT_CONTROL_ROT_270;
rot_write(val, ROT_CONTROL);
}
static void rotator_dst_set_buf(struct rot_context *rot,
struct exynos_drm_ipp_buffer *buf)
{
u32 val;
/* Set buffer size configuration */
val = ROT_SET_BUF_SIZE_H(buf->buf.height) |
ROT_SET_BUF_SIZE_W(buf->buf.pitch[0] / buf->format->cpp[0]);
rot_write(val, ROT_DST_BUF_SIZE);
/* Set crop image position configuration */
val = ROT_CROP_POS_Y(buf->rect.y) | ROT_CROP_POS_X(buf->rect.x);
rot_write(val, ROT_DST_CROP_POS);
/* Set buffer DMA address */
rot_write(buf->dma_addr[0], ROT_DST_BUF_ADDR(0));
rot_write(buf->dma_addr[1], ROT_DST_BUF_ADDR(1));
}
static void rotator_start(struct rot_context *rot)
{
u32 val;
/* Set interrupt enable */
rotator_reg_set_irq(rot, true);
val = rot_read(ROT_CONTROL);
val |= ROT_CONTROL_START;
rot_write(val, ROT_CONTROL);
}
static int rotator_commit(struct exynos_drm_ipp *ipp,
struct exynos_drm_ipp_task *task)
{
struct rot_context *rot =
container_of(ipp, struct rot_context, ipp);
pm_runtime_get_sync(rot->dev);
rot->task = task;
rotator_src_set_fmt(rot, task->src.buf.fourcc);
rotator_src_set_buf(rot, &task->src);
rotator_dst_set_transf(rot, task->transform.rotation);
rotator_dst_set_buf(rot, &task->dst);
rotator_start(rot);
return 0;
}
static const struct exynos_drm_ipp_funcs ipp_funcs = {
.commit = rotator_commit,
};
static int rotator_bind(struct device *dev, struct device *master, void *data)
{
struct rot_context *rot = dev_get_drvdata(dev);
struct drm_device *drm_dev = data;
struct exynos_drm_ipp *ipp = &rot->ipp;
rot->drm_dev = drm_dev;
ipp->drm_dev = drm_dev;
exynos_drm_register_dma(drm_dev, dev, &rot->dma_priv);
exynos_drm_ipp_register(dev, ipp, &ipp_funcs,
DRM_EXYNOS_IPP_CAP_CROP | DRM_EXYNOS_IPP_CAP_ROTATE,
rot->formats, rot->num_formats, "rotator");
dev_info(dev, "The exynos rotator has been probed successfully\n");
return 0;
}
static void rotator_unbind(struct device *dev, struct device *master,
void *data)
{
struct rot_context *rot = dev_get_drvdata(dev);
struct exynos_drm_ipp *ipp = &rot->ipp;
exynos_drm_ipp_unregister(dev, ipp);
exynos_drm_unregister_dma(rot->drm_dev, rot->dev, &rot->dma_priv);
}
static const struct component_ops rotator_component_ops = {
.bind = rotator_bind,
.unbind = rotator_unbind,
};
static int rotator_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct resource *regs_res;
struct rot_context *rot;
const struct rot_variant *variant;
int irq;
int ret;
rot = devm_kzalloc(dev, sizeof(*rot), GFP_KERNEL);
if (!rot)
return -ENOMEM;
variant = of_device_get_match_data(dev);
rot->formats = variant->formats;
rot->num_formats = variant->num_formats;
rot->dev = dev;
regs_res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
rot->regs = devm_ioremap_resource(dev, regs_res);
if (IS_ERR(rot->regs))
return PTR_ERR(rot->regs);
irq = platform_get_irq(pdev, 0);
if (irq < 0) {
dev_err(dev, "failed to get irq\n");
return irq;
}
ret = devm_request_irq(dev, irq, rotator_irq_handler, 0, dev_name(dev),
rot);
if (ret < 0) {
dev_err(dev, "failed to request irq\n");
return ret;
}
rot->clock = devm_clk_get(dev, "rotator");
if (IS_ERR(rot->clock)) {
dev_err(dev, "failed to get clock\n");
return PTR_ERR(rot->clock);
}
pm_runtime_use_autosuspend(dev);
pm_runtime_set_autosuspend_delay(dev, ROTATOR_AUTOSUSPEND_DELAY);
pm_runtime_enable(dev);
platform_set_drvdata(pdev, rot);
ret = component_add(dev, &rotator_component_ops);
if (ret)
goto err_component;
return 0;
err_component:
pm_runtime_dont_use_autosuspend(dev);
pm_runtime_disable(dev);
return ret;
}
static int rotator_remove(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
component_del(dev, &rotator_component_ops);
pm_runtime_dont_use_autosuspend(dev);
pm_runtime_disable(dev);
return 0;
}
#ifdef CONFIG_PM
static int rotator_runtime_suspend(struct device *dev)
{
struct rot_context *rot = dev_get_drvdata(dev);
clk_disable_unprepare(rot->clock);
return 0;
}
static int rotator_runtime_resume(struct device *dev)
{
struct rot_context *rot = dev_get_drvdata(dev);
return clk_prepare_enable(rot->clock);
}
#endif
static const struct drm_exynos_ipp_limit rotator_s5pv210_rbg888_limits[] = {
{ IPP_SIZE_LIMIT(BUFFER, .h = { 8, SZ_16K }, .v = { 8, SZ_16K }) },
{ IPP_SIZE_LIMIT(AREA, .h.align = 2, .v.align = 2) },
};
static const struct drm_exynos_ipp_limit rotator_4210_rbg888_limits[] = {
{ IPP_SIZE_LIMIT(BUFFER, .h = { 8, SZ_16K }, .v = { 8, SZ_16K }) },
{ IPP_SIZE_LIMIT(AREA, .h.align = 4, .v.align = 4) },
};
static const struct drm_exynos_ipp_limit rotator_4412_rbg888_limits[] = {
{ IPP_SIZE_LIMIT(BUFFER, .h = { 8, SZ_8K }, .v = { 8, SZ_8K }) },
{ IPP_SIZE_LIMIT(AREA, .h.align = 4, .v.align = 4) },
};
static const struct drm_exynos_ipp_limit rotator_5250_rbg888_limits[] = {
{ IPP_SIZE_LIMIT(BUFFER, .h = { 8, SZ_8K }, .v = { 8, SZ_8K }) },
{ IPP_SIZE_LIMIT(AREA, .h.align = 2, .v.align = 2) },
};
static const struct drm_exynos_ipp_limit rotator_s5pv210_yuv_limits[] = {
{ IPP_SIZE_LIMIT(BUFFER, .h = { 32, SZ_64K }, .v = { 32, SZ_64K }) },
{ IPP_SIZE_LIMIT(AREA, .h.align = 8, .v.align = 8) },
};
static const struct drm_exynos_ipp_limit rotator_4210_yuv_limits[] = {
{ IPP_SIZE_LIMIT(BUFFER, .h = { 32, SZ_64K }, .v = { 32, SZ_64K }) },
{ IPP_SIZE_LIMIT(AREA, .h.align = 8, .v.align = 8) },
};
static const struct drm_exynos_ipp_limit rotator_4412_yuv_limits[] = {
{ IPP_SIZE_LIMIT(BUFFER, .h = { 32, SZ_32K }, .v = { 32, SZ_32K }) },
{ IPP_SIZE_LIMIT(AREA, .h.align = 8, .v.align = 8) },
};
static const struct exynos_drm_ipp_formats rotator_s5pv210_formats[] = {
{ IPP_SRCDST_FORMAT(XRGB8888, rotator_s5pv210_rbg888_limits) },
{ IPP_SRCDST_FORMAT(NV12, rotator_s5pv210_yuv_limits) },
};
static const struct exynos_drm_ipp_formats rotator_4210_formats[] = {
{ IPP_SRCDST_FORMAT(XRGB8888, rotator_4210_rbg888_limits) },
{ IPP_SRCDST_FORMAT(NV12, rotator_4210_yuv_limits) },
};
static const struct exynos_drm_ipp_formats rotator_4412_formats[] = {
{ IPP_SRCDST_FORMAT(XRGB8888, rotator_4412_rbg888_limits) },
{ IPP_SRCDST_FORMAT(NV12, rotator_4412_yuv_limits) },
};
static const struct exynos_drm_ipp_formats rotator_5250_formats[] = {
{ IPP_SRCDST_FORMAT(XRGB8888, rotator_5250_rbg888_limits) },
{ IPP_SRCDST_FORMAT(NV12, rotator_4412_yuv_limits) },
};
static const struct rot_variant rotator_s5pv210_data = {
.formats = rotator_s5pv210_formats,
.num_formats = ARRAY_SIZE(rotator_s5pv210_formats),
};
static const struct rot_variant rotator_4210_data = {
.formats = rotator_4210_formats,
.num_formats = ARRAY_SIZE(rotator_4210_formats),
};
static const struct rot_variant rotator_4412_data = {
.formats = rotator_4412_formats,
.num_formats = ARRAY_SIZE(rotator_4412_formats),
};
static const struct rot_variant rotator_5250_data = {
.formats = rotator_5250_formats,
.num_formats = ARRAY_SIZE(rotator_5250_formats),
};
static const struct of_device_id exynos_rotator_match[] = {
{
.compatible = "samsung,s5pv210-rotator",
.data = &rotator_s5pv210_data,
}, {
.compatible = "samsung,exynos4210-rotator",
.data = &rotator_4210_data,
}, {
.compatible = "samsung,exynos4212-rotator",
.data = &rotator_4412_data,
}, {
.compatible = "samsung,exynos5250-rotator",
.data = &rotator_5250_data,
}, {
},
};
MODULE_DEVICE_TABLE(of, exynos_rotator_match);
static const struct dev_pm_ops rotator_pm_ops = {
SET_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend,
pm_runtime_force_resume)
SET_RUNTIME_PM_OPS(rotator_runtime_suspend, rotator_runtime_resume,
NULL)
};
struct platform_driver rotator_driver = {
.probe = rotator_probe,
.remove = rotator_remove,
.driver = {
.name = "exynos-rotator",
.owner = THIS_MODULE,
.pm = &rotator_pm_ops,
.of_match_table = exynos_rotator_match,
},
};
|
130212.c | /*
ID: need help in writing horrible unreadable code?
PROG: crypt1
LANG: C
*/
#include <stdio.h>
#include <stdlib.h>
int N;
int digits[9];
int inDigit(int n);
int main(void)
{
FILE *fin = fopen("crypt1.in", "r");
FILE *fout = fopen("crypt1.out", "w");
fscanf(fin, "%d", &N);
for(int i = 0; i < N; i++)
{
fscanf(fin, "%d", &digits[i]);
}
int count = 0;
for(int product = 1111; product <= 9999; product++)
{
if(inDigit(product))
{
for(int d = 11; d <= 99; d++)
{
if(product % d == 0)
{
int m = product / d;
if(
m >= 111 &&
(m * (d % 10)) >= 111 &&
(m * (d / 10)) >= 111 &&
(m * (d % 10)) <= 999 &&
(m * (d / 10)) <= 999 &&
inDigit(d) &&
inDigit(m) &&
inDigit(m * (d % 10)) &&
inDigit(m * (d / 10))
)
{
count++;
}
}
}
}
}
fprintf(fout, "%d\n", count);
return 0;
}
int search(int d)
{
for(int i = 0; i < N; i++)
{
if(digits[i] == d)
{
return 1;
}
}
return 0;
}
int inDigit(int n)
{
while(n > 0)
{
if(!search(n % 10))
{
return 0;
}
n /= 10;
}
return 1;
}
|
117554.c | // Copyright (C) 2003, by Lonely. All rights reserved.
// This software can not be used, copied, or modified
// in any form without the written permission from authors.
inherit ROOM;
void create()
{
set("short", "水龍軒");
set("long", @LONG
這裏是桃花島主黃藥師日常起居活動的地方,軒內陳設十分簡單。四
壁掛着一些晉人字畫,中間一副墨跡淋漓的條幅(tiaofu),正是黃藥師時
常吟頌的《水龍吟》。門楣上嵌着一個黑黝黝的鐵八卦(bagua),桌上零
散放着幾隻茶杯,一部翻開的阮籍詩鈔,一張當書籤的字紙,除此之外再
無長物。西面和北面各有一道長廊。
LONG );
set("cost", 2);
set("item_desc", ([
"tiaofu" : "放船千里凌波去,略為吳山留顧。雲屯水府,濤隨神女,九江東注。北客翩然,壯心偏\n"
"感,年華將暮。念伊蒿舊隱,巢由故友,南柯夢,遽如許。回首妖氛未掃,問人間何處?\n"
"奇謀復國,可憐無用,塵昏白扇。鐵鎖橫江,錦帆衝浪,孫郎良苦。但愁桂棹,悲吟樑\n"
"父,淚流如雨 。。\n",
"bagua" : "這個鐵八卦卦象排得零零落落,歪歪斜斜,既非伏羲先天八卦,也非文王\n"
"後天八卦,不知道派什麼用場。\n",
]));
set("exits", ([
"west" : __DIR__"changlang2",
"out" : __DIR__"jingshe",
"north" : __DIR__"changlang",
]));
set("objects", ([
// __DIR__"obj/paper1" : 1,
]));
set("coor/x", 8990);
set("coor/y", -2950);
set("coor/z", 0);
setup();
replace_program(ROOM);
} |
802588.c | #define DINT
#include <../Source/umf_set_stats.c>
|
551078.c | /*
* USB HID support for Linux
*
* Copyright (c) 1999 Andreas Gal
* Copyright (c) 2000-2005 Vojtech Pavlik <[email protected]>
* Copyright (c) 2005 Michael Haboustak <[email protected]> for Concept2, Inc
* Copyright (c) 2007-2008 Oliver Neukum
* Copyright (c) 2006-2010 Jiri Kosina
*/
/*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/mm.h>
#include <linux/mutex.h>
#include <linux/spinlock.h>
#include <asm/unaligned.h>
#include <asm/byteorder.h>
#include <linux/input.h>
#include <linux/wait.h>
#include <linux/workqueue.h>
#include <linux/string.h>
#include <linux/usb.h>
#include <linux/hid.h>
#include <linux/hiddev.h>
#include <linux/hid-debug.h>
#include <linux/hidraw.h>
#include "usbhid.h"
/*
* Version Information
*/
#define DRIVER_DESC "USB HID core driver"
#define DRIVER_LICENSE "GPL"
/*
* Module parameters.
*/
static unsigned int hid_mousepoll_interval;
module_param_named(mousepoll, hid_mousepoll_interval, uint, 0644);
MODULE_PARM_DESC(mousepoll, "Polling interval of mice");
static unsigned int ignoreled;
module_param_named(ignoreled, ignoreled, uint, 0644);
MODULE_PARM_DESC(ignoreled, "Autosuspend with active leds");
/* Quirks specified at module load time */
static char *quirks_param[MAX_USBHID_BOOT_QUIRKS];
module_param_array_named(quirks, quirks_param, charp, NULL, 0444);
MODULE_PARM_DESC(quirks, "Add/modify USB HID quirks by specifying "
" quirks=vendorID:productID:quirks"
" where vendorID, productID, and quirks are all in"
" 0x-prefixed hex");
/*
* Input submission and I/O error handler.
*/
static DEFINE_MUTEX(hid_open_mut);
static void hid_io_error(struct hid_device *hid);
static int hid_submit_out(struct hid_device *hid);
static int hid_submit_ctrl(struct hid_device *hid);
static void hid_cancel_delayed_stuff(struct usbhid_device *usbhid);
/* Start up the input URB */
static int hid_start_in(struct hid_device *hid)
{
unsigned long flags;
int rc = 0;
struct usbhid_device *usbhid = hid->driver_data;
spin_lock_irqsave(&usbhid->lock, flags);
if ((hid->open > 0 || hid->quirks & HID_QUIRK_ALWAYS_POLL) &&
!test_bit(HID_DISCONNECTED, &usbhid->iofl) &&
!test_bit(HID_SUSPENDED, &usbhid->iofl) &&
!test_and_set_bit(HID_IN_RUNNING, &usbhid->iofl)) {
rc = usb_submit_urb(usbhid->urbin, GFP_ATOMIC);
if (rc != 0) {
clear_bit(HID_IN_RUNNING, &usbhid->iofl);
if (rc == -ENOSPC)
set_bit(HID_NO_BANDWIDTH, &usbhid->iofl);
} else {
clear_bit(HID_NO_BANDWIDTH, &usbhid->iofl);
}
}
spin_unlock_irqrestore(&usbhid->lock, flags);
return rc;
}
/* I/O retry timer routine */
static void hid_retry_timeout(unsigned long _hid)
{
struct hid_device *hid = (struct hid_device *) _hid;
struct usbhid_device *usbhid = hid->driver_data;
dev_dbg(&usbhid->intf->dev, "retrying intr urb\n");
if (hid_start_in(hid))
hid_io_error(hid);
}
/* Workqueue routine to reset the device or clear a halt */
static void hid_reset(struct work_struct *work)
{
struct usbhid_device *usbhid =
container_of(work, struct usbhid_device, reset_work);
struct hid_device *hid = usbhid->hid;
int rc;
if (test_bit(HID_CLEAR_HALT, &usbhid->iofl)) {
dev_dbg(&usbhid->intf->dev, "clear halt\n");
rc = usb_clear_halt(hid_to_usb_dev(hid), usbhid->urbin->pipe);
clear_bit(HID_CLEAR_HALT, &usbhid->iofl);
if (rc == 0) {
hid_start_in(hid);
} else {
dev_dbg(&usbhid->intf->dev,
"clear-halt failed: %d\n", rc);
set_bit(HID_RESET_PENDING, &usbhid->iofl);
}
}
if (test_bit(HID_RESET_PENDING, &usbhid->iofl)) {
dev_dbg(&usbhid->intf->dev, "resetting device\n");
usb_queue_reset_device(usbhid->intf);
}
}
/* Main I/O error handler */
static void hid_io_error(struct hid_device *hid)
{
unsigned long flags;
struct usbhid_device *usbhid = hid->driver_data;
spin_lock_irqsave(&usbhid->lock, flags);
/* Stop when disconnected */
if (test_bit(HID_DISCONNECTED, &usbhid->iofl))
goto done;
/* If it has been a while since the last error, we'll assume
* this a brand new error and reset the retry timeout. */
if (time_after(jiffies, usbhid->stop_retry + HZ/2))
usbhid->retry_delay = 0;
/* When an error occurs, retry at increasing intervals */
if (usbhid->retry_delay == 0) {
usbhid->retry_delay = 13; /* Then 26, 52, 104, 104, ... */
usbhid->stop_retry = jiffies + msecs_to_jiffies(1000);
} else if (usbhid->retry_delay < 100)
usbhid->retry_delay *= 2;
if (time_after(jiffies, usbhid->stop_retry)) {
/* Retries failed, so do a port reset unless we lack bandwidth*/
if (test_bit(HID_NO_BANDWIDTH, &usbhid->iofl)
&& !test_and_set_bit(HID_RESET_PENDING, &usbhid->iofl)) {
schedule_work(&usbhid->reset_work);
goto done;
}
}
mod_timer(&usbhid->io_retry,
jiffies + msecs_to_jiffies(usbhid->retry_delay));
done:
spin_unlock_irqrestore(&usbhid->lock, flags);
}
static void usbhid_mark_busy(struct usbhid_device *usbhid)
{
struct usb_interface *intf = usbhid->intf;
usb_mark_last_busy(interface_to_usbdev(intf));
}
static int usbhid_restart_out_queue(struct usbhid_device *usbhid)
{
struct hid_device *hid = usb_get_intfdata(usbhid->intf);
int kicked;
int r;
if (!hid || test_bit(HID_RESET_PENDING, &usbhid->iofl) ||
test_bit(HID_SUSPENDED, &usbhid->iofl))
return 0;
if ((kicked = (usbhid->outhead != usbhid->outtail))) {
hid_dbg(hid, "Kicking head %d tail %d", usbhid->outhead, usbhid->outtail);
/* Try to wake up from autosuspend... */
r = usb_autopm_get_interface_async(usbhid->intf);
if (r < 0)
return r;
/*
* If still suspended, don't submit. Submission will
* occur if/when resume drains the queue.
*/
if (test_bit(HID_SUSPENDED, &usbhid->iofl)) {
usb_autopm_put_interface_no_suspend(usbhid->intf);
return r;
}
/* Asynchronously flush queue. */
set_bit(HID_OUT_RUNNING, &usbhid->iofl);
if (hid_submit_out(hid)) {
clear_bit(HID_OUT_RUNNING, &usbhid->iofl);
usb_autopm_put_interface_async(usbhid->intf);
}
wake_up(&usbhid->wait);
}
return kicked;
}
static int usbhid_restart_ctrl_queue(struct usbhid_device *usbhid)
{
struct hid_device *hid = usb_get_intfdata(usbhid->intf);
int kicked;
int r;
WARN_ON(hid == NULL);
if (!hid || test_bit(HID_RESET_PENDING, &usbhid->iofl) ||
test_bit(HID_SUSPENDED, &usbhid->iofl))
return 0;
if ((kicked = (usbhid->ctrlhead != usbhid->ctrltail))) {
hid_dbg(hid, "Kicking head %d tail %d", usbhid->ctrlhead, usbhid->ctrltail);
/* Try to wake up from autosuspend... */
r = usb_autopm_get_interface_async(usbhid->intf);
if (r < 0)
return r;
/*
* If still suspended, don't submit. Submission will
* occur if/when resume drains the queue.
*/
if (test_bit(HID_SUSPENDED, &usbhid->iofl)) {
usb_autopm_put_interface_no_suspend(usbhid->intf);
return r;
}
/* Asynchronously flush queue. */
set_bit(HID_CTRL_RUNNING, &usbhid->iofl);
if (hid_submit_ctrl(hid)) {
clear_bit(HID_CTRL_RUNNING, &usbhid->iofl);
usb_autopm_put_interface_async(usbhid->intf);
}
wake_up(&usbhid->wait);
}
return kicked;
}
/*
* Input interrupt completion handler.
*/
static void hid_irq_in(struct urb *urb)
{
struct hid_device *hid = urb->context;
struct usbhid_device *usbhid = hid->driver_data;
int status;
switch (urb->status) {
case 0: /* success */
usbhid_mark_busy(usbhid);
usbhid->retry_delay = 0;
if ((hid->quirks & HID_QUIRK_ALWAYS_POLL) && !hid->open)
break;
hid_input_report(urb->context, HID_INPUT_REPORT,
urb->transfer_buffer,
urb->actual_length, 1);
/*
* autosuspend refused while keys are pressed
* because most keyboards don't wake up when
* a key is released
*/
if (hid_check_keys_pressed(hid))
set_bit(HID_KEYS_PRESSED, &usbhid->iofl);
else
clear_bit(HID_KEYS_PRESSED, &usbhid->iofl);
break;
case -EPIPE: /* stall */
usbhid_mark_busy(usbhid);
clear_bit(HID_IN_RUNNING, &usbhid->iofl);
set_bit(HID_CLEAR_HALT, &usbhid->iofl);
schedule_work(&usbhid->reset_work);
return;
case -ECONNRESET: /* unlink */
case -ENOENT:
case -ESHUTDOWN: /* unplug */
clear_bit(HID_IN_RUNNING, &usbhid->iofl);
return;
case -EILSEQ: /* protocol error or unplug */
case -EPROTO: /* protocol error or unplug */
case -ETIME: /* protocol error or unplug */
case -ETIMEDOUT: /* Should never happen, but... */
usbhid_mark_busy(usbhid);
clear_bit(HID_IN_RUNNING, &usbhid->iofl);
hid_io_error(hid);
return;
default: /* error */
hid_warn(urb->dev, "input irq status %d received\n",
urb->status);
}
status = usb_submit_urb(urb, GFP_ATOMIC);
if (status) {
clear_bit(HID_IN_RUNNING, &usbhid->iofl);
if (status != -EPERM) {
hid_err(hid, "can't resubmit intr, %s-%s/input%d, status %d\n",
hid_to_usb_dev(hid)->bus->bus_name,
hid_to_usb_dev(hid)->devpath,
usbhid->ifnum, status);
hid_io_error(hid);
}
}
}
static int hid_submit_out(struct hid_device *hid)
{
struct hid_report *report;
char *raw_report;
struct usbhid_device *usbhid = hid->driver_data;
int r;
report = usbhid->out[usbhid->outtail].report;
raw_report = usbhid->out[usbhid->outtail].raw_report;
usbhid->urbout->transfer_buffer_length = ((report->size - 1) >> 3) +
1 + (report->id > 0);
usbhid->urbout->dev = hid_to_usb_dev(hid);
if (raw_report) {
memcpy(usbhid->outbuf, raw_report,
usbhid->urbout->transfer_buffer_length);
kfree(raw_report);
usbhid->out[usbhid->outtail].raw_report = NULL;
}
dbg_hid("submitting out urb\n");
r = usb_submit_urb(usbhid->urbout, GFP_ATOMIC);
if (r < 0) {
hid_err(hid, "usb_submit_urb(out) failed: %d\n", r);
return r;
}
usbhid->last_out = jiffies;
return 0;
}
static int hid_submit_ctrl(struct hid_device *hid)
{
struct hid_report *report;
unsigned char dir;
char *raw_report;
int len, r;
struct usbhid_device *usbhid = hid->driver_data;
report = usbhid->ctrl[usbhid->ctrltail].report;
raw_report = usbhid->ctrl[usbhid->ctrltail].raw_report;
dir = usbhid->ctrl[usbhid->ctrltail].dir;
len = ((report->size - 1) >> 3) + 1 + (report->id > 0);
if (dir == USB_DIR_OUT) {
usbhid->urbctrl->pipe = usb_sndctrlpipe(hid_to_usb_dev(hid), 0);
usbhid->urbctrl->transfer_buffer_length = len;
if (raw_report) {
memcpy(usbhid->ctrlbuf, raw_report, len);
kfree(raw_report);
usbhid->ctrl[usbhid->ctrltail].raw_report = NULL;
}
} else {
int maxpacket, padlen;
usbhid->urbctrl->pipe = usb_rcvctrlpipe(hid_to_usb_dev(hid), 0);
maxpacket = usb_maxpacket(hid_to_usb_dev(hid),
usbhid->urbctrl->pipe, 0);
if (maxpacket > 0) {
padlen = DIV_ROUND_UP(len, maxpacket);
padlen *= maxpacket;
if (padlen > usbhid->bufsize)
padlen = usbhid->bufsize;
} else
padlen = 0;
usbhid->urbctrl->transfer_buffer_length = padlen;
}
usbhid->urbctrl->dev = hid_to_usb_dev(hid);
usbhid->cr->bRequestType = USB_TYPE_CLASS | USB_RECIP_INTERFACE | dir;
usbhid->cr->bRequest = (dir == USB_DIR_OUT) ? HID_REQ_SET_REPORT :
HID_REQ_GET_REPORT;
usbhid->cr->wValue = cpu_to_le16(((report->type + 1) << 8) |
report->id);
usbhid->cr->wIndex = cpu_to_le16(usbhid->ifnum);
usbhid->cr->wLength = cpu_to_le16(len);
dbg_hid("submitting ctrl urb: %s wValue=0x%04x wIndex=0x%04x wLength=%u\n",
usbhid->cr->bRequest == HID_REQ_SET_REPORT ? "Set_Report" :
"Get_Report",
usbhid->cr->wValue, usbhid->cr->wIndex, usbhid->cr->wLength);
r = usb_submit_urb(usbhid->urbctrl, GFP_ATOMIC);
if (r < 0) {
hid_err(hid, "usb_submit_urb(ctrl) failed: %d\n", r);
return r;
}
usbhid->last_ctrl = jiffies;
return 0;
}
/*
* Output interrupt completion handler.
*/
static void hid_irq_out(struct urb *urb)
{
struct hid_device *hid = urb->context;
struct usbhid_device *usbhid = hid->driver_data;
unsigned long flags;
int unplug = 0;
switch (urb->status) {
case 0: /* success */
break;
case -ESHUTDOWN: /* unplug */
unplug = 1;
case -EILSEQ: /* protocol error or unplug */
case -EPROTO: /* protocol error or unplug */
case -ECONNRESET: /* unlink */
case -ENOENT:
break;
default: /* error */
hid_warn(urb->dev, "output irq status %d received\n",
urb->status);
}
spin_lock_irqsave(&usbhid->lock, flags);
if (unplug) {
usbhid->outtail = usbhid->outhead;
} else {
usbhid->outtail = (usbhid->outtail + 1) & (HID_OUTPUT_FIFO_SIZE - 1);
if (usbhid->outhead != usbhid->outtail &&
hid_submit_out(hid) == 0) {
/* Successfully submitted next urb in queue */
spin_unlock_irqrestore(&usbhid->lock, flags);
return;
}
}
clear_bit(HID_OUT_RUNNING, &usbhid->iofl);
spin_unlock_irqrestore(&usbhid->lock, flags);
usb_autopm_put_interface_async(usbhid->intf);
wake_up(&usbhid->wait);
}
/*
* Control pipe completion handler.
*/
static void hid_ctrl(struct urb *urb)
{
struct hid_device *hid = urb->context;
struct usbhid_device *usbhid = hid->driver_data;
int unplug = 0, status = urb->status;
spin_lock(&usbhid->lock);
switch (status) {
case 0: /* success */
if (usbhid->ctrl[usbhid->ctrltail].dir == USB_DIR_IN)
hid_input_report(urb->context,
usbhid->ctrl[usbhid->ctrltail].report->type,
urb->transfer_buffer, urb->actual_length, 0);
break;
case -ESHUTDOWN: /* unplug */
unplug = 1;
case -EILSEQ: /* protocol error or unplug */
case -EPROTO: /* protocol error or unplug */
case -ECONNRESET: /* unlink */
case -ENOENT:
case -EPIPE: /* report not available */
break;
default: /* error */
hid_warn(urb->dev, "ctrl urb status %d received\n", status);
}
if (unplug) {
usbhid->ctrltail = usbhid->ctrlhead;
} else {
usbhid->ctrltail = (usbhid->ctrltail + 1) & (HID_CONTROL_FIFO_SIZE - 1);
if (usbhid->ctrlhead != usbhid->ctrltail &&
hid_submit_ctrl(hid) == 0) {
/* Successfully submitted next urb in queue */
spin_unlock(&usbhid->lock);
return;
}
}
clear_bit(HID_CTRL_RUNNING, &usbhid->iofl);
spin_unlock(&usbhid->lock);
usb_autopm_put_interface_async(usbhid->intf);
wake_up(&usbhid->wait);
}
static void __usbhid_submit_report(struct hid_device *hid, struct hid_report *report,
unsigned char dir)
{
int head;
struct usbhid_device *usbhid = hid->driver_data;
if (((hid->quirks & HID_QUIRK_NOGET) && dir == USB_DIR_IN) ||
test_bit(HID_DISCONNECTED, &usbhid->iofl))
return;
if (usbhid->urbout && dir == USB_DIR_OUT && report->type == HID_OUTPUT_REPORT) {
if ((head = (usbhid->outhead + 1) & (HID_OUTPUT_FIFO_SIZE - 1)) == usbhid->outtail) {
hid_warn(hid, "output queue full\n");
return;
}
usbhid->out[usbhid->outhead].raw_report = hid_alloc_report_buf(report, GFP_ATOMIC);
if (!usbhid->out[usbhid->outhead].raw_report) {
hid_warn(hid, "output queueing failed\n");
return;
}
hid_output_report(report, usbhid->out[usbhid->outhead].raw_report);
usbhid->out[usbhid->outhead].report = report;
usbhid->outhead = head;
/* If the queue isn't running, restart it */
if (!test_bit(HID_OUT_RUNNING, &usbhid->iofl)) {
usbhid_restart_out_queue(usbhid);
/* Otherwise see if an earlier request has timed out */
} else if (time_after(jiffies, usbhid->last_out + HZ * 5)) {
/* Prevent autosuspend following the unlink */
usb_autopm_get_interface_no_resume(usbhid->intf);
/*
* Prevent resubmission in case the URB completes
* before we can unlink it. We don't want to cancel
* the wrong transfer!
*/
usb_block_urb(usbhid->urbout);
/* Drop lock to avoid deadlock if the callback runs */
spin_unlock(&usbhid->lock);
usb_unlink_urb(usbhid->urbout);
spin_lock(&usbhid->lock);
usb_unblock_urb(usbhid->urbout);
/* Unlink might have stopped the queue */
if (!test_bit(HID_OUT_RUNNING, &usbhid->iofl))
usbhid_restart_out_queue(usbhid);
/* Now we can allow autosuspend again */
usb_autopm_put_interface_async(usbhid->intf);
}
return;
}
if ((head = (usbhid->ctrlhead + 1) & (HID_CONTROL_FIFO_SIZE - 1)) == usbhid->ctrltail) {
hid_warn(hid, "control queue full\n");
return;
}
if (dir == USB_DIR_OUT) {
usbhid->ctrl[usbhid->ctrlhead].raw_report = hid_alloc_report_buf(report, GFP_ATOMIC);
if (!usbhid->ctrl[usbhid->ctrlhead].raw_report) {
hid_warn(hid, "control queueing failed\n");
return;
}
hid_output_report(report, usbhid->ctrl[usbhid->ctrlhead].raw_report);
}
usbhid->ctrl[usbhid->ctrlhead].report = report;
usbhid->ctrl[usbhid->ctrlhead].dir = dir;
usbhid->ctrlhead = head;
/* If the queue isn't running, restart it */
if (!test_bit(HID_CTRL_RUNNING, &usbhid->iofl)) {
usbhid_restart_ctrl_queue(usbhid);
/* Otherwise see if an earlier request has timed out */
} else if (time_after(jiffies, usbhid->last_ctrl + HZ * 5)) {
/* Prevent autosuspend following the unlink */
usb_autopm_get_interface_no_resume(usbhid->intf);
/*
* Prevent resubmission in case the URB completes
* before we can unlink it. We don't want to cancel
* the wrong transfer!
*/
usb_block_urb(usbhid->urbctrl);
/* Drop lock to avoid deadlock if the callback runs */
spin_unlock(&usbhid->lock);
usb_unlink_urb(usbhid->urbctrl);
spin_lock(&usbhid->lock);
usb_unblock_urb(usbhid->urbctrl);
/* Unlink might have stopped the queue */
if (!test_bit(HID_CTRL_RUNNING, &usbhid->iofl))
usbhid_restart_ctrl_queue(usbhid);
/* Now we can allow autosuspend again */
usb_autopm_put_interface_async(usbhid->intf);
}
}
static void usbhid_submit_report(struct hid_device *hid, struct hid_report *report, unsigned char dir)
{
struct usbhid_device *usbhid = hid->driver_data;
unsigned long flags;
spin_lock_irqsave(&usbhid->lock, flags);
__usbhid_submit_report(hid, report, dir);
spin_unlock_irqrestore(&usbhid->lock, flags);
}
static int usbhid_wait_io(struct hid_device *hid)
{
struct usbhid_device *usbhid = hid->driver_data;
if (!wait_event_timeout(usbhid->wait,
(!test_bit(HID_CTRL_RUNNING, &usbhid->iofl) &&
!test_bit(HID_OUT_RUNNING, &usbhid->iofl)),
10*HZ)) {
dbg_hid("timeout waiting for ctrl or out queue to clear\n");
return -1;
}
return 0;
}
static int hid_set_idle(struct usb_device *dev, int ifnum, int report, int idle)
{
return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
HID_REQ_SET_IDLE, USB_TYPE_CLASS | USB_RECIP_INTERFACE, (idle << 8) | report,
ifnum, NULL, 0, USB_CTRL_SET_TIMEOUT);
}
static int hid_get_class_descriptor(struct usb_device *dev, int ifnum,
unsigned char type, void *buf, int size)
{
int result, retries = 4;
memset(buf, 0, size);
do {
result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
USB_REQ_GET_DESCRIPTOR, USB_RECIP_INTERFACE | USB_DIR_IN,
(type << 8), ifnum, buf, size, USB_CTRL_GET_TIMEOUT);
retries--;
} while (result < size && retries);
return result;
}
int usbhid_open(struct hid_device *hid)
{
struct usbhid_device *usbhid = hid->driver_data;
int res = 0;
mutex_lock(&hid_open_mut);
if (!hid->open++) {
res = usb_autopm_get_interface(usbhid->intf);
/* the device must be awake to reliably request remote wakeup */
if (res < 0) {
hid->open--;
res = -EIO;
goto done;
}
usbhid->intf->needs_remote_wakeup = 1;
res = hid_start_in(hid);
if (res) {
if (res != -ENOSPC) {
hid_io_error(hid);
res = 0;
} else {
/* no use opening if resources are insufficient */
hid->open--;
res = -EBUSY;
usbhid->intf->needs_remote_wakeup = 0;
}
}
usb_autopm_put_interface(usbhid->intf);
}
done:
mutex_unlock(&hid_open_mut);
return res;
}
void usbhid_close(struct hid_device *hid)
{
struct usbhid_device *usbhid = hid->driver_data;
mutex_lock(&hid_open_mut);
/* protecting hid->open to make sure we don't restart
* data acquistion due to a resumption we no longer
* care about
*/
spin_lock_irq(&usbhid->lock);
if (!--hid->open) {
spin_unlock_irq(&usbhid->lock);
hid_cancel_delayed_stuff(usbhid);
if (!(hid->quirks & HID_QUIRK_ALWAYS_POLL)) {
usb_kill_urb(usbhid->urbin);
usbhid->intf->needs_remote_wakeup = 0;
}
} else {
spin_unlock_irq(&usbhid->lock);
}
mutex_unlock(&hid_open_mut);
}
/*
* Initialize all reports
*/
void usbhid_init_reports(struct hid_device *hid)
{
struct hid_report *report;
struct usbhid_device *usbhid = hid->driver_data;
struct hid_report_enum *report_enum;
int err, ret;
if (!(hid->quirks & HID_QUIRK_NO_INIT_INPUT_REPORTS)) {
report_enum = &hid->report_enum[HID_INPUT_REPORT];
list_for_each_entry(report, &report_enum->report_list, list)
usbhid_submit_report(hid, report, USB_DIR_IN);
}
report_enum = &hid->report_enum[HID_FEATURE_REPORT];
list_for_each_entry(report, &report_enum->report_list, list)
usbhid_submit_report(hid, report, USB_DIR_IN);
err = 0;
ret = usbhid_wait_io(hid);
while (ret) {
err |= ret;
if (test_bit(HID_CTRL_RUNNING, &usbhid->iofl))
usb_kill_urb(usbhid->urbctrl);
if (test_bit(HID_OUT_RUNNING, &usbhid->iofl))
usb_kill_urb(usbhid->urbout);
ret = usbhid_wait_io(hid);
}
if (err)
hid_warn(hid, "timeout initializing reports\n");
}
/*
* Reset LEDs which BIOS might have left on. For now, just NumLock (0x01).
*/
static int hid_find_field_early(struct hid_device *hid, unsigned int page,
unsigned int hid_code, struct hid_field **pfield)
{
struct hid_report *report;
struct hid_field *field;
struct hid_usage *usage;
int i, j;
list_for_each_entry(report, &hid->report_enum[HID_OUTPUT_REPORT].report_list, list) {
for (i = 0; i < report->maxfield; i++) {
field = report->field[i];
for (j = 0; j < field->maxusage; j++) {
usage = &field->usage[j];
if ((usage->hid & HID_USAGE_PAGE) == page &&
(usage->hid & 0xFFFF) == hid_code) {
*pfield = field;
return j;
}
}
}
}
return -1;
}
static void usbhid_set_leds(struct hid_device *hid)
{
struct hid_field *field;
int offset;
if ((offset = hid_find_field_early(hid, HID_UP_LED, 0x01, &field)) != -1) {
hid_set_field(field, offset, 0);
usbhid_submit_report(hid, field->report, USB_DIR_OUT);
}
}
/*
* Traverse the supplied list of reports and find the longest
*/
static void hid_find_max_report(struct hid_device *hid, unsigned int type,
unsigned int *max)
{
struct hid_report *report;
unsigned int size;
list_for_each_entry(report, &hid->report_enum[type].report_list, list) {
size = ((report->size - 1) >> 3) + 1 + hid->report_enum[type].numbered;
if (*max < size)
*max = size;
}
}
static int hid_alloc_buffers(struct usb_device *dev, struct hid_device *hid)
{
struct usbhid_device *usbhid = hid->driver_data;
usbhid->inbuf = usb_alloc_coherent(dev, usbhid->bufsize, GFP_KERNEL,
&usbhid->inbuf_dma);
usbhid->outbuf = usb_alloc_coherent(dev, usbhid->bufsize, GFP_KERNEL,
&usbhid->outbuf_dma);
usbhid->cr = kmalloc(sizeof(*usbhid->cr), GFP_KERNEL);
usbhid->ctrlbuf = usb_alloc_coherent(dev, usbhid->bufsize, GFP_KERNEL,
&usbhid->ctrlbuf_dma);
if (!usbhid->inbuf || !usbhid->outbuf || !usbhid->cr ||
!usbhid->ctrlbuf)
return -1;
return 0;
}
static int usbhid_get_raw_report(struct hid_device *hid,
unsigned char report_number, __u8 *buf, size_t count,
unsigned char report_type)
{
struct usbhid_device *usbhid = hid->driver_data;
struct usb_device *dev = hid_to_usb_dev(hid);
struct usb_interface *intf = usbhid->intf;
struct usb_host_interface *interface = intf->cur_altsetting;
int skipped_report_id = 0;
int ret;
/* Byte 0 is the report number. Report data starts at byte 1.*/
buf[0] = report_number;
if (report_number == 0x0) {
/* Offset the return buffer by 1, so that the report ID
will remain in byte 0. */
buf++;
count--;
skipped_report_id = 1;
}
ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
HID_REQ_GET_REPORT,
USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
((report_type + 1) << 8) | report_number,
interface->desc.bInterfaceNumber, buf, count,
USB_CTRL_SET_TIMEOUT);
/* count also the report id */
if (ret > 0 && skipped_report_id)
ret++;
return ret;
}
static int usbhid_set_raw_report(struct hid_device *hid, unsigned int reportnum,
__u8 *buf, size_t count, unsigned char rtype)
{
struct usbhid_device *usbhid = hid->driver_data;
struct usb_device *dev = hid_to_usb_dev(hid);
struct usb_interface *intf = usbhid->intf;
struct usb_host_interface *interface = intf->cur_altsetting;
int ret, skipped_report_id = 0;
/* Byte 0 is the report number. Report data starts at byte 1.*/
if ((rtype == HID_OUTPUT_REPORT) &&
(hid->quirks & HID_QUIRK_SKIP_OUTPUT_REPORT_ID))
buf[0] = 0;
else
buf[0] = reportnum;
if (buf[0] == 0x0) {
/* Don't send the Report ID */
buf++;
count--;
skipped_report_id = 1;
}
ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
HID_REQ_SET_REPORT,
USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
((rtype + 1) << 8) | reportnum,
interface->desc.bInterfaceNumber, buf, count,
USB_CTRL_SET_TIMEOUT);
/* count also the report id, if this was a numbered report. */
if (ret > 0 && skipped_report_id)
ret++;
return ret;
}
static int usbhid_output_report(struct hid_device *hid, __u8 *buf, size_t count)
{
struct usbhid_device *usbhid = hid->driver_data;
struct usb_device *dev = hid_to_usb_dev(hid);
int actual_length, skipped_report_id = 0, ret;
if (!usbhid->urbout)
return -ENOSYS;
if (buf[0] == 0x0) {
/* Don't send the Report ID */
buf++;
count--;
skipped_report_id = 1;
}
ret = usb_interrupt_msg(dev, usbhid->urbout->pipe,
buf, count, &actual_length,
USB_CTRL_SET_TIMEOUT);
/* return the number of bytes transferred */
if (ret == 0) {
ret = actual_length;
/* count also the report id */
if (skipped_report_id)
ret++;
}
return ret;
}
static void usbhid_restart_queues(struct usbhid_device *usbhid)
{
if (usbhid->urbout && !test_bit(HID_OUT_RUNNING, &usbhid->iofl))
usbhid_restart_out_queue(usbhid);
if (!test_bit(HID_CTRL_RUNNING, &usbhid->iofl))
usbhid_restart_ctrl_queue(usbhid);
}
static void hid_free_buffers(struct usb_device *dev, struct hid_device *hid)
{
struct usbhid_device *usbhid = hid->driver_data;
usb_free_coherent(dev, usbhid->bufsize, usbhid->inbuf, usbhid->inbuf_dma);
usb_free_coherent(dev, usbhid->bufsize, usbhid->outbuf, usbhid->outbuf_dma);
kfree(usbhid->cr);
usb_free_coherent(dev, usbhid->bufsize, usbhid->ctrlbuf, usbhid->ctrlbuf_dma);
}
static int usbhid_parse(struct hid_device *hid)
{
struct usb_interface *intf = to_usb_interface(hid->dev.parent);
struct usb_host_interface *interface = intf->cur_altsetting;
struct usb_device *dev = interface_to_usbdev (intf);
struct hid_descriptor *hdesc;
u32 quirks = 0;
unsigned int rsize = 0;
char *rdesc;
int ret, n;
quirks = usbhid_lookup_quirk(le16_to_cpu(dev->descriptor.idVendor),
le16_to_cpu(dev->descriptor.idProduct));
if (quirks & HID_QUIRK_IGNORE)
return -ENODEV;
/* Many keyboards and mice don't like to be polled for reports,
* so we will always set the HID_QUIRK_NOGET flag for them. */
if (interface->desc.bInterfaceSubClass == USB_INTERFACE_SUBCLASS_BOOT) {
if (interface->desc.bInterfaceProtocol == USB_INTERFACE_PROTOCOL_KEYBOARD ||
interface->desc.bInterfaceProtocol == USB_INTERFACE_PROTOCOL_MOUSE)
quirks |= HID_QUIRK_NOGET;
}
if (usb_get_extra_descriptor(interface, HID_DT_HID, &hdesc) &&
(!interface->desc.bNumEndpoints ||
usb_get_extra_descriptor(&interface->endpoint[0], HID_DT_HID, &hdesc))) {
dbg_hid("class descriptor not present\n");
return -ENODEV;
}
hid->version = le16_to_cpu(hdesc->bcdHID);
hid->country = hdesc->bCountryCode;
for (n = 0; n < hdesc->bNumDescriptors; n++)
if (hdesc->desc[n].bDescriptorType == HID_DT_REPORT)
rsize = le16_to_cpu(hdesc->desc[n].wDescriptorLength);
if (!rsize || rsize > HID_MAX_DESCRIPTOR_SIZE) {
dbg_hid("weird size of report descriptor (%u)\n", rsize);
return -EINVAL;
}
if (!(rdesc = kmalloc(rsize, GFP_KERNEL))) {
dbg_hid("couldn't allocate rdesc memory\n");
return -ENOMEM;
}
hid_set_idle(dev, interface->desc.bInterfaceNumber, 0, 0);
ret = hid_get_class_descriptor(dev, interface->desc.bInterfaceNumber,
HID_DT_REPORT, rdesc, rsize);
if (ret < 0) {
dbg_hid("reading report descriptor failed\n");
kfree(rdesc);
goto err;
}
ret = hid_parse_report(hid, rdesc, rsize);
kfree(rdesc);
if (ret) {
dbg_hid("parsing report descriptor failed\n");
goto err;
}
hid->quirks |= quirks;
return 0;
err:
return ret;
}
static int usbhid_start(struct hid_device *hid)
{
struct usb_interface *intf = to_usb_interface(hid->dev.parent);
struct usb_host_interface *interface = intf->cur_altsetting;
struct usb_device *dev = interface_to_usbdev(intf);
struct usbhid_device *usbhid = hid->driver_data;
unsigned int n, insize = 0;
int ret;
clear_bit(HID_DISCONNECTED, &usbhid->iofl);
usbhid->bufsize = HID_MIN_BUFFER_SIZE;
hid_find_max_report(hid, HID_INPUT_REPORT, &usbhid->bufsize);
hid_find_max_report(hid, HID_OUTPUT_REPORT, &usbhid->bufsize);
hid_find_max_report(hid, HID_FEATURE_REPORT, &usbhid->bufsize);
if (usbhid->bufsize > HID_MAX_BUFFER_SIZE)
usbhid->bufsize = HID_MAX_BUFFER_SIZE;
hid_find_max_report(hid, HID_INPUT_REPORT, &insize);
if (insize > HID_MAX_BUFFER_SIZE)
insize = HID_MAX_BUFFER_SIZE;
if (hid_alloc_buffers(dev, hid)) {
ret = -ENOMEM;
goto fail;
}
for (n = 0; n < interface->desc.bNumEndpoints; n++) {
struct usb_endpoint_descriptor *endpoint;
int pipe;
int interval;
endpoint = &interface->endpoint[n].desc;
if (!usb_endpoint_xfer_int(endpoint))
continue;
interval = endpoint->bInterval;
/* Some vendors give fullspeed interval on highspeed devides */
if (hid->quirks & HID_QUIRK_FULLSPEED_INTERVAL &&
dev->speed == USB_SPEED_HIGH) {
interval = fls(endpoint->bInterval*8);
printk(KERN_INFO "%s: Fixing fullspeed to highspeed interval: %d -> %d\n",
hid->name, endpoint->bInterval, interval);
}
/* Change the polling interval of mice. */
if (hid->collection->usage == HID_GD_MOUSE && hid_mousepoll_interval > 0)
interval = hid_mousepoll_interval;
ret = -ENOMEM;
if (usb_endpoint_dir_in(endpoint)) {
if (usbhid->urbin)
continue;
if (!(usbhid->urbin = usb_alloc_urb(0, GFP_KERNEL)))
goto fail;
pipe = usb_rcvintpipe(dev, endpoint->bEndpointAddress);
usb_fill_int_urb(usbhid->urbin, dev, pipe, usbhid->inbuf, insize,
hid_irq_in, hid, interval);
usbhid->urbin->transfer_dma = usbhid->inbuf_dma;
usbhid->urbin->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
} else {
if (usbhid->urbout)
continue;
if (!(usbhid->urbout = usb_alloc_urb(0, GFP_KERNEL)))
goto fail;
pipe = usb_sndintpipe(dev, endpoint->bEndpointAddress);
usb_fill_int_urb(usbhid->urbout, dev, pipe, usbhid->outbuf, 0,
hid_irq_out, hid, interval);
usbhid->urbout->transfer_dma = usbhid->outbuf_dma;
usbhid->urbout->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
}
}
usbhid->urbctrl = usb_alloc_urb(0, GFP_KERNEL);
if (!usbhid->urbctrl) {
ret = -ENOMEM;
goto fail;
}
usb_fill_control_urb(usbhid->urbctrl, dev, 0, (void *) usbhid->cr,
usbhid->ctrlbuf, 1, hid_ctrl, hid);
usbhid->urbctrl->transfer_dma = usbhid->ctrlbuf_dma;
usbhid->urbctrl->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
if (!(hid->quirks & HID_QUIRK_NO_INIT_REPORTS))
usbhid_init_reports(hid);
set_bit(HID_STARTED, &usbhid->iofl);
if (hid->quirks & HID_QUIRK_ALWAYS_POLL) {
ret = usb_autopm_get_interface(usbhid->intf);
if (ret)
goto fail;
usbhid->intf->needs_remote_wakeup = 1;
ret = hid_start_in(hid);
if (ret) {
dev_err(&hid->dev,
"failed to start in urb: %d\n", ret);
}
usb_autopm_put_interface(usbhid->intf);
}
/* Some keyboards don't work until their LEDs have been set.
* Since BIOSes do set the LEDs, it must be safe for any device
* that supports the keyboard boot protocol.
* In addition, enable remote wakeup by default for all keyboard
* devices supporting the boot protocol.
*/
if (interface->desc.bInterfaceSubClass == USB_INTERFACE_SUBCLASS_BOOT &&
interface->desc.bInterfaceProtocol ==
USB_INTERFACE_PROTOCOL_KEYBOARD) {
usbhid_set_leds(hid);
device_set_wakeup_enable(&dev->dev, 1);
}
return 0;
fail:
usb_free_urb(usbhid->urbin);
usb_free_urb(usbhid->urbout);
usb_free_urb(usbhid->urbctrl);
usbhid->urbin = NULL;
usbhid->urbout = NULL;
usbhid->urbctrl = NULL;
hid_free_buffers(dev, hid);
return ret;
}
static void usbhid_stop(struct hid_device *hid)
{
struct usbhid_device *usbhid = hid->driver_data;
if (WARN_ON(!usbhid))
return;
if (hid->quirks & HID_QUIRK_ALWAYS_POLL)
usbhid->intf->needs_remote_wakeup = 0;
clear_bit(HID_STARTED, &usbhid->iofl);
spin_lock_irq(&usbhid->lock); /* Sync with error and led handlers */
set_bit(HID_DISCONNECTED, &usbhid->iofl);
spin_unlock_irq(&usbhid->lock);
usb_kill_urb(usbhid->urbin);
usb_kill_urb(usbhid->urbout);
usb_kill_urb(usbhid->urbctrl);
hid_cancel_delayed_stuff(usbhid);
hid->claimed = 0;
usb_free_urb(usbhid->urbin);
usb_free_urb(usbhid->urbctrl);
usb_free_urb(usbhid->urbout);
usbhid->urbin = NULL; /* don't mess up next start */
usbhid->urbctrl = NULL;
usbhid->urbout = NULL;
hid_free_buffers(hid_to_usb_dev(hid), hid);
}
static int usbhid_power(struct hid_device *hid, int lvl)
{
int r = 0;
switch (lvl) {
case PM_HINT_FULLON:
r = usbhid_get_power(hid);
break;
case PM_HINT_NORMAL:
usbhid_put_power(hid);
break;
}
return r;
}
static void usbhid_request(struct hid_device *hid, struct hid_report *rep, int reqtype)
{
switch (reqtype) {
case HID_REQ_GET_REPORT:
usbhid_submit_report(hid, rep, USB_DIR_IN);
break;
case HID_REQ_SET_REPORT:
usbhid_submit_report(hid, rep, USB_DIR_OUT);
break;
}
}
static int usbhid_raw_request(struct hid_device *hid, unsigned char reportnum,
__u8 *buf, size_t len, unsigned char rtype,
int reqtype)
{
switch (reqtype) {
case HID_REQ_GET_REPORT:
return usbhid_get_raw_report(hid, reportnum, buf, len, rtype);
case HID_REQ_SET_REPORT:
return usbhid_set_raw_report(hid, reportnum, buf, len, rtype);
default:
return -EIO;
}
}
static int usbhid_idle(struct hid_device *hid, int report, int idle,
int reqtype)
{
struct usb_device *dev = hid_to_usb_dev(hid);
struct usb_interface *intf = to_usb_interface(hid->dev.parent);
struct usb_host_interface *interface = intf->cur_altsetting;
int ifnum = interface->desc.bInterfaceNumber;
if (reqtype != HID_REQ_SET_IDLE)
return -EINVAL;
return hid_set_idle(dev, ifnum, report, idle);
}
static struct hid_ll_driver usb_hid_driver = {
.parse = usbhid_parse,
.start = usbhid_start,
.stop = usbhid_stop,
.open = usbhid_open,
.close = usbhid_close,
.power = usbhid_power,
.request = usbhid_request,
.wait = usbhid_wait_io,
.raw_request = usbhid_raw_request,
.output_report = usbhid_output_report,
.idle = usbhid_idle,
};
static int usbhid_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct usb_host_interface *interface = intf->cur_altsetting;
struct usb_device *dev = interface_to_usbdev(intf);
struct usbhid_device *usbhid;
struct hid_device *hid;
unsigned int n, has_in = 0;
size_t len;
int ret;
dbg_hid("HID probe called for ifnum %d\n",
intf->altsetting->desc.bInterfaceNumber);
for (n = 0; n < interface->desc.bNumEndpoints; n++)
if (usb_endpoint_is_int_in(&interface->endpoint[n].desc))
has_in++;
if (!has_in) {
hid_err(intf, "couldn't find an input interrupt endpoint\n");
return -ENODEV;
}
hid = hid_allocate_device();
if (IS_ERR(hid))
return PTR_ERR(hid);
usb_set_intfdata(intf, hid);
hid->ll_driver = &usb_hid_driver;
hid->ff_init = hid_pidff_init;
#ifdef CONFIG_USB_HIDDEV
hid->hiddev_connect = hiddev_connect;
hid->hiddev_disconnect = hiddev_disconnect;
hid->hiddev_hid_event = hiddev_hid_event;
hid->hiddev_report_event = hiddev_report_event;
#endif
hid->dev.parent = &intf->dev;
hid->bus = BUS_USB;
hid->vendor = le16_to_cpu(dev->descriptor.idVendor);
hid->product = le16_to_cpu(dev->descriptor.idProduct);
hid->name[0] = 0;
hid->quirks = usbhid_lookup_quirk(hid->vendor, hid->product);
if (intf->cur_altsetting->desc.bInterfaceProtocol ==
USB_INTERFACE_PROTOCOL_MOUSE)
hid->type = HID_TYPE_USBMOUSE;
else if (intf->cur_altsetting->desc.bInterfaceProtocol == 0)
hid->type = HID_TYPE_USBNONE;
if (dev->manufacturer)
strlcpy(hid->name, dev->manufacturer, sizeof(hid->name));
if (dev->product) {
if (dev->manufacturer)
strlcat(hid->name, " ", sizeof(hid->name));
strlcat(hid->name, dev->product, sizeof(hid->name));
}
if (!strlen(hid->name))
snprintf(hid->name, sizeof(hid->name), "HID %04x:%04x",
le16_to_cpu(dev->descriptor.idVendor),
le16_to_cpu(dev->descriptor.idProduct));
usb_make_path(dev, hid->phys, sizeof(hid->phys));
strlcat(hid->phys, "/input", sizeof(hid->phys));
len = strlen(hid->phys);
if (len < sizeof(hid->phys) - 1)
snprintf(hid->phys + len, sizeof(hid->phys) - len,
"%d", intf->altsetting[0].desc.bInterfaceNumber);
if (usb_string(dev, dev->descriptor.iSerialNumber, hid->uniq, 64) <= 0)
hid->uniq[0] = 0;
usbhid = kzalloc(sizeof(*usbhid), GFP_KERNEL);
if (usbhid == NULL) {
ret = -ENOMEM;
goto err;
}
hid->driver_data = usbhid;
usbhid->hid = hid;
usbhid->intf = intf;
usbhid->ifnum = interface->desc.bInterfaceNumber;
init_waitqueue_head(&usbhid->wait);
INIT_WORK(&usbhid->reset_work, hid_reset);
setup_timer(&usbhid->io_retry, hid_retry_timeout, (unsigned long) hid);
spin_lock_init(&usbhid->lock);
ret = hid_add_device(hid);
if (ret) {
if (ret != -ENODEV)
hid_err(intf, "can't add hid device: %d\n", ret);
goto err_free;
}
return 0;
err_free:
kfree(usbhid);
err:
hid_destroy_device(hid);
return ret;
}
static void usbhid_disconnect(struct usb_interface *intf)
{
struct hid_device *hid = usb_get_intfdata(intf);
struct usbhid_device *usbhid;
if (WARN_ON(!hid))
return;
usbhid = hid->driver_data;
spin_lock_irq(&usbhid->lock); /* Sync with error and led handlers */
set_bit(HID_DISCONNECTED, &usbhid->iofl);
spin_unlock_irq(&usbhid->lock);
hid_destroy_device(hid);
kfree(usbhid);
}
static void hid_cancel_delayed_stuff(struct usbhid_device *usbhid)
{
del_timer_sync(&usbhid->io_retry);
cancel_work_sync(&usbhid->reset_work);
}
static void hid_cease_io(struct usbhid_device *usbhid)
{
del_timer_sync(&usbhid->io_retry);
usb_kill_urb(usbhid->urbin);
usb_kill_urb(usbhid->urbctrl);
usb_kill_urb(usbhid->urbout);
}
/* Treat USB reset pretty much the same as suspend/resume */
static int hid_pre_reset(struct usb_interface *intf)
{
struct hid_device *hid = usb_get_intfdata(intf);
struct usbhid_device *usbhid = hid->driver_data;
spin_lock_irq(&usbhid->lock);
set_bit(HID_RESET_PENDING, &usbhid->iofl);
spin_unlock_irq(&usbhid->lock);
hid_cease_io(usbhid);
return 0;
}
/* Same routine used for post_reset and reset_resume */
static int hid_post_reset(struct usb_interface *intf)
{
struct usb_device *dev = interface_to_usbdev (intf);
struct hid_device *hid = usb_get_intfdata(intf);
struct usbhid_device *usbhid = hid->driver_data;
struct usb_host_interface *interface = intf->cur_altsetting;
int status;
char *rdesc;
/* Fetch and examine the HID report descriptor. If this
* has changed, then rebind. Since usbcore's check of the
* configuration descriptors passed, we already know that
* the size of the HID report descriptor has not changed.
*/
rdesc = kmalloc(hid->dev_rsize, GFP_KERNEL);
if (!rdesc) {
dbg_hid("couldn't allocate rdesc memory (post_reset)\n");
return 1;
}
status = hid_get_class_descriptor(dev,
interface->desc.bInterfaceNumber,
HID_DT_REPORT, rdesc, hid->dev_rsize);
if (status < 0) {
dbg_hid("reading report descriptor failed (post_reset)\n");
kfree(rdesc);
return 1;
}
status = memcmp(rdesc, hid->dev_rdesc, hid->dev_rsize);
kfree(rdesc);
if (status != 0) {
dbg_hid("report descriptor changed\n");
return 1;
}
spin_lock_irq(&usbhid->lock);
clear_bit(HID_RESET_PENDING, &usbhid->iofl);
spin_unlock_irq(&usbhid->lock);
hid_set_idle(dev, intf->cur_altsetting->desc.bInterfaceNumber, 0, 0);
status = hid_start_in(hid);
if (status < 0)
hid_io_error(hid);
usbhid_restart_queues(usbhid);
return 0;
}
int usbhid_get_power(struct hid_device *hid)
{
struct usbhid_device *usbhid = hid->driver_data;
return usb_autopm_get_interface(usbhid->intf);
}
void usbhid_put_power(struct hid_device *hid)
{
struct usbhid_device *usbhid = hid->driver_data;
usb_autopm_put_interface(usbhid->intf);
}
#ifdef CONFIG_PM
static int hid_resume_common(struct hid_device *hid, bool driver_suspended)
{
struct usbhid_device *usbhid = hid->driver_data;
int status;
spin_lock_irq(&usbhid->lock);
clear_bit(HID_SUSPENDED, &usbhid->iofl);
usbhid_mark_busy(usbhid);
if (test_bit(HID_CLEAR_HALT, &usbhid->iofl) ||
test_bit(HID_RESET_PENDING, &usbhid->iofl))
schedule_work(&usbhid->reset_work);
usbhid->retry_delay = 0;
usbhid_restart_queues(usbhid);
spin_unlock_irq(&usbhid->lock);
status = hid_start_in(hid);
if (status < 0)
hid_io_error(hid);
if (driver_suspended && hid->driver && hid->driver->resume)
status = hid->driver->resume(hid);
return status;
}
static int hid_suspend(struct usb_interface *intf, pm_message_t message)
{
struct hid_device *hid = usb_get_intfdata(intf);
struct usbhid_device *usbhid = hid->driver_data;
int status = 0;
bool driver_suspended = false;
unsigned int ledcount;
if (PMSG_IS_AUTO(message)) {
ledcount = hidinput_count_leds(hid);
spin_lock_irq(&usbhid->lock); /* Sync with error handler */
if (!test_bit(HID_RESET_PENDING, &usbhid->iofl)
&& !test_bit(HID_CLEAR_HALT, &usbhid->iofl)
&& !test_bit(HID_OUT_RUNNING, &usbhid->iofl)
&& !test_bit(HID_CTRL_RUNNING, &usbhid->iofl)
&& !test_bit(HID_KEYS_PRESSED, &usbhid->iofl)
&& (!ledcount || ignoreled))
{
set_bit(HID_SUSPENDED, &usbhid->iofl);
spin_unlock_irq(&usbhid->lock);
if (hid->driver && hid->driver->suspend) {
status = hid->driver->suspend(hid, message);
if (status < 0)
goto failed;
}
driver_suspended = true;
} else {
usbhid_mark_busy(usbhid);
spin_unlock_irq(&usbhid->lock);
return -EBUSY;
}
} else {
/* TODO: resume() might need to handle suspend failure */
if (hid->driver && hid->driver->suspend)
status = hid->driver->suspend(hid, message);
driver_suspended = true;
spin_lock_irq(&usbhid->lock);
set_bit(HID_SUSPENDED, &usbhid->iofl);
spin_unlock_irq(&usbhid->lock);
if (usbhid_wait_io(hid) < 0)
status = -EIO;
}
hid_cancel_delayed_stuff(usbhid);
hid_cease_io(usbhid);
if (PMSG_IS_AUTO(message) && test_bit(HID_KEYS_PRESSED, &usbhid->iofl)) {
/* lost race against keypresses */
status = -EBUSY;
goto failed;
}
dev_dbg(&intf->dev, "suspend\n");
return status;
failed:
hid_resume_common(hid, driver_suspended);
return status;
}
static int hid_resume(struct usb_interface *intf)
{
struct hid_device *hid = usb_get_intfdata (intf);
struct usbhid_device *usbhid = hid->driver_data;
int status;
if (!test_bit(HID_STARTED, &usbhid->iofl))
return 0;
status = hid_resume_common(hid, true);
dev_dbg(&intf->dev, "resume status %d\n", status);
return 0;
}
static int hid_reset_resume(struct usb_interface *intf)
{
struct hid_device *hid = usb_get_intfdata(intf);
struct usbhid_device *usbhid = hid->driver_data;
int status;
clear_bit(HID_SUSPENDED, &usbhid->iofl);
status = hid_post_reset(intf);
if (status >= 0 && hid->driver && hid->driver->reset_resume) {
int ret = hid->driver->reset_resume(hid);
if (ret < 0)
status = ret;
}
return status;
}
#endif /* CONFIG_PM */
static const struct usb_device_id hid_usb_ids[] = {
{ .match_flags = USB_DEVICE_ID_MATCH_INT_CLASS,
.bInterfaceClass = USB_INTERFACE_CLASS_HID },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE (usb, hid_usb_ids);
static struct usb_driver hid_driver = {
.name = "usbhid",
.probe = usbhid_probe,
.disconnect = usbhid_disconnect,
#ifdef CONFIG_PM
.suspend = hid_suspend,
.resume = hid_resume,
.reset_resume = hid_reset_resume,
#endif
.pre_reset = hid_pre_reset,
.post_reset = hid_post_reset,
.id_table = hid_usb_ids,
.supports_autosuspend = 1,
};
struct usb_interface *usbhid_find_interface(int minor)
{
return usb_find_interface(&hid_driver, minor);
}
static int __init hid_init(void)
{
int retval = -ENOMEM;
retval = usbhid_quirks_init(quirks_param);
if (retval)
goto usbhid_quirks_init_fail;
retval = usb_register(&hid_driver);
if (retval)
goto usb_register_fail;
printk(KERN_INFO KBUILD_MODNAME ": " DRIVER_DESC "\n");
return 0;
usb_register_fail:
usbhid_quirks_exit();
usbhid_quirks_init_fail:
return retval;
}
static void __exit hid_exit(void)
{
usb_deregister(&hid_driver);
usbhid_quirks_exit();
}
module_init(hid_init);
module_exit(hid_exit);
MODULE_AUTHOR("Andreas Gal");
MODULE_AUTHOR("Vojtech Pavlik");
MODULE_AUTHOR("Jiri Kosina");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE(DRIVER_LICENSE);
|
26008.c | /* vi:set ts=8 sts=4 sw=4 noet:
*
* VIM - Vi IMproved by Bram Moolenaar
*
* Do ":help uganda" in Vim to read copying and usage conditions.
* Do ":help credits" in Vim to see a list of people who contributed.
* See README.txt for an overview of the Vim source code.
*/
/*
* eval.c: Expression evaluation.
*/
#define USING_FLOAT_STUFF
#include "vim.h"
#if defined(FEAT_EVAL) || defined(PROTO)
#ifdef VMS
# include <float.h>
#endif
#define NAMESPACE_CHAR (char_u *)"abglstvw"
/*
* When recursively copying lists and dicts we need to remember which ones we
* have done to avoid endless recursiveness. This unique ID is used for that.
* The last bit is used for previous_funccal, ignored when comparing.
*/
static int current_copyID = 0;
/*
* Info used by a ":for" loop.
*/
typedef struct
{
int fi_semicolon; // TRUE if ending in '; var]'
int fi_varcount; // nr of variables in the list
int fi_break_count; // nr of line breaks encountered
listwatch_T fi_lw; // keep an eye on the item used.
list_T *fi_list; // list being used
int fi_bi; // index of blob
blob_T *fi_blob; // blob being used
} forinfo_T;
static int tv_op(typval_T *tv1, typval_T *tv2, char_u *op);
static int eval2(char_u **arg, typval_T *rettv, evalarg_T *evalarg);
static int eval3(char_u **arg, typval_T *rettv, evalarg_T *evalarg);
static int eval4(char_u **arg, typval_T *rettv, evalarg_T *evalarg);
static int eval5(char_u **arg, typval_T *rettv, evalarg_T *evalarg);
static int eval6(char_u **arg, typval_T *rettv, evalarg_T *evalarg, int want_string);
static int eval7(char_u **arg, typval_T *rettv, evalarg_T *evalarg, int want_string);
static int eval7_leader(typval_T *rettv, int numeric_only, char_u *start_leader, char_u **end_leaderp);
static int free_unref_items(int copyID);
static char_u *make_expanded_name(char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end);
/*
* Return "n1" divided by "n2", taking care of dividing by zero.
* If "failed" is not NULL set it to TRUE when dividing by zero fails.
*/
varnumber_T
num_divide(varnumber_T n1, varnumber_T n2, int *failed)
{
varnumber_T result;
if (n2 == 0)
{
if (in_vim9script())
{
emsg(_(e_divide_by_zero));
if (failed != NULL)
*failed = TRUE;
}
if (n1 == 0)
result = VARNUM_MIN; // similar to NaN
else if (n1 < 0)
result = -VARNUM_MAX;
else
result = VARNUM_MAX;
}
else
result = n1 / n2;
return result;
}
/*
* Return "n1" modulus "n2", taking care of dividing by zero.
* If "failed" is not NULL set it to TRUE when dividing by zero fails.
*/
varnumber_T
num_modulus(varnumber_T n1, varnumber_T n2, int *failed)
{
if (n2 == 0 && in_vim9script())
{
emsg(_(e_divide_by_zero));
if (failed != NULL)
*failed = TRUE;
}
return (n2 == 0) ? 0 : (n1 % n2);
}
#if defined(EBCDIC) || defined(PROTO)
/*
* Compare struct fst by function name.
*/
static int
compare_func_name(const void *s1, const void *s2)
{
struct fst *p1 = (struct fst *)s1;
struct fst *p2 = (struct fst *)s2;
return STRCMP(p1->f_name, p2->f_name);
}
/*
* Sort the function table by function name.
* The sorting of the table above is ASCII dependent.
* On machines using EBCDIC we have to sort it.
*/
static void
sortFunctions(void)
{
int funcCnt = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
qsort(functions, (size_t)funcCnt, sizeof(struct fst), compare_func_name);
}
#endif
/*
* Initialize the global and v: variables.
*/
void
eval_init(void)
{
evalvars_init();
func_init();
#ifdef EBCDIC
/*
* Sort the function table, to enable binary search.
*/
sortFunctions();
#endif
}
#if defined(EXITFREE) || defined(PROTO)
void
eval_clear(void)
{
evalvars_clear();
free_scriptnames(); // must come after evalvars_clear().
free_locales();
// autoloaded script names
free_autoload_scriptnames();
// unreferenced lists and dicts
(void)garbage_collect(FALSE);
// functions not garbage collected
free_all_functions();
}
#endif
void
fill_evalarg_from_eap(evalarg_T *evalarg, exarg_T *eap, int skip)
{
CLEAR_FIELD(*evalarg);
evalarg->eval_flags = skip ? 0 : EVAL_EVALUATE;
if (eap != NULL && getline_equal(eap->getline, eap->cookie, getsourceline))
{
evalarg->eval_getline = eap->getline;
evalarg->eval_cookie = eap->cookie;
}
}
/*
* Top level evaluation function, returning a boolean.
* Sets "error" to TRUE if there was an error.
* Return TRUE or FALSE.
*/
int
eval_to_bool(
char_u *arg,
int *error,
exarg_T *eap,
int skip) // only parse, don't execute
{
typval_T tv;
varnumber_T retval = FALSE;
evalarg_T evalarg;
fill_evalarg_from_eap(&evalarg, eap, skip);
if (skip)
++emsg_skip;
if (eval0(arg, &tv, eap, &evalarg) == FAIL)
*error = TRUE;
else
{
*error = FALSE;
if (!skip)
{
if (in_vim9script())
retval = tv_get_bool_chk(&tv, error);
else
retval = (tv_get_number_chk(&tv, error) != 0);
clear_tv(&tv);
}
}
if (skip)
--emsg_skip;
clear_evalarg(&evalarg, eap);
return (int)retval;
}
/*
* Call eval1() and give an error message if not done at a lower level.
*/
static int
eval1_emsg(char_u **arg, typval_T *rettv, exarg_T *eap)
{
char_u *start = *arg;
int ret;
int did_emsg_before = did_emsg;
int called_emsg_before = called_emsg;
evalarg_T evalarg;
fill_evalarg_from_eap(&evalarg, eap, eap != NULL && eap->skip);
ret = eval1(arg, rettv, &evalarg);
if (ret == FAIL)
{
// Report the invalid expression unless the expression evaluation has
// been cancelled due to an aborting error, an interrupt, or an
// exception, or we already gave a more specific error.
// Also check called_emsg for when using assert_fails().
if (!aborting() && did_emsg == did_emsg_before
&& called_emsg == called_emsg_before)
semsg(_(e_invexpr2), start);
}
clear_evalarg(&evalarg, eap);
return ret;
}
/*
* Return whether a typval is a valid expression to pass to eval_expr_typval()
* or eval_expr_to_bool(). An empty string returns FALSE;
*/
int
eval_expr_valid_arg(typval_T *tv)
{
return tv->v_type != VAR_UNKNOWN
&& (tv->v_type != VAR_STRING
|| (tv->vval.v_string != NULL && *tv->vval.v_string != NUL));
}
/*
* Evaluate an expression, which can be a function, partial or string.
* Pass arguments "argv[argc]".
* Return the result in "rettv" and OK or FAIL.
*/
int
eval_expr_typval(typval_T *expr, typval_T *argv, int argc, typval_T *rettv)
{
char_u *s;
char_u buf[NUMBUFLEN];
funcexe_T funcexe;
if (expr->v_type == VAR_FUNC)
{
s = expr->vval.v_string;
if (s == NULL || *s == NUL)
return FAIL;
CLEAR_FIELD(funcexe);
funcexe.evaluate = TRUE;
if (call_func(s, -1, rettv, argc, argv, &funcexe) == FAIL)
return FAIL;
}
else if (expr->v_type == VAR_PARTIAL)
{
partial_T *partial = expr->vval.v_partial;
if (partial == NULL)
return FAIL;
if (partial->pt_func != NULL
&& partial->pt_func->uf_def_status != UF_NOT_COMPILED)
{
if (call_def_function(partial->pt_func, argc, argv,
partial, rettv) == FAIL)
return FAIL;
}
else
{
s = partial_name(partial);
if (s == NULL || *s == NUL)
return FAIL;
CLEAR_FIELD(funcexe);
funcexe.evaluate = TRUE;
funcexe.partial = partial;
if (call_func(s, -1, rettv, argc, argv, &funcexe) == FAIL)
return FAIL;
}
}
else
{
s = tv_get_string_buf_chk(expr, buf);
if (s == NULL)
return FAIL;
s = skipwhite(s);
if (eval1_emsg(&s, rettv, NULL) == FAIL)
return FAIL;
if (*skipwhite(s) != NUL) // check for trailing chars after expr
{
clear_tv(rettv);
semsg(_(e_invexpr2), s);
return FAIL;
}
}
return OK;
}
/*
* Like eval_to_bool() but using a typval_T instead of a string.
* Works for string, funcref and partial.
*/
int
eval_expr_to_bool(typval_T *expr, int *error)
{
typval_T rettv;
int res;
if (eval_expr_typval(expr, NULL, 0, &rettv) == FAIL)
{
*error = TRUE;
return FALSE;
}
res = (tv_get_bool_chk(&rettv, error) != 0);
clear_tv(&rettv);
return res;
}
/*
* Top level evaluation function, returning a string. If "skip" is TRUE,
* only parsing to "nextcmd" is done, without reporting errors. Return
* pointer to allocated memory, or NULL for failure or when "skip" is TRUE.
*/
char_u *
eval_to_string_skip(
char_u *arg,
exarg_T *eap,
int skip) // only parse, don't execute
{
typval_T tv;
char_u *retval;
evalarg_T evalarg;
fill_evalarg_from_eap(&evalarg, eap, skip);
if (skip)
++emsg_skip;
if (eval0(arg, &tv, eap, &evalarg) == FAIL || skip)
retval = NULL;
else
{
retval = vim_strsave(tv_get_string(&tv));
clear_tv(&tv);
}
if (skip)
--emsg_skip;
clear_evalarg(&evalarg, eap);
return retval;
}
/*
* Skip over an expression at "*pp".
* Return FAIL for an error, OK otherwise.
*/
int
skip_expr(char_u **pp, evalarg_T *evalarg)
{
typval_T rettv;
*pp = skipwhite(*pp);
return eval1(pp, &rettv, evalarg);
}
/*
* Skip over an expression at "*pp".
* If in Vim9 script and line breaks are encountered, the lines are
* concatenated. "evalarg->eval_tofree" will be set accordingly.
* "arg" is advanced to just after the expression.
* "start" is set to the start of the expression, "end" to just after the end.
* Also when the expression is copied to allocated memory.
* Return FAIL for an error, OK otherwise.
*/
int
skip_expr_concatenate(
char_u **arg,
char_u **start,
char_u **end,
evalarg_T *evalarg)
{
typval_T rettv;
int res;
int vim9script = in_vim9script();
garray_T *gap = evalarg == NULL ? NULL : &evalarg->eval_ga;
int save_flags = evalarg == NULL ? 0 : evalarg->eval_flags;
int evaluate = evalarg == NULL
? FALSE : (evalarg->eval_flags & EVAL_EVALUATE);
if (vim9script && evaluate
&& (evalarg->eval_cookie != NULL || evalarg->eval_cctx != NULL))
{
ga_init2(gap, sizeof(char_u *), 10);
// leave room for "start"
if (ga_grow(gap, 1) == OK)
++gap->ga_len;
}
*start = *arg;
// Don't evaluate the expression.
if (evalarg != NULL)
evalarg->eval_flags &= ~EVAL_EVALUATE;
*arg = skipwhite(*arg);
res = eval1(arg, &rettv, evalarg);
*end = *arg;
if (evalarg != NULL)
evalarg->eval_flags = save_flags;
if (vim9script && evaluate
&& (evalarg->eval_cookie != NULL || evalarg->eval_cctx != NULL))
{
if (evalarg->eval_ga.ga_len == 1)
{
// just one line, no need to concatenate
ga_clear(gap);
gap->ga_itemsize = 0;
}
else
{
char_u *p;
size_t endoff = STRLEN(*arg);
// Line breaks encountered, concatenate all the lines.
*((char_u **)gap->ga_data) = *start;
p = ga_concat_strings(gap, "");
// free the lines only when using getsourceline()
if (evalarg->eval_cookie != NULL)
{
// Do not free the first line, the caller can still use it.
*((char_u **)gap->ga_data) = NULL;
// Do not free the last line, "arg" points into it, free it
// later.
vim_free(evalarg->eval_tofree);
evalarg->eval_tofree =
((char_u **)gap->ga_data)[gap->ga_len - 1];
((char_u **)gap->ga_data)[gap->ga_len - 1] = NULL;
ga_clear_strings(gap);
}
else
ga_clear(gap);
gap->ga_itemsize = 0;
if (p == NULL)
return FAIL;
*start = p;
vim_free(evalarg->eval_tofree_lambda);
evalarg->eval_tofree_lambda = p;
// Compute "end" relative to the end.
*end = *start + STRLEN(*start) - endoff;
}
}
return res;
}
/*
* Convert "tv" to a string.
* When "convert" is TRUE convert a List into a sequence of lines and convert
* a Float to a String.
* Returns an allocated string (NULL when out of memory).
*/
char_u *
typval2string(typval_T *tv, int convert)
{
garray_T ga;
char_u *retval;
#ifdef FEAT_FLOAT
char_u numbuf[NUMBUFLEN];
#endif
if (convert && tv->v_type == VAR_LIST)
{
ga_init2(&ga, (int)sizeof(char), 80);
if (tv->vval.v_list != NULL)
{
list_join(&ga, tv->vval.v_list, (char_u *)"\n", TRUE, FALSE, 0);
if (tv->vval.v_list->lv_len > 0)
ga_append(&ga, NL);
}
ga_append(&ga, NUL);
retval = (char_u *)ga.ga_data;
}
#ifdef FEAT_FLOAT
else if (convert && tv->v_type == VAR_FLOAT)
{
vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv->vval.v_float);
retval = vim_strsave(numbuf);
}
#endif
else
retval = vim_strsave(tv_get_string(tv));
return retval;
}
/*
* Top level evaluation function, returning a string. Does not handle line
* breaks.
* When "convert" is TRUE convert a List into a sequence of lines and convert
* a Float to a String.
* Return pointer to allocated memory, or NULL for failure.
*/
char_u *
eval_to_string_eap(
char_u *arg,
int convert,
exarg_T *eap)
{
typval_T tv;
char_u *retval;
evalarg_T evalarg;
fill_evalarg_from_eap(&evalarg, eap, eap != NULL && eap->skip);
if (eval0(arg, &tv, NULL, &evalarg) == FAIL)
retval = NULL;
else
{
retval = typval2string(&tv, convert);
clear_tv(&tv);
}
clear_evalarg(&evalarg, NULL);
return retval;
}
char_u *
eval_to_string(
char_u *arg,
int convert)
{
return eval_to_string_eap(arg, convert, NULL);
}
/*
* Call eval_to_string() without using current local variables and using
* textwinlock. When "use_sandbox" is TRUE use the sandbox.
* Use legacy Vim script syntax.
*/
char_u *
eval_to_string_safe(
char_u *arg,
int use_sandbox)
{
char_u *retval;
funccal_entry_T funccal_entry;
int save_sc_version = current_sctx.sc_version;
current_sctx.sc_version = 1;
save_funccal(&funccal_entry);
if (use_sandbox)
++sandbox;
++textwinlock;
retval = eval_to_string(arg, FALSE);
if (use_sandbox)
--sandbox;
--textwinlock;
restore_funccal();
current_sctx.sc_version = save_sc_version;
return retval;
}
/*
* Top level evaluation function, returning a number.
* Evaluates "expr" silently.
* Returns -1 for an error.
*/
varnumber_T
eval_to_number(char_u *expr)
{
typval_T rettv;
varnumber_T retval;
char_u *p = skipwhite(expr);
++emsg_off;
if (eval1(&p, &rettv, &EVALARG_EVALUATE) == FAIL)
retval = -1;
else
{
retval = tv_get_number_chk(&rettv, NULL);
clear_tv(&rettv);
}
--emsg_off;
return retval;
}
/*
* Top level evaluation function.
* Returns an allocated typval_T with the result.
* Returns NULL when there is an error.
*/
typval_T *
eval_expr(char_u *arg, exarg_T *eap)
{
typval_T *tv;
evalarg_T evalarg;
fill_evalarg_from_eap(&evalarg, eap, eap != NULL && eap->skip);
tv = ALLOC_ONE(typval_T);
if (tv != NULL && eval0(arg, tv, eap, &evalarg) == FAIL)
VIM_CLEAR(tv);
clear_evalarg(&evalarg, eap);
return tv;
}
/*
* Call some Vim script function and return the result in "*rettv".
* Uses argv[0] to argv[argc - 1] for the function arguments. argv[argc]
* should have type VAR_UNKNOWN.
* Returns OK or FAIL.
*/
int
call_vim_function(
char_u *func,
int argc,
typval_T *argv,
typval_T *rettv)
{
int ret;
funcexe_T funcexe;
rettv->v_type = VAR_UNKNOWN; // clear_tv() uses this
CLEAR_FIELD(funcexe);
funcexe.firstline = curwin->w_cursor.lnum;
funcexe.lastline = curwin->w_cursor.lnum;
funcexe.evaluate = TRUE;
ret = call_func(func, -1, rettv, argc, argv, &funcexe);
if (ret == FAIL)
clear_tv(rettv);
return ret;
}
/*
* Call Vim script function "func" and return the result as a number.
* Returns -1 when calling the function fails.
* Uses argv[0] to argv[argc - 1] for the function arguments. argv[argc] should
* have type VAR_UNKNOWN.
*/
varnumber_T
call_func_retnr(
char_u *func,
int argc,
typval_T *argv)
{
typval_T rettv;
varnumber_T retval;
if (call_vim_function(func, argc, argv, &rettv) == FAIL)
return -1;
retval = tv_get_number_chk(&rettv, NULL);
clear_tv(&rettv);
return retval;
}
/*
* Call Vim script function like call_func_retnr() and drop the result.
* Returns FAIL when calling the function fails.
*/
int
call_func_noret(
char_u *func,
int argc,
typval_T *argv)
{
typval_T rettv;
if (call_vim_function(func, argc, argv, &rettv) == FAIL)
return FAIL;
clear_tv(&rettv);
return OK;
}
/*
* Call Vim script function "func" and return the result as a string.
* Uses "argv" and "argc" as call_func_retnr().
* Returns NULL when calling the function fails.
*/
void *
call_func_retstr(
char_u *func,
int argc,
typval_T *argv)
{
typval_T rettv;
char_u *retval;
if (call_vim_function(func, argc, argv, &rettv) == FAIL)
return NULL;
retval = vim_strsave(tv_get_string(&rettv));
clear_tv(&rettv);
return retval;
}
/*
* Call Vim script function "func" and return the result as a List.
* Uses "argv" and "argc" as call_func_retnr().
* Returns NULL when there is something wrong.
*/
void *
call_func_retlist(
char_u *func,
int argc,
typval_T *argv)
{
typval_T rettv;
if (call_vim_function(func, argc, argv, &rettv) == FAIL)
return NULL;
if (rettv.v_type != VAR_LIST)
{
clear_tv(&rettv);
return NULL;
}
return rettv.vval.v_list;
}
#ifdef FEAT_FOLDING
/*
* Evaluate "arg", which is 'foldexpr'.
* Note: caller must set "curwin" to match "arg".
* Returns the foldlevel, and any character preceding it in "*cp". Doesn't
* give error messages.
*/
int
eval_foldexpr(char_u *arg, int *cp)
{
typval_T tv;
varnumber_T retval;
char_u *s;
int use_sandbox = was_set_insecurely((char_u *)"foldexpr",
OPT_LOCAL);
++emsg_off;
if (use_sandbox)
++sandbox;
++textwinlock;
*cp = NUL;
if (eval0(arg, &tv, NULL, &EVALARG_EVALUATE) == FAIL)
retval = 0;
else
{
// If the result is a number, just return the number.
if (tv.v_type == VAR_NUMBER)
retval = tv.vval.v_number;
else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)
retval = 0;
else
{
// If the result is a string, check if there is a non-digit before
// the number.
s = tv.vval.v_string;
if (!VIM_ISDIGIT(*s) && *s != '-')
*cp = *s++;
retval = atol((char *)s);
}
clear_tv(&tv);
}
--emsg_off;
if (use_sandbox)
--sandbox;
--textwinlock;
clear_evalarg(&EVALARG_EVALUATE, NULL);
return (int)retval;
}
#endif
/*
* Get an lval: variable, Dict item or List item that can be assigned a value
* to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]",
* "name.key", "name.key[expr]" etc.
* Indexing only works if "name" is an existing List or Dictionary.
* "name" points to the start of the name.
* If "rettv" is not NULL it points to the value to be assigned.
* "unlet" is TRUE for ":unlet": slightly different behavior when something is
* wrong; must end in space or cmd separator.
*
* flags:
* GLV_QUIET: do not give error messages
* GLV_READ_ONLY: will not change the variable
* GLV_NO_AUTOLOAD: do not use script autoloading
*
* Returns a pointer to just after the name, including indexes.
* When an evaluation error occurs "lp->ll_name" is NULL;
* Returns NULL for a parsing error. Still need to free items in "lp"!
*/
char_u *
get_lval(
char_u *name,
typval_T *rettv,
lval_T *lp,
int unlet,
int skip,
int flags, // GLV_ values
int fne_flags) // flags for find_name_end()
{
char_u *p;
char_u *expr_start, *expr_end;
int cc;
dictitem_T *v;
typval_T var1;
typval_T var2;
int empty1 = FALSE;
listitem_T *ni;
char_u *key = NULL;
int len;
hashtab_T *ht = NULL;
int quiet = flags & GLV_QUIET;
int writing;
// Clear everything in "lp".
CLEAR_POINTER(lp);
if (skip || (flags & GLV_COMPILING))
{
// When skipping or compiling just find the end of the name.
lp->ll_name = name;
lp->ll_name_end = find_name_end(name, NULL, NULL,
FNE_INCL_BR | fne_flags);
return lp->ll_name_end;
}
// Find the end of the name.
p = find_name_end(name, &expr_start, &expr_end, fne_flags);
lp->ll_name_end = p;
if (expr_start != NULL)
{
// Don't expand the name when we already know there is an error.
if (unlet && !VIM_ISWHITE(*p) && !ends_excmd(*p)
&& *p != '[' && *p != '.')
{
semsg(_(e_trailing_arg), p);
return NULL;
}
lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
if (lp->ll_exp_name == NULL)
{
// Report an invalid expression in braces, unless the
// expression evaluation has been cancelled due to an
// aborting error, an interrupt, or an exception.
if (!aborting() && !quiet)
{
emsg_severe = TRUE;
semsg(_(e_invarg2), name);
return NULL;
}
}
lp->ll_name = lp->ll_exp_name;
}
else
{
lp->ll_name = name;
if (in_vim9script())
{
// "a: type" is declaring variable "a" with a type, not "a:".
if (p == name + 2 && p[-1] == ':')
{
--p;
lp->ll_name_end = p;
}
if (*p == ':')
{
scriptitem_T *si = SCRIPT_ITEM(current_sctx.sc_sid);
char_u *tp = skipwhite(p + 1);
// parse the type after the name
lp->ll_type = parse_type(&tp, &si->sn_type_list, !quiet);
if (lp->ll_type == NULL && !quiet)
return NULL;
lp->ll_name_end = tp;
}
}
}
// Without [idx] or .key we are done.
if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
return p;
cc = *p;
*p = NUL;
// When we would write to the variable pass &ht and prevent autoload.
writing = !(flags & GLV_READ_ONLY);
v = find_var(lp->ll_name, writing ? &ht : NULL,
(flags & GLV_NO_AUTOLOAD) || writing);
if (v == NULL && !quiet)
semsg(_(e_undefined_variable_str), lp->ll_name);
*p = cc;
if (v == NULL)
return NULL;
if (in_vim9script() && (flags & GLV_NO_DECL) == 0)
{
if (!quiet)
semsg(_(e_variable_already_declared), lp->ll_name);
return NULL;
}
/*
* Loop until no more [idx] or .key is following.
*/
lp->ll_tv = &v->di_tv;
var1.v_type = VAR_UNKNOWN;
var2.v_type = VAR_UNKNOWN;
while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT))
{
if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
&& !(lp->ll_tv->v_type == VAR_DICT)
&& !(lp->ll_tv->v_type == VAR_BLOB
&& lp->ll_tv->vval.v_blob != NULL))
{
if (!quiet)
emsg(_("E689: Can only index a List, Dictionary or Blob"));
return NULL;
}
if (lp->ll_range)
{
if (!quiet)
emsg(_("E708: [:] must come last"));
return NULL;
}
if (in_vim9script() && lp->ll_valtype == NULL
&& lp->ll_tv == &v->di_tv
&& ht != NULL && ht == get_script_local_ht())
{
svar_T *sv = find_typval_in_script(lp->ll_tv);
// Vim9 script local variable: get the type
if (sv != NULL)
lp->ll_valtype = sv->sv_type;
}
len = -1;
if (*p == '.')
{
key = p + 1;
for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
;
if (len == 0)
{
if (!quiet)
emsg(_(e_emptykey));
return NULL;
}
p = key + len;
}
else
{
// Get the index [expr] or the first index [expr: ].
p = skipwhite(p + 1);
if (*p == ':')
empty1 = TRUE;
else
{
empty1 = FALSE;
if (eval1(&p, &var1, &EVALARG_EVALUATE) == FAIL) // recursive!
return NULL;
if (tv_get_string_chk(&var1) == NULL)
{
// not a number or string
clear_tv(&var1);
return NULL;
}
p = skipwhite(p);
}
// Optionally get the second index [ :expr].
if (*p == ':')
{
if (lp->ll_tv->v_type == VAR_DICT)
{
if (!quiet)
emsg(_(e_cannot_slice_dictionary));
clear_tv(&var1);
return NULL;
}
if (rettv != NULL
&& !(rettv->v_type == VAR_LIST
&& rettv->vval.v_list != NULL)
&& !(rettv->v_type == VAR_BLOB
&& rettv->vval.v_blob != NULL))
{
if (!quiet)
emsg(_("E709: [:] requires a List or Blob value"));
clear_tv(&var1);
return NULL;
}
p = skipwhite(p + 1);
if (*p == ']')
lp->ll_empty2 = TRUE;
else
{
lp->ll_empty2 = FALSE;
// recursive!
if (eval1(&p, &var2, &EVALARG_EVALUATE) == FAIL)
{
clear_tv(&var1);
return NULL;
}
if (tv_get_string_chk(&var2) == NULL)
{
// not a number or string
clear_tv(&var1);
clear_tv(&var2);
return NULL;
}
}
lp->ll_range = TRUE;
}
else
lp->ll_range = FALSE;
if (*p != ']')
{
if (!quiet)
emsg(_(e_missbrac));
clear_tv(&var1);
clear_tv(&var2);
return NULL;
}
// Skip to past ']'.
++p;
}
if (lp->ll_tv->v_type == VAR_DICT)
{
if (len == -1)
{
// "[key]": get key from "var1"
key = tv_get_string_chk(&var1); // is number or string
if (key == NULL)
{
clear_tv(&var1);
return NULL;
}
}
lp->ll_list = NULL;
// a NULL dict is equivalent with an empty dict
if (lp->ll_tv->vval.v_dict == NULL)
{
lp->ll_tv->vval.v_dict = dict_alloc();
if (lp->ll_tv->vval.v_dict == NULL)
{
clear_tv(&var1);
return NULL;
}
++lp->ll_tv->vval.v_dict->dv_refcount;
}
lp->ll_dict = lp->ll_tv->vval.v_dict;
lp->ll_di = dict_find(lp->ll_dict, key, len);
// When assigning to a scope dictionary check that a function and
// variable name is valid (only variable name unless it is l: or
// g: dictionary). Disallow overwriting a builtin function.
if (rettv != NULL && lp->ll_dict->dv_scope != 0)
{
int prevval;
int wrong;
if (len != -1)
{
prevval = key[len];
key[len] = NUL;
}
else
prevval = 0; // avoid compiler warning
wrong = (lp->ll_dict->dv_scope == VAR_DEF_SCOPE
&& rettv->v_type == VAR_FUNC
&& var_wrong_func_name(key, lp->ll_di == NULL))
|| !valid_varname(key, TRUE);
if (len != -1)
key[len] = prevval;
if (wrong)
{
clear_tv(&var1);
return NULL;
}
}
if (lp->ll_valtype != NULL)
// use the type of the member
lp->ll_valtype = lp->ll_valtype->tt_member;
if (lp->ll_di == NULL)
{
// Can't add "v:" or "a:" variable.
if (lp->ll_dict == get_vimvar_dict()
|| &lp->ll_dict->dv_hashtab == get_funccal_args_ht())
{
semsg(_(e_illvar), name);
clear_tv(&var1);
return NULL;
}
// Key does not exist in dict: may need to add it.
if (*p == '[' || *p == '.' || unlet)
{
if (!quiet)
semsg(_(e_dictkey), key);
clear_tv(&var1);
return NULL;
}
if (len == -1)
lp->ll_newkey = vim_strsave(key);
else
lp->ll_newkey = vim_strnsave(key, len);
clear_tv(&var1);
if (lp->ll_newkey == NULL)
p = NULL;
break;
}
// existing variable, need to check if it can be changed
else if ((flags & GLV_READ_ONLY) == 0
&& (var_check_ro(lp->ll_di->di_flags, name, FALSE)
|| var_check_lock(lp->ll_di->di_flags, name, FALSE)))
{
clear_tv(&var1);
return NULL;
}
clear_tv(&var1);
lp->ll_tv = &lp->ll_di->di_tv;
}
else if (lp->ll_tv->v_type == VAR_BLOB)
{
long bloblen = blob_len(lp->ll_tv->vval.v_blob);
/*
* Get the number and item for the only or first index of the List.
*/
if (empty1)
lp->ll_n1 = 0;
else
// is number or string
lp->ll_n1 = (long)tv_get_number(&var1);
clear_tv(&var1);
if (lp->ll_n1 < 0
|| lp->ll_n1 > bloblen
|| (lp->ll_range && lp->ll_n1 == bloblen))
{
if (!quiet)
semsg(_(e_blobidx), lp->ll_n1);
clear_tv(&var2);
return NULL;
}
if (lp->ll_range && !lp->ll_empty2)
{
lp->ll_n2 = (long)tv_get_number(&var2);
clear_tv(&var2);
if (lp->ll_n2 < 0
|| lp->ll_n2 >= bloblen
|| lp->ll_n2 < lp->ll_n1)
{
if (!quiet)
semsg(_(e_blobidx), lp->ll_n2);
return NULL;
}
}
lp->ll_blob = lp->ll_tv->vval.v_blob;
lp->ll_tv = NULL;
break;
}
else
{
/*
* Get the number and item for the only or first index of the List.
*/
if (empty1)
lp->ll_n1 = 0;
else
// is number or string
lp->ll_n1 = (long)tv_get_number(&var1);
clear_tv(&var1);
lp->ll_dict = NULL;
lp->ll_list = lp->ll_tv->vval.v_list;
lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
if (lp->ll_li == NULL)
{
if (lp->ll_n1 < 0)
{
lp->ll_n1 = 0;
lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
}
}
if (lp->ll_li == NULL)
{
clear_tv(&var2);
if (!quiet)
semsg(_(e_listidx), lp->ll_n1);
return NULL;
}
if (lp->ll_valtype != NULL)
// use the type of the member
lp->ll_valtype = lp->ll_valtype->tt_member;
/*
* May need to find the item or absolute index for the second
* index of a range.
* When no index given: "lp->ll_empty2" is TRUE.
* Otherwise "lp->ll_n2" is set to the second index.
*/
if (lp->ll_range && !lp->ll_empty2)
{
lp->ll_n2 = (long)tv_get_number(&var2);
// is number or string
clear_tv(&var2);
if (lp->ll_n2 < 0)
{
ni = list_find(lp->ll_list, lp->ll_n2);
if (ni == NULL)
{
if (!quiet)
semsg(_(e_listidx), lp->ll_n2);
return NULL;
}
lp->ll_n2 = list_idx_of_item(lp->ll_list, ni);
}
// Check that lp->ll_n2 isn't before lp->ll_n1.
if (lp->ll_n1 < 0)
lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li);
if (lp->ll_n2 < lp->ll_n1)
{
if (!quiet)
semsg(_(e_listidx), lp->ll_n2);
return NULL;
}
}
lp->ll_tv = &lp->ll_li->li_tv;
}
}
clear_tv(&var1);
lp->ll_name_end = p;
return p;
}
/*
* Clear lval "lp" that was filled by get_lval().
*/
void
clear_lval(lval_T *lp)
{
vim_free(lp->ll_exp_name);
vim_free(lp->ll_newkey);
}
/*
* Set a variable that was parsed by get_lval() to "rettv".
* "endp" points to just after the parsed name.
* "op" is NULL, "+" for "+=", "-" for "-=", "*" for "*=", "/" for "/=",
* "%" for "%=", "." for ".=" or "=" for "=".
*/
void
set_var_lval(
lval_T *lp,
char_u *endp,
typval_T *rettv,
int copy,
int flags, // ASSIGN_CONST, ASSIGN_NO_DECL
char_u *op)
{
int cc;
listitem_T *ri;
dictitem_T *di;
if (lp->ll_tv == NULL)
{
cc = *endp;
*endp = NUL;
if (lp->ll_blob != NULL)
{
int error = FALSE, val;
if (op != NULL && *op != '=')
{
semsg(_(e_letwrong), op);
return;
}
if (value_check_lock(lp->ll_blob->bv_lock, lp->ll_name, FALSE))
return;
if (lp->ll_range && rettv->v_type == VAR_BLOB)
{
int il, ir;
if (lp->ll_empty2)
lp->ll_n2 = blob_len(lp->ll_blob) - 1;
if (lp->ll_n2 - lp->ll_n1 + 1 != blob_len(rettv->vval.v_blob))
{
emsg(_("E972: Blob value does not have the right number of bytes"));
return;
}
if (lp->ll_empty2)
lp->ll_n2 = blob_len(lp->ll_blob);
ir = 0;
for (il = lp->ll_n1; il <= lp->ll_n2; il++)
blob_set(lp->ll_blob, il,
blob_get(rettv->vval.v_blob, ir++));
}
else
{
val = (int)tv_get_number_chk(rettv, &error);
if (!error)
{
garray_T *gap = &lp->ll_blob->bv_ga;
// Allow for appending a byte. Setting a byte beyond
// the end is an error otherwise.
if (lp->ll_n1 < gap->ga_len
|| (lp->ll_n1 == gap->ga_len
&& ga_grow(&lp->ll_blob->bv_ga, 1) == OK))
{
blob_set(lp->ll_blob, lp->ll_n1, val);
if (lp->ll_n1 == gap->ga_len)
++gap->ga_len;
}
// error for invalid range was already given in get_lval()
}
}
}
else if (op != NULL && *op != '=')
{
typval_T tv;
if (flags & (ASSIGN_CONST | ASSIGN_FINAL))
{
emsg(_(e_cannot_mod));
*endp = cc;
return;
}
// handle +=, -=, *=, /=, %= and .=
di = NULL;
if (eval_variable(lp->ll_name, (int)STRLEN(lp->ll_name),
&tv, &di, TRUE, FALSE) == OK)
{
if ((di == NULL
|| (!var_check_ro(di->di_flags, lp->ll_name, FALSE)
&& !tv_check_lock(&di->di_tv, lp->ll_name, FALSE)))
&& tv_op(&tv, rettv, op) == OK)
set_var(lp->ll_name, &tv, FALSE);
clear_tv(&tv);
}
}
else
{
if (lp->ll_type != NULL
&& check_typval_type(lp->ll_type, rettv, 0) == FAIL)
return;
set_var_const(lp->ll_name, lp->ll_type, rettv, copy, flags);
}
*endp = cc;
}
else if (value_check_lock(lp->ll_newkey == NULL
? lp->ll_tv->v_lock
: lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name, FALSE))
;
else if (lp->ll_range)
{
listitem_T *ll_li = lp->ll_li;
int ll_n1 = lp->ll_n1;
if (flags & (ASSIGN_CONST | ASSIGN_FINAL))
{
emsg(_("E996: Cannot lock a range"));
return;
}
/*
* Check whether any of the list items is locked
*/
for (ri = rettv->vval.v_list->lv_first; ri != NULL && ll_li != NULL; )
{
if (value_check_lock(ll_li->li_tv.v_lock, lp->ll_name, FALSE))
return;
ri = ri->li_next;
if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == ll_n1))
break;
ll_li = ll_li->li_next;
++ll_n1;
}
/*
* Assign the List values to the list items.
*/
for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
{
if (op != NULL && *op != '=')
tv_op(&lp->ll_li->li_tv, &ri->li_tv, op);
else
{
clear_tv(&lp->ll_li->li_tv);
copy_tv(&ri->li_tv, &lp->ll_li->li_tv);
}
ri = ri->li_next;
if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1))
break;
if (lp->ll_li->li_next == NULL)
{
// Need to add an empty item.
if (list_append_number(lp->ll_list, 0) == FAIL)
{
ri = NULL;
break;
}
}
lp->ll_li = lp->ll_li->li_next;
++lp->ll_n1;
}
if (ri != NULL)
emsg(_(e_list_value_has_more_items_than_targets));
else if (lp->ll_empty2
? (lp->ll_li != NULL && lp->ll_li->li_next != NULL)
: lp->ll_n1 != lp->ll_n2)
emsg(_(e_list_value_does_not_have_enough_items));
}
else
{
/*
* Assign to a List or Dictionary item.
*/
if (flags & (ASSIGN_CONST | ASSIGN_FINAL))
{
emsg(_("E996: Cannot lock a list or dict"));
return;
}
if (lp->ll_valtype != NULL
&& check_typval_type(lp->ll_valtype, rettv, 0) == FAIL)
return;
if (lp->ll_newkey != NULL)
{
if (op != NULL && *op != '=')
{
semsg(_(e_letwrong), op);
return;
}
// Need to add an item to the Dictionary.
di = dictitem_alloc(lp->ll_newkey);
if (di == NULL)
return;
if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)
{
vim_free(di);
return;
}
lp->ll_tv = &di->di_tv;
}
else if (op != NULL && *op != '=')
{
tv_op(lp->ll_tv, rettv, op);
return;
}
else
clear_tv(lp->ll_tv);
/*
* Assign the value to the variable or list item.
*/
if (copy)
copy_tv(rettv, lp->ll_tv);
else
{
*lp->ll_tv = *rettv;
lp->ll_tv->v_lock = 0;
init_tv(rettv);
}
}
}
/*
* Handle "tv1 += tv2", "tv1 -= tv2", "tv1 *= tv2", "tv1 /= tv2", "tv1 %= tv2"
* and "tv1 .= tv2"
* Returns OK or FAIL.
*/
static int
tv_op(typval_T *tv1, typval_T *tv2, char_u *op)
{
varnumber_T n;
char_u numbuf[NUMBUFLEN];
char_u *s;
int failed = FALSE;
// Can't do anything with a Funcref, Dict, v:true on the right.
if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT
&& tv2->v_type != VAR_BOOL && tv2->v_type != VAR_SPECIAL)
{
switch (tv1->v_type)
{
case VAR_UNKNOWN:
case VAR_ANY:
case VAR_VOID:
case VAR_DICT:
case VAR_FUNC:
case VAR_PARTIAL:
case VAR_BOOL:
case VAR_SPECIAL:
case VAR_JOB:
case VAR_CHANNEL:
break;
case VAR_BLOB:
if (*op != '+' || tv2->v_type != VAR_BLOB)
break;
// BLOB += BLOB
if (tv1->vval.v_blob != NULL && tv2->vval.v_blob != NULL)
{
blob_T *b1 = tv1->vval.v_blob;
blob_T *b2 = tv2->vval.v_blob;
int i, len = blob_len(b2);
for (i = 0; i < len; i++)
ga_append(&b1->bv_ga, blob_get(b2, i));
}
return OK;
case VAR_LIST:
if (*op != '+' || tv2->v_type != VAR_LIST)
break;
// List += List
if (tv2->vval.v_list != NULL)
{
if (tv1->vval.v_list == NULL)
{
tv1->vval.v_list = tv2->vval.v_list;
++tv1->vval.v_list->lv_refcount;
}
else
list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);
}
return OK;
case VAR_NUMBER:
case VAR_STRING:
if (tv2->v_type == VAR_LIST)
break;
if (vim_strchr((char_u *)"+-*/%", *op) != NULL)
{
// nr += nr , nr -= nr , nr *=nr , nr /= nr , nr %= nr
n = tv_get_number(tv1);
#ifdef FEAT_FLOAT
if (tv2->v_type == VAR_FLOAT)
{
float_T f = n;
if (*op == '%')
break;
switch (*op)
{
case '+': f += tv2->vval.v_float; break;
case '-': f -= tv2->vval.v_float; break;
case '*': f *= tv2->vval.v_float; break;
case '/': f /= tv2->vval.v_float; break;
}
clear_tv(tv1);
tv1->v_type = VAR_FLOAT;
tv1->vval.v_float = f;
}
else
#endif
{
switch (*op)
{
case '+': n += tv_get_number(tv2); break;
case '-': n -= tv_get_number(tv2); break;
case '*': n *= tv_get_number(tv2); break;
case '/': n = num_divide(n, tv_get_number(tv2),
&failed); break;
case '%': n = num_modulus(n, tv_get_number(tv2),
&failed); break;
}
clear_tv(tv1);
tv1->v_type = VAR_NUMBER;
tv1->vval.v_number = n;
}
}
else
{
if (tv2->v_type == VAR_FLOAT)
break;
// str .= str
s = tv_get_string(tv1);
s = concat_str(s, tv_get_string_buf(tv2, numbuf));
clear_tv(tv1);
tv1->v_type = VAR_STRING;
tv1->vval.v_string = s;
}
return failed ? FAIL : OK;
case VAR_FLOAT:
#ifdef FEAT_FLOAT
{
float_T f;
if (*op == '%' || *op == '.'
|| (tv2->v_type != VAR_FLOAT
&& tv2->v_type != VAR_NUMBER
&& tv2->v_type != VAR_STRING))
break;
if (tv2->v_type == VAR_FLOAT)
f = tv2->vval.v_float;
else
f = tv_get_number(tv2);
switch (*op)
{
case '+': tv1->vval.v_float += f; break;
case '-': tv1->vval.v_float -= f; break;
case '*': tv1->vval.v_float *= f; break;
case '/': tv1->vval.v_float /= f; break;
}
}
#endif
return OK;
}
}
semsg(_(e_letwrong), op);
return FAIL;
}
/*
* Evaluate the expression used in a ":for var in expr" command.
* "arg" points to "var".
* Set "*errp" to TRUE for an error, FALSE otherwise;
* Return a pointer that holds the info. Null when there is an error.
*/
void *
eval_for_line(
char_u *arg,
int *errp,
exarg_T *eap,
evalarg_T *evalarg)
{
forinfo_T *fi;
char_u *expr;
typval_T tv;
list_T *l;
int skip = !(evalarg->eval_flags & EVAL_EVALUATE);
*errp = TRUE; // default: there is an error
fi = ALLOC_CLEAR_ONE(forinfo_T);
if (fi == NULL)
return NULL;
expr = skip_var_list(arg, TRUE, &fi->fi_varcount, &fi->fi_semicolon, FALSE);
if (expr == NULL)
return fi;
expr = skipwhite_and_linebreak(expr, evalarg);
if (expr[0] != 'i' || expr[1] != 'n'
|| !(expr[2] == NUL || VIM_ISWHITE(expr[2])))
{
emsg(_(e_missing_in));
return fi;
}
if (skip)
++emsg_skip;
expr = skipwhite_and_linebreak(expr + 2, evalarg);
if (eval0(expr, &tv, eap, evalarg) == OK)
{
*errp = FALSE;
if (!skip)
{
if (tv.v_type == VAR_LIST)
{
l = tv.vval.v_list;
if (l == NULL)
{
// a null list is like an empty list: do nothing
clear_tv(&tv);
}
else
{
// Need a real list here.
CHECK_LIST_MATERIALIZE(l);
// No need to increment the refcount, it's already set for
// the list being used in "tv".
fi->fi_list = l;
list_add_watch(l, &fi->fi_lw);
fi->fi_lw.lw_item = l->lv_first;
}
}
else if (tv.v_type == VAR_BLOB)
{
fi->fi_bi = 0;
if (tv.vval.v_blob != NULL)
{
typval_T btv;
// Make a copy, so that the iteration still works when the
// blob is changed.
blob_copy(tv.vval.v_blob, &btv);
fi->fi_blob = btv.vval.v_blob;
}
clear_tv(&tv);
}
else
{
emsg(_(e_listreq));
clear_tv(&tv);
}
}
}
if (skip)
--emsg_skip;
fi->fi_break_count = evalarg->eval_break_count;
return fi;
}
/*
* Used when looping over a :for line, skip the "in expr" part.
*/
void
skip_for_lines(void *fi_void, evalarg_T *evalarg)
{
forinfo_T *fi = (forinfo_T *)fi_void;
int i;
for (i = 0; i < fi->fi_break_count; ++i)
eval_next_line(evalarg);
}
/*
* Use the first item in a ":for" list. Advance to the next.
* Assign the values to the variable (list). "arg" points to the first one.
* Return TRUE when a valid item was found, FALSE when at end of list or
* something wrong.
*/
int
next_for_item(void *fi_void, char_u *arg)
{
forinfo_T *fi = (forinfo_T *)fi_void;
int result;
int flag = in_vim9script() ? ASSIGN_DECL : 0;
listitem_T *item;
if (fi->fi_blob != NULL)
{
typval_T tv;
if (fi->fi_bi >= blob_len(fi->fi_blob))
return FALSE;
tv.v_type = VAR_NUMBER;
tv.v_lock = VAR_FIXED;
tv.vval.v_number = blob_get(fi->fi_blob, fi->fi_bi);
++fi->fi_bi;
return ex_let_vars(arg, &tv, TRUE, fi->fi_semicolon,
fi->fi_varcount, flag, NULL) == OK;
}
item = fi->fi_lw.lw_item;
if (item == NULL)
result = FALSE;
else
{
fi->fi_lw.lw_item = item->li_next;
result = (ex_let_vars(arg, &item->li_tv, TRUE, fi->fi_semicolon,
fi->fi_varcount, flag, NULL) == OK);
}
return result;
}
/*
* Free the structure used to store info used by ":for".
*/
void
free_for_info(void *fi_void)
{
forinfo_T *fi = (forinfo_T *)fi_void;
if (fi != NULL && fi->fi_list != NULL)
{
list_rem_watch(fi->fi_list, &fi->fi_lw);
list_unref(fi->fi_list);
}
if (fi != NULL && fi->fi_blob != NULL)
blob_unref(fi->fi_blob);
vim_free(fi);
}
void
set_context_for_expression(
expand_T *xp,
char_u *arg,
cmdidx_T cmdidx)
{
int has_expr = cmdidx != CMD_let && cmdidx != CMD_var;
int c;
char_u *p;
if (cmdidx == CMD_let || cmdidx == CMD_var
|| cmdidx == CMD_const || cmdidx == CMD_final)
{
xp->xp_context = EXPAND_USER_VARS;
if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL)
{
// ":let var1 var2 ...": find last space.
for (p = arg + STRLEN(arg); p >= arg; )
{
xp->xp_pattern = p;
MB_PTR_BACK(arg, p);
if (VIM_ISWHITE(*p))
break;
}
return;
}
}
else
xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS
: EXPAND_EXPRESSION;
while ((xp->xp_pattern = vim_strpbrk(arg,
(char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL)
{
c = *xp->xp_pattern;
if (c == '&')
{
c = xp->xp_pattern[1];
if (c == '&')
{
++xp->xp_pattern;
xp->xp_context = has_expr ? EXPAND_EXPRESSION : EXPAND_NOTHING;
}
else if (c != ' ')
{
xp->xp_context = EXPAND_SETTINGS;
if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')
xp->xp_pattern += 2;
}
}
else if (c == '$')
{
// environment variable
xp->xp_context = EXPAND_ENV_VARS;
}
else if (c == '=')
{
has_expr = TRUE;
xp->xp_context = EXPAND_EXPRESSION;
}
else if (c == '#'
&& xp->xp_context == EXPAND_EXPRESSION)
{
// Autoload function/variable contains '#'.
break;
}
else if ((c == '<' || c == '#')
&& xp->xp_context == EXPAND_FUNCTIONS
&& vim_strchr(xp->xp_pattern, '(') == NULL)
{
// Function name can start with "<SNR>" and contain '#'.
break;
}
else if (has_expr)
{
if (c == '"') // string
{
while ((c = *++xp->xp_pattern) != NUL && c != '"')
if (c == '\\' && xp->xp_pattern[1] != NUL)
++xp->xp_pattern;
xp->xp_context = EXPAND_NOTHING;
}
else if (c == '\'') // literal string
{
// Trick: '' is like stopping and starting a literal string.
while ((c = *++xp->xp_pattern) != NUL && c != '\'')
/* skip */ ;
xp->xp_context = EXPAND_NOTHING;
}
else if (c == '|')
{
if (xp->xp_pattern[1] == '|')
{
++xp->xp_pattern;
xp->xp_context = EXPAND_EXPRESSION;
}
else
xp->xp_context = EXPAND_COMMANDS;
}
else
xp->xp_context = EXPAND_EXPRESSION;
}
else
// Doesn't look like something valid, expand as an expression
// anyway.
xp->xp_context = EXPAND_EXPRESSION;
arg = xp->xp_pattern;
if (*arg != NUL)
while ((c = *++arg) != NUL && (c == ' ' || c == '\t'))
/* skip */ ;
}
// ":exe one two" completes "two"
if ((cmdidx == CMD_execute
|| cmdidx == CMD_echo
|| cmdidx == CMD_echon
|| cmdidx == CMD_echomsg)
&& xp->xp_context == EXPAND_EXPRESSION)
{
for (;;)
{
char_u *n = skiptowhite(arg);
if (n == arg || IS_WHITE_OR_NUL(*skipwhite(n)))
break;
arg = skipwhite(n);
}
}
xp->xp_pattern = arg;
}
/*
* Return TRUE if "pat" matches "text".
* Does not use 'cpo' and always uses 'magic'.
*/
int
pattern_match(char_u *pat, char_u *text, int ic)
{
int matches = FALSE;
char_u *save_cpo;
regmatch_T regmatch;
// avoid 'l' flag in 'cpoptions'
save_cpo = p_cpo;
p_cpo = empty_option;
regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
if (regmatch.regprog != NULL)
{
regmatch.rm_ic = ic;
matches = vim_regexec_nl(®match, text, (colnr_T)0);
vim_regfree(regmatch.regprog);
}
p_cpo = save_cpo;
return matches;
}
/*
* Handle a name followed by "(". Both for just "name(arg)" and for
* "expr->name(arg)".
* Returns OK or FAIL.
*/
static int
eval_func(
char_u **arg, // points to "(", will be advanced
evalarg_T *evalarg,
char_u *name,
int name_len,
typval_T *rettv,
int flags,
typval_T *basetv) // "expr" for "expr->name(arg)"
{
int evaluate = flags & EVAL_EVALUATE;
char_u *s = name;
int len = name_len;
partial_T *partial;
int ret = OK;
type_T *type = NULL;
if (!evaluate)
check_vars(s, len);
// If "s" is the name of a variable of type VAR_FUNC
// use its contents.
s = deref_func_name(s, &len, &partial,
in_vim9script() ? &type : NULL, !evaluate);
// Need to make a copy, in case evaluating the arguments makes
// the name invalid.
s = vim_strsave(s);
if (s == NULL || (flags & EVAL_CONSTANT))
ret = FAIL;
else
{
funcexe_T funcexe;
// Invoke the function.
CLEAR_FIELD(funcexe);
funcexe.firstline = curwin->w_cursor.lnum;
funcexe.lastline = curwin->w_cursor.lnum;
funcexe.evaluate = evaluate;
funcexe.partial = partial;
funcexe.basetv = basetv;
funcexe.check_type = type;
ret = get_func_tv(s, len, rettv, arg, evalarg, &funcexe);
}
vim_free(s);
// If evaluate is FALSE rettv->v_type was not set in
// get_func_tv, but it's needed in handle_subscript() to parse
// what follows. So set it here.
if (rettv->v_type == VAR_UNKNOWN && !evaluate && **arg == '(')
{
rettv->vval.v_string = NULL;
rettv->v_type = VAR_FUNC;
}
// Stop the expression evaluation when immediately
// aborting on error, or when an interrupt occurred or
// an exception was thrown but not caught.
if (evaluate && aborting())
{
if (ret == OK)
clear_tv(rettv);
ret = FAIL;
}
return ret;
}
/*
* Get the next line source line without advancing. But do skip over comment
* lines.
*/
static char_u *
getline_peek_skip_comments(evalarg_T *evalarg)
{
for (;;)
{
char_u *next = getline_peek(evalarg->eval_getline,
evalarg->eval_cookie);
char_u *p;
if (next == NULL)
break;
p = skipwhite(next);
if (*p != NUL && !vim9_comment_start(p))
return next;
(void)eval_next_line(evalarg);
}
return NULL;
}
/*
* If inside Vim9 script, "arg" points to the end of a line (ignoring a #
* comment) and there is a next line, return the next line (skipping blanks)
* and set "getnext".
* Otherwise just return "arg" unmodified and set "getnext" to FALSE.
* "arg" must point somewhere inside a line, not at the start.
*/
char_u *
eval_next_non_blank(char_u *arg, evalarg_T *evalarg, int *getnext)
{
char_u *p = skipwhite(arg);
*getnext = FALSE;
if (in_vim9script()
&& evalarg != NULL
&& (evalarg->eval_cookie != NULL || evalarg->eval_cctx != NULL)
&& (*p == NUL || (VIM_ISWHITE(p[-1]) && vim9_comment_start(p))))
{
char_u *next;
if (evalarg->eval_cookie != NULL)
next = getline_peek_skip_comments(evalarg);
else
next = peek_next_line_from_context(evalarg->eval_cctx);
if (next != NULL)
{
*getnext = TRUE;
return skipwhite(next);
}
}
return p;
}
/*
* To be called after eval_next_non_blank() sets "getnext" to TRUE.
*/
char_u *
eval_next_line(evalarg_T *evalarg)
{
garray_T *gap = &evalarg->eval_ga;
char_u *line;
if (evalarg->eval_cookie != NULL)
line = evalarg->eval_getline(0, evalarg->eval_cookie, 0,
GETLINE_CONCAT_ALL);
else
line = next_line_from_context(evalarg->eval_cctx, TRUE);
++evalarg->eval_break_count;
if (gap->ga_itemsize > 0 && ga_grow(gap, 1) == OK)
{
// Going to concatenate the lines after parsing.
((char_u **)gap->ga_data)[gap->ga_len] = line;
++gap->ga_len;
}
else if (evalarg->eval_cookie != NULL)
{
vim_free(evalarg->eval_tofree);
evalarg->eval_tofree = line;
}
return skipwhite(line);
}
/*
* Call eval_next_non_blank() and get the next line if needed.
*/
char_u *
skipwhite_and_linebreak(char_u *arg, evalarg_T *evalarg)
{
int getnext;
char_u *p = skipwhite(arg);
if (evalarg == NULL)
return skipwhite(arg);
eval_next_non_blank(p, evalarg, &getnext);
if (getnext)
return eval_next_line(evalarg);
return p;
}
/*
* After using "evalarg" filled from "eap": free the memory.
*/
void
clear_evalarg(evalarg_T *evalarg, exarg_T *eap)
{
if (evalarg != NULL)
{
if (evalarg->eval_tofree != NULL)
{
if (eap != NULL)
{
// We may need to keep the original command line, e.g. for
// ":let" it has the variable names. But we may also need the
// new one, "nextcmd" points into it. Keep both.
vim_free(eap->cmdline_tofree);
eap->cmdline_tofree = *eap->cmdlinep;
*eap->cmdlinep = evalarg->eval_tofree;
}
else
vim_free(evalarg->eval_tofree);
evalarg->eval_tofree = NULL;
}
vim_free(evalarg->eval_tofree_lambda);
evalarg->eval_tofree_lambda = NULL;
}
}
/*
* The "evaluate" argument: When FALSE, the argument is only parsed but not
* executed. The function may return OK, but the rettv will be of type
* VAR_UNKNOWN. The function still returns FAIL for a syntax error.
*/
/*
* Handle zero level expression.
* This calls eval1() and handles error message and nextcmd.
* Put the result in "rettv" when returning OK and "evaluate" is TRUE.
* Note: "rettv.v_lock" is not set.
* "evalarg" can be NULL, EVALARG_EVALUATE or a pointer.
* Return OK or FAIL.
*/
int
eval0(
char_u *arg,
typval_T *rettv,
exarg_T *eap,
evalarg_T *evalarg)
{
int ret;
char_u *p;
int did_emsg_before = did_emsg;
int called_emsg_before = called_emsg;
int flags = evalarg == NULL ? 0 : evalarg->eval_flags;
p = skipwhite(arg);
ret = eval1(&p, rettv, evalarg);
p = skipwhite(p);
if (ret == FAIL || !ends_excmd2(arg, p))
{
if (ret != FAIL)
clear_tv(rettv);
/*
* Report the invalid expression unless the expression evaluation has
* been cancelled due to an aborting error, an interrupt, or an
* exception, or we already gave a more specific error.
* Also check called_emsg for when using assert_fails().
*/
if (!aborting()
&& did_emsg == did_emsg_before
&& called_emsg == called_emsg_before
&& (flags & EVAL_CONSTANT) == 0)
semsg(_(e_invexpr2), arg);
// Some of the expression may not have been consumed. Do not check for
// a next command to avoid more errors, unless "|" is following, which
// could only be a command separator.
if (eap != NULL && skipwhite(p)[0] == '|' && skipwhite(p)[1] != '|')
eap->nextcmd = check_nextcmd(p);
return FAIL;
}
if (eap != NULL)
eap->nextcmd = check_nextcmd(p);
return ret;
}
/*
* Handle top level expression:
* expr2 ? expr1 : expr1
* expr2 ?? expr1
*
* "arg" must point to the first non-white of the expression.
* "arg" is advanced to just after the recognized expression.
*
* Note: "rettv.v_lock" is not set.
*
* Return OK or FAIL.
*/
int
eval1(char_u **arg, typval_T *rettv, evalarg_T *evalarg)
{
char_u *p;
int getnext;
CLEAR_POINTER(rettv);
/*
* Get the first variable.
*/
if (eval2(arg, rettv, evalarg) == FAIL)
return FAIL;
p = eval_next_non_blank(*arg, evalarg, &getnext);
if (*p == '?')
{
int op_falsy = p[1] == '?';
int result;
typval_T var2;
evalarg_T *evalarg_used = evalarg;
evalarg_T local_evalarg;
int orig_flags;
int evaluate;
int vim9script = in_vim9script();
if (evalarg == NULL)
{
CLEAR_FIELD(local_evalarg);
evalarg_used = &local_evalarg;
}
orig_flags = evalarg_used->eval_flags;
evaluate = evalarg_used->eval_flags & EVAL_EVALUATE;
if (getnext)
*arg = eval_next_line(evalarg_used);
else
{
if (evaluate && vim9script && !VIM_ISWHITE(p[-1]))
{
error_white_both(p, 1);
clear_tv(rettv);
return FAIL;
}
*arg = p;
}
result = FALSE;
if (evaluate)
{
int error = FALSE;
if (op_falsy)
result = tv2bool(rettv);
else if (vim9script)
result = tv_get_bool_chk(rettv, &error);
else if (tv_get_number_chk(rettv, &error) != 0)
result = TRUE;
if (error || !op_falsy || !result)
clear_tv(rettv);
if (error)
return FAIL;
}
/*
* Get the second variable. Recursive!
*/
if (op_falsy)
++*arg;
if (evaluate && vim9script && !IS_WHITE_OR_NUL((*arg)[1]))
{
error_white_both(p, 1);
clear_tv(rettv);
return FAIL;
}
*arg = skipwhite_and_linebreak(*arg + 1, evalarg_used);
evalarg_used->eval_flags = (op_falsy ? !result : result)
? orig_flags : orig_flags & ~EVAL_EVALUATE;
if (eval1(arg, &var2, evalarg_used) == FAIL)
{
evalarg_used->eval_flags = orig_flags;
return FAIL;
}
if (!op_falsy || !result)
*rettv = var2;
if (!op_falsy)
{
/*
* Check for the ":".
*/
p = eval_next_non_blank(*arg, evalarg_used, &getnext);
if (*p != ':')
{
emsg(_(e_missing_colon));
if (evaluate && result)
clear_tv(rettv);
evalarg_used->eval_flags = orig_flags;
return FAIL;
}
if (getnext)
*arg = eval_next_line(evalarg_used);
else
{
if (evaluate && vim9script && !VIM_ISWHITE(p[-1]))
{
error_white_both(p, 1);
clear_tv(rettv);
evalarg_used->eval_flags = orig_flags;
return FAIL;
}
*arg = p;
}
/*
* Get the third variable. Recursive!
*/
if (evaluate && vim9script && !IS_WHITE_OR_NUL((*arg)[1]))
{
error_white_both(p, 1);
clear_tv(rettv);
evalarg_used->eval_flags = orig_flags;
return FAIL;
}
*arg = skipwhite_and_linebreak(*arg + 1, evalarg_used);
evalarg_used->eval_flags = !result ? orig_flags
: orig_flags & ~EVAL_EVALUATE;
if (eval1(arg, &var2, evalarg_used) == FAIL)
{
if (evaluate && result)
clear_tv(rettv);
evalarg_used->eval_flags = orig_flags;
return FAIL;
}
if (evaluate && !result)
*rettv = var2;
}
if (evalarg == NULL)
clear_evalarg(&local_evalarg, NULL);
else
evalarg->eval_flags = orig_flags;
}
return OK;
}
/*
* Handle first level expression:
* expr2 || expr2 || expr2 logical OR
*
* "arg" must point to the first non-white of the expression.
* "arg" is advanced to just after the recognized expression.
*
* Return OK or FAIL.
*/
static int
eval2(char_u **arg, typval_T *rettv, evalarg_T *evalarg)
{
char_u *p;
int getnext;
/*
* Get the first variable.
*/
if (eval3(arg, rettv, evalarg) == FAIL)
return FAIL;
/*
* Handle the "||" operator.
*/
p = eval_next_non_blank(*arg, evalarg, &getnext);
if (p[0] == '|' && p[1] == '|')
{
evalarg_T *evalarg_used = evalarg;
evalarg_T local_evalarg;
int evaluate;
int orig_flags;
long result = FALSE;
typval_T var2;
int error = FALSE;
int vim9script = in_vim9script();
if (evalarg == NULL)
{
CLEAR_FIELD(local_evalarg);
evalarg_used = &local_evalarg;
}
orig_flags = evalarg_used->eval_flags;
evaluate = orig_flags & EVAL_EVALUATE;
if (evaluate)
{
if (vim9script)
result = tv_get_bool_chk(rettv, &error);
else if (tv_get_number_chk(rettv, &error) != 0)
result = TRUE;
clear_tv(rettv);
if (error)
return FAIL;
}
/*
* Repeat until there is no following "||".
*/
while (p[0] == '|' && p[1] == '|')
{
if (getnext)
*arg = eval_next_line(evalarg_used);
else
{
if (evaluate && in_vim9script() && !VIM_ISWHITE(p[-1]))
{
error_white_both(p, 2);
clear_tv(rettv);
return FAIL;
}
*arg = p;
}
/*
* Get the second variable.
*/
if (evaluate && in_vim9script() && !IS_WHITE_OR_NUL((*arg)[2]))
{
error_white_both(p, 2);
clear_tv(rettv);
return FAIL;
}
*arg = skipwhite_and_linebreak(*arg + 2, evalarg_used);
evalarg_used->eval_flags = !result ? orig_flags
: orig_flags & ~EVAL_EVALUATE;
if (eval3(arg, &var2, evalarg_used) == FAIL)
return FAIL;
/*
* Compute the result.
*/
if (evaluate && !result)
{
if (vim9script)
result = tv_get_bool_chk(&var2, &error);
else if (tv_get_number_chk(&var2, &error) != 0)
result = TRUE;
clear_tv(&var2);
if (error)
return FAIL;
}
if (evaluate)
{
if (vim9script)
{
rettv->v_type = VAR_BOOL;
rettv->vval.v_number = result ? VVAL_TRUE : VVAL_FALSE;
}
else
{
rettv->v_type = VAR_NUMBER;
rettv->vval.v_number = result;
}
}
p = eval_next_non_blank(*arg, evalarg_used, &getnext);
}
if (evalarg == NULL)
clear_evalarg(&local_evalarg, NULL);
else
evalarg->eval_flags = orig_flags;
}
return OK;
}
/*
* Handle second level expression:
* expr3 && expr3 && expr3 logical AND
*
* "arg" must point to the first non-white of the expression.
* "arg" is advanced to just after the recognized expression.
*
* Return OK or FAIL.
*/
static int
eval3(char_u **arg, typval_T *rettv, evalarg_T *evalarg)
{
char_u *p;
int getnext;
/*
* Get the first variable.
*/
if (eval4(arg, rettv, evalarg) == FAIL)
return FAIL;
/*
* Handle the "&&" operator.
*/
p = eval_next_non_blank(*arg, evalarg, &getnext);
if (p[0] == '&' && p[1] == '&')
{
evalarg_T *evalarg_used = evalarg;
evalarg_T local_evalarg;
int orig_flags;
int evaluate;
long result = TRUE;
typval_T var2;
int error = FALSE;
int vim9script = in_vim9script();
if (evalarg == NULL)
{
CLEAR_FIELD(local_evalarg);
evalarg_used = &local_evalarg;
}
orig_flags = evalarg_used->eval_flags;
evaluate = orig_flags & EVAL_EVALUATE;
if (evaluate)
{
if (vim9script)
result = tv_get_bool_chk(rettv, &error);
else if (tv_get_number_chk(rettv, &error) == 0)
result = FALSE;
clear_tv(rettv);
if (error)
return FAIL;
}
/*
* Repeat until there is no following "&&".
*/
while (p[0] == '&' && p[1] == '&')
{
if (getnext)
*arg = eval_next_line(evalarg_used);
else
{
if (evaluate && vim9script && !VIM_ISWHITE(p[-1]))
{
error_white_both(p, 2);
clear_tv(rettv);
return FAIL;
}
*arg = p;
}
/*
* Get the second variable.
*/
if (evaluate && in_vim9script() && !IS_WHITE_OR_NUL((*arg)[2]))
{
error_white_both(p, 2);
clear_tv(rettv);
return FAIL;
}
*arg = skipwhite_and_linebreak(*arg + 2, evalarg_used);
evalarg_used->eval_flags = result ? orig_flags
: orig_flags & ~EVAL_EVALUATE;
CLEAR_FIELD(var2);
if (eval4(arg, &var2, evalarg_used) == FAIL)
return FAIL;
/*
* Compute the result.
*/
if (evaluate && result)
{
if (vim9script)
result = tv_get_bool_chk(&var2, &error);
else if (tv_get_number_chk(&var2, &error) == 0)
result = FALSE;
clear_tv(&var2);
if (error)
return FAIL;
}
if (evaluate)
{
if (vim9script)
{
rettv->v_type = VAR_BOOL;
rettv->vval.v_number = result ? VVAL_TRUE : VVAL_FALSE;
}
else
{
rettv->v_type = VAR_NUMBER;
rettv->vval.v_number = result;
}
}
p = eval_next_non_blank(*arg, evalarg_used, &getnext);
}
if (evalarg == NULL)
clear_evalarg(&local_evalarg, NULL);
else
evalarg->eval_flags = orig_flags;
}
return OK;
}
/*
* Handle third level expression:
* var1 == var2
* var1 =~ var2
* var1 != var2
* var1 !~ var2
* var1 > var2
* var1 >= var2
* var1 < var2
* var1 <= var2
* var1 is var2
* var1 isnot var2
*
* "arg" must point to the first non-white of the expression.
* "arg" is advanced to just after the recognized expression.
*
* Return OK or FAIL.
*/
static int
eval4(char_u **arg, typval_T *rettv, evalarg_T *evalarg)
{
char_u *p;
int getnext;
exprtype_T type = EXPR_UNKNOWN;
int len = 2;
int type_is = FALSE;
/*
* Get the first variable.
*/
if (eval5(arg, rettv, evalarg) == FAIL)
return FAIL;
p = eval_next_non_blank(*arg, evalarg, &getnext);
type = get_compare_type(p, &len, &type_is);
/*
* If there is a comparative operator, use it.
*/
if (type != EXPR_UNKNOWN)
{
typval_T var2;
int ic;
int vim9script = in_vim9script();
int evaluate = evalarg == NULL
? 0 : (evalarg->eval_flags & EVAL_EVALUATE);
if (getnext)
*arg = eval_next_line(evalarg);
else if (evaluate && vim9script && !VIM_ISWHITE(**arg))
{
error_white_both(p, len);
clear_tv(rettv);
return FAIL;
}
if (vim9script && type_is && (p[len] == '?' || p[len] == '#'))
{
semsg(_(e_invexpr2), p);
clear_tv(rettv);
return FAIL;
}
// extra question mark appended: ignore case
if (p[len] == '?')
{
ic = TRUE;
++len;
}
// extra '#' appended: match case
else if (p[len] == '#')
{
ic = FALSE;
++len;
}
// nothing appended: use 'ignorecase' if not in Vim script
else
ic = vim9script ? FALSE : p_ic;
/*
* Get the second variable.
*/
if (evaluate && vim9script && !IS_WHITE_OR_NUL(p[len]))
{
error_white_both(p, 1);
clear_tv(rettv);
return FAIL;
}
*arg = skipwhite_and_linebreak(p + len, evalarg);
if (eval5(arg, &var2, evalarg) == FAIL)
{
clear_tv(rettv);
return FAIL;
}
if (evaluate)
{
int ret;
if (vim9script && check_compare_types(type, rettv, &var2) == FAIL)
{
ret = FAIL;
clear_tv(rettv);
}
else
ret = typval_compare(rettv, &var2, type, ic);
clear_tv(&var2);
return ret;
}
}
return OK;
}
/*
* Make a copy of blob "tv1" and append blob "tv2".
*/
void
eval_addblob(typval_T *tv1, typval_T *tv2)
{
blob_T *b1 = tv1->vval.v_blob;
blob_T *b2 = tv2->vval.v_blob;
blob_T *b = blob_alloc();
int i;
if (b != NULL)
{
for (i = 0; i < blob_len(b1); i++)
ga_append(&b->bv_ga, blob_get(b1, i));
for (i = 0; i < blob_len(b2); i++)
ga_append(&b->bv_ga, blob_get(b2, i));
clear_tv(tv1);
rettv_blob_set(tv1, b);
}
}
/*
* Make a copy of list "tv1" and append list "tv2".
*/
int
eval_addlist(typval_T *tv1, typval_T *tv2)
{
typval_T var3;
// concatenate Lists
if (list_concat(tv1->vval.v_list, tv2->vval.v_list, &var3) == FAIL)
{
clear_tv(tv1);
clear_tv(tv2);
return FAIL;
}
clear_tv(tv1);
*tv1 = var3;
return OK;
}
/*
* Handle fourth level expression:
* + number addition
* - number subtraction
* . string concatenation (if script version is 1)
* .. string concatenation
*
* "arg" must point to the first non-white of the expression.
* "arg" is advanced to just after the recognized expression.
*
* Return OK or FAIL.
*/
static int
eval5(char_u **arg, typval_T *rettv, evalarg_T *evalarg)
{
/*
* Get the first variable.
*/
if (eval6(arg, rettv, evalarg, FALSE) == FAIL)
return FAIL;
/*
* Repeat computing, until no '+', '-' or '.' is following.
*/
for (;;)
{
int evaluate;
int getnext;
char_u *p;
int op;
int oplen;
int concat;
typval_T var2;
int vim9script = in_vim9script();
// "." is only string concatenation when scriptversion is 1
// "+=" and "-=" are assignment
p = eval_next_non_blank(*arg, evalarg, &getnext);
op = *p;
concat = op == '.' && (*(p + 1) == '.' || current_sctx.sc_version < 2);
if ((op != '+' && op != '-' && !concat) || p[1] == '=')
break;
evaluate = evalarg == NULL ? 0 : (evalarg->eval_flags & EVAL_EVALUATE);
oplen = (concat && p[1] == '.') ? 2 : 1;
if (getnext)
*arg = eval_next_line(evalarg);
else
{
if (evaluate && vim9script && !VIM_ISWHITE(**arg))
{
error_white_both(p, oplen);
clear_tv(rettv);
return FAIL;
}
*arg = p;
}
if ((op != '+' || (rettv->v_type != VAR_LIST
&& rettv->v_type != VAR_BLOB))
#ifdef FEAT_FLOAT
&& (op == '.' || rettv->v_type != VAR_FLOAT)
#endif
&& evaluate)
{
int error = FALSE;
// For "list + ...", an illegal use of the first operand as
// a number cannot be determined before evaluating the 2nd
// operand: if this is also a list, all is ok.
// For "something . ...", "something - ..." or "non-list + ...",
// we know that the first operand needs to be a string or number
// without evaluating the 2nd operand. So check before to avoid
// side effects after an error.
if (op != '.')
tv_get_number_chk(rettv, &error);
if ((op == '.' && tv_get_string_chk(rettv) == NULL) || error)
{
clear_tv(rettv);
return FAIL;
}
}
/*
* Get the second variable.
*/
if (evaluate && vim9script && !IS_WHITE_OR_NUL((*arg)[oplen]))
{
error_white_both(p, oplen);
clear_tv(rettv);
return FAIL;
}
*arg = skipwhite_and_linebreak(*arg + oplen, evalarg);
if (eval6(arg, &var2, evalarg, !vim9script && op == '.') == FAIL)
{
clear_tv(rettv);
return FAIL;
}
if (evaluate)
{
/*
* Compute the result.
*/
if (op == '.')
{
char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
char_u *s1 = tv_get_string_buf(rettv, buf1);
char_u *s2 = NULL;
if (vim9script && (var2.v_type == VAR_VOID
|| var2.v_type == VAR_CHANNEL
|| var2.v_type == VAR_JOB))
emsg(_(e_inval_string));
#ifdef FEAT_FLOAT
else if (vim9script && var2.v_type == VAR_FLOAT)
{
vim_snprintf((char *)buf2, NUMBUFLEN, "%g",
var2.vval.v_float);
s2 = buf2;
}
#endif
else
s2 = tv_get_string_buf_chk(&var2, buf2);
if (s2 == NULL) // type error ?
{
clear_tv(rettv);
clear_tv(&var2);
return FAIL;
}
p = concat_str(s1, s2);
clear_tv(rettv);
rettv->v_type = VAR_STRING;
rettv->vval.v_string = p;
}
else if (op == '+' && rettv->v_type == VAR_BLOB
&& var2.v_type == VAR_BLOB)
eval_addblob(rettv, &var2);
else if (op == '+' && rettv->v_type == VAR_LIST
&& var2.v_type == VAR_LIST)
{
if (eval_addlist(rettv, &var2) == FAIL)
return FAIL;
}
else
{
int error = FALSE;
varnumber_T n1, n2;
#ifdef FEAT_FLOAT
float_T f1 = 0, f2 = 0;
if (rettv->v_type == VAR_FLOAT)
{
f1 = rettv->vval.v_float;
n1 = 0;
}
else
#endif
{
n1 = tv_get_number_chk(rettv, &error);
if (error)
{
// This can only happen for "list + non-list". For
// "non-list + ..." or "something - ...", we returned
// before evaluating the 2nd operand.
clear_tv(rettv);
return FAIL;
}
#ifdef FEAT_FLOAT
if (var2.v_type == VAR_FLOAT)
f1 = n1;
#endif
}
#ifdef FEAT_FLOAT
if (var2.v_type == VAR_FLOAT)
{
f2 = var2.vval.v_float;
n2 = 0;
}
else
#endif
{
n2 = tv_get_number_chk(&var2, &error);
if (error)
{
clear_tv(rettv);
clear_tv(&var2);
return FAIL;
}
#ifdef FEAT_FLOAT
if (rettv->v_type == VAR_FLOAT)
f2 = n2;
#endif
}
clear_tv(rettv);
#ifdef FEAT_FLOAT
// If there is a float on either side the result is a float.
if (rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
{
if (op == '+')
f1 = f1 + f2;
else
f1 = f1 - f2;
rettv->v_type = VAR_FLOAT;
rettv->vval.v_float = f1;
}
else
#endif
{
if (op == '+')
n1 = n1 + n2;
else
n1 = n1 - n2;
rettv->v_type = VAR_NUMBER;
rettv->vval.v_number = n1;
}
}
clear_tv(&var2);
}
}
return OK;
}
/*
* Handle fifth level expression:
* * number multiplication
* / number division
* % number modulo
*
* "arg" must point to the first non-white of the expression.
* "arg" is advanced to just after the recognized expression.
*
* Return OK or FAIL.
*/
static int
eval6(
char_u **arg,
typval_T *rettv,
evalarg_T *evalarg,
int want_string) // after "." operator
{
#ifdef FEAT_FLOAT
int use_float = FALSE;
#endif
/*
* Get the first variable.
*/
if (eval7(arg, rettv, evalarg, want_string) == FAIL)
return FAIL;
/*
* Repeat computing, until no '*', '/' or '%' is following.
*/
for (;;)
{
int evaluate;
int getnext;
typval_T var2;
char_u *p;
int op;
varnumber_T n1, n2;
#ifdef FEAT_FLOAT
float_T f1, f2;
#endif
int error;
p = eval_next_non_blank(*arg, evalarg, &getnext);
op = *p;
if (op != '*' && op != '/' && op != '%')
break;
evaluate = evalarg == NULL ? 0 : (evalarg->eval_flags & EVAL_EVALUATE);
if (getnext)
*arg = eval_next_line(evalarg);
else
{
if (evaluate && in_vim9script() && !VIM_ISWHITE(**arg))
{
error_white_both(p, 1);
clear_tv(rettv);
return FAIL;
}
*arg = p;
}
#ifdef FEAT_FLOAT
f1 = 0;
f2 = 0;
#endif
error = FALSE;
if (evaluate)
{
#ifdef FEAT_FLOAT
if (rettv->v_type == VAR_FLOAT)
{
f1 = rettv->vval.v_float;
use_float = TRUE;
n1 = 0;
}
else
#endif
n1 = tv_get_number_chk(rettv, &error);
clear_tv(rettv);
if (error)
return FAIL;
}
else
n1 = 0;
/*
* Get the second variable.
*/
if (evaluate && in_vim9script() && !IS_WHITE_OR_NUL((*arg)[1]))
{
error_white_both(p, 1);
clear_tv(rettv);
return FAIL;
}
*arg = skipwhite_and_linebreak(*arg + 1, evalarg);
if (eval7(arg, &var2, evalarg, FALSE) == FAIL)
return FAIL;
if (evaluate)
{
#ifdef FEAT_FLOAT
if (var2.v_type == VAR_FLOAT)
{
if (!use_float)
{
f1 = n1;
use_float = TRUE;
}
f2 = var2.vval.v_float;
n2 = 0;
}
else
#endif
{
n2 = tv_get_number_chk(&var2, &error);
clear_tv(&var2);
if (error)
return FAIL;
#ifdef FEAT_FLOAT
if (use_float)
f2 = n2;
#endif
}
/*
* Compute the result.
* When either side is a float the result is a float.
*/
#ifdef FEAT_FLOAT
if (use_float)
{
if (op == '*')
f1 = f1 * f2;
else if (op == '/')
{
# ifdef VMS
// VMS crashes on divide by zero, work around it
if (f2 == 0.0)
{
if (f1 == 0)
f1 = -1 * __F_FLT_MAX - 1L; // similar to NaN
else if (f1 < 0)
f1 = -1 * __F_FLT_MAX;
else
f1 = __F_FLT_MAX;
}
else
f1 = f1 / f2;
# else
// We rely on the floating point library to handle divide
// by zero to result in "inf" and not a crash.
f1 = f1 / f2;
# endif
}
else
{
emsg(_(e_modulus));
return FAIL;
}
rettv->v_type = VAR_FLOAT;
rettv->vval.v_float = f1;
}
else
#endif
{
int failed = FALSE;
if (op == '*')
n1 = n1 * n2;
else if (op == '/')
n1 = num_divide(n1, n2, &failed);
else
n1 = num_modulus(n1, n2, &failed);
if (failed)
return FAIL;
rettv->v_type = VAR_NUMBER;
rettv->vval.v_number = n1;
}
}
}
return OK;
}
int
eval_leader(char_u **arg, int vim9)
{
char_u *s = *arg;
char_u *p = *arg;
while (*p == '!' || *p == '-' || *p == '+')
{
char_u *n = skipwhite(p + 1);
// ++, --, -+ and +- are not accepted in Vim9 script
if (vim9 && (*p == '-' || *p == '+') && (*n == '-' || *n == '+'))
{
semsg(_(e_invexpr2), s);
return FAIL;
}
p = n;
}
*arg = p;
return OK;
}
/*
* Handle sixth level expression:
* number number constant
* 0zFFFFFFFF Blob constant
* "string" string constant
* 'string' literal string constant
* &option-name option value
* @r register contents
* identifier variable value
* function() function call
* $VAR environment variable
* (expression) nested expression
* [expr, expr] List
* {arg, arg -> expr} Lambda
* {key: val, key: val} Dictionary
* #{key: val, key: val} Dictionary with literal keys
*
* Also handle:
* ! in front logical NOT
* - in front unary minus
* + in front unary plus (ignored)
* trailing [] subscript in String or List
* trailing .name entry in Dictionary
* trailing ->name() method call
*
* "arg" must point to the first non-white of the expression.
* "arg" is advanced to just after the recognized expression.
*
* Return OK or FAIL.
*/
static int
eval7(
char_u **arg,
typval_T *rettv,
evalarg_T *evalarg,
int want_string) // after "." operator
{
int evaluate = evalarg != NULL
&& (evalarg->eval_flags & EVAL_EVALUATE);
int len;
char_u *s;
char_u *start_leader, *end_leader;
int ret = OK;
char_u *alias;
/*
* Initialise variable so that clear_tv() can't mistake this for a
* string and free a string that isn't there.
*/
rettv->v_type = VAR_UNKNOWN;
/*
* Skip '!', '-' and '+' characters. They are handled later.
*/
start_leader = *arg;
if (eval_leader(arg, in_vim9script()) == FAIL)
return FAIL;
end_leader = *arg;
if (**arg == '.' && (!isdigit(*(*arg + 1))
#ifdef FEAT_FLOAT
|| current_sctx.sc_version < 2
#endif
))
{
semsg(_(e_invexpr2), *arg);
++*arg;
return FAIL;
}
switch (**arg)
{
/*
* Number constant.
*/
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '.': ret = eval_number(arg, rettv, evaluate, want_string);
// Apply prefixed "-" and "+" now. Matters especially when
// "->" follows.
if (ret == OK && evaluate && end_leader > start_leader
&& rettv->v_type != VAR_BLOB)
ret = eval7_leader(rettv, TRUE, start_leader, &end_leader);
break;
/*
* String constant: "string".
*/
case '"': ret = eval_string(arg, rettv, evaluate);
break;
/*
* Literal string constant: 'str''ing'.
*/
case '\'': ret = eval_lit_string(arg, rettv, evaluate);
break;
/*
* List: [expr, expr]
*/
case '[': ret = eval_list(arg, rettv, evalarg, TRUE);
break;
/*
* Dictionary: #{key: val, key: val}
*/
case '#': if (!in_vim9script() && (*arg)[1] == '{')
{
++*arg;
ret = eval_dict(arg, rettv, evalarg, TRUE);
}
else
ret = NOTDONE;
break;
/*
* Lambda: {arg, arg -> expr}
* Dictionary: {'key': val, 'key': val}
*/
case '{': if (in_vim9script())
ret = NOTDONE;
else
ret = get_lambda_tv(arg, rettv, in_vim9script(), evalarg);
if (ret == NOTDONE)
ret = eval_dict(arg, rettv, evalarg, FALSE);
break;
/*
* Option value: &name
*/
case '&': ret = eval_option(arg, rettv, evaluate);
break;
/*
* Environment variable: $VAR.
*/
case '$': ret = eval_env_var(arg, rettv, evaluate);
break;
/*
* Register contents: @r.
*/
case '@': ++*arg;
if (evaluate)
{
rettv->v_type = VAR_STRING;
rettv->vval.v_string = get_reg_contents(**arg,
GREG_EXPR_SRC);
}
if (**arg != NUL)
++*arg;
break;
/*
* nested expression: (expression).
* lambda: (arg) => expr
*/
case '(': ret = NOTDONE;
if (in_vim9script())
ret = get_lambda_tv(arg, rettv, TRUE, evalarg);
if (ret == NOTDONE)
{
*arg = skipwhite_and_linebreak(*arg + 1, evalarg);
ret = eval1(arg, rettv, evalarg); // recursive!
*arg = skipwhite_and_linebreak(*arg, evalarg);
if (**arg == ')')
++*arg;
else if (ret == OK)
{
emsg(_(e_missing_close));
clear_tv(rettv);
ret = FAIL;
}
}
break;
default: ret = NOTDONE;
break;
}
if (ret == NOTDONE)
{
/*
* Must be a variable or function name.
* Can also be a curly-braces kind of name: {expr}.
*/
s = *arg;
len = get_name_len(arg, &alias, evaluate, TRUE);
if (alias != NULL)
s = alias;
if (len <= 0)
ret = FAIL;
else
{
int flags = evalarg == NULL ? 0 : evalarg->eval_flags;
if ((in_vim9script() ? **arg : *skipwhite(*arg)) == '(')
{
// "name(..." recursive!
*arg = skipwhite(*arg);
ret = eval_func(arg, evalarg, s, len, rettv, flags, NULL);
}
else if (flags & EVAL_CONSTANT)
ret = FAIL;
else if (evaluate)
{
// get the value of "true", "false" or a variable
if (len == 4 && in_vim9script() && STRNCMP(s, "true", 4) == 0)
{
rettv->v_type = VAR_BOOL;
rettv->vval.v_number = VVAL_TRUE;
ret = OK;
}
else if (len == 5 && in_vim9script()
&& STRNCMP(s, "false", 5) == 0)
{
rettv->v_type = VAR_BOOL;
rettv->vval.v_number = VVAL_FALSE;
ret = OK;
}
else if (len == 4 && in_vim9script()
&& STRNCMP(s, "null", 4) == 0)
{
rettv->v_type = VAR_SPECIAL;
rettv->vval.v_number = VVAL_NULL;
ret = OK;
}
else
ret = eval_variable(s, len, rettv, NULL, TRUE, FALSE);
}
else
{
// skip the name
check_vars(s, len);
ret = OK;
}
}
vim_free(alias);
}
// Handle following '[', '(' and '.' for expr[expr], expr.name,
// expr(expr), expr->name(expr)
if (ret == OK)
ret = handle_subscript(arg, rettv, evalarg, TRUE);
/*
* Apply logical NOT and unary '-', from right to left, ignore '+'.
*/
if (ret == OK && evaluate && end_leader > start_leader)
ret = eval7_leader(rettv, FALSE, start_leader, &end_leader);
return ret;
}
/*
* Apply the leading "!" and "-" before an eval7 expression to "rettv".
* When "numeric_only" is TRUE only handle "+" and "-".
* Adjusts "end_leaderp" until it is at "start_leader".
*/
static int
eval7_leader(
typval_T *rettv,
int numeric_only,
char_u *start_leader,
char_u **end_leaderp)
{
char_u *end_leader = *end_leaderp;
int ret = OK;
int error = FALSE;
varnumber_T val = 0;
vartype_T type = rettv->v_type;
#ifdef FEAT_FLOAT
float_T f = 0.0;
if (rettv->v_type == VAR_FLOAT)
f = rettv->vval.v_float;
else
#endif
{
while (VIM_ISWHITE(end_leader[-1]))
--end_leader;
if (in_vim9script() && end_leader[-1] == '!')
val = tv2bool(rettv);
else
val = tv_get_number_chk(rettv, &error);
}
if (error)
{
clear_tv(rettv);
ret = FAIL;
}
else
{
while (end_leader > start_leader)
{
--end_leader;
if (*end_leader == '!')
{
if (numeric_only)
{
++end_leader;
break;
}
#ifdef FEAT_FLOAT
if (rettv->v_type == VAR_FLOAT)
{
if (in_vim9script())
{
rettv->v_type = VAR_BOOL;
val = f == 0.0 ? VVAL_TRUE : VVAL_FALSE;
}
else
f = !f;
}
else
#endif
{
val = !val;
type = VAR_BOOL;
}
}
else if (*end_leader == '-')
{
#ifdef FEAT_FLOAT
if (rettv->v_type == VAR_FLOAT)
f = -f;
else
#endif
{
val = -val;
type = VAR_NUMBER;
}
}
}
#ifdef FEAT_FLOAT
if (rettv->v_type == VAR_FLOAT)
{
clear_tv(rettv);
rettv->vval.v_float = f;
}
else
#endif
{
clear_tv(rettv);
if (in_vim9script())
rettv->v_type = type;
else
rettv->v_type = VAR_NUMBER;
rettv->vval.v_number = val;
}
}
*end_leaderp = end_leader;
return ret;
}
/*
* Call the function referred to in "rettv".
*/
static int
call_func_rettv(
char_u **arg,
evalarg_T *evalarg,
typval_T *rettv,
int evaluate,
dict_T *selfdict,
typval_T *basetv)
{
partial_T *pt = NULL;
funcexe_T funcexe;
typval_T functv;
char_u *s;
int ret;
// need to copy the funcref so that we can clear rettv
if (evaluate)
{
functv = *rettv;
rettv->v_type = VAR_UNKNOWN;
// Invoke the function. Recursive!
if (functv.v_type == VAR_PARTIAL)
{
pt = functv.vval.v_partial;
s = partial_name(pt);
}
else
s = functv.vval.v_string;
}
else
s = (char_u *)"";
CLEAR_FIELD(funcexe);
funcexe.firstline = curwin->w_cursor.lnum;
funcexe.lastline = curwin->w_cursor.lnum;
funcexe.evaluate = evaluate;
funcexe.partial = pt;
funcexe.selfdict = selfdict;
funcexe.basetv = basetv;
ret = get_func_tv(s, -1, rettv, arg, evalarg, &funcexe);
// Clear the funcref afterwards, so that deleting it while
// evaluating the arguments is possible (see test55).
if (evaluate)
clear_tv(&functv);
return ret;
}
/*
* Evaluate "->method()".
* "*arg" points to "method".
* Returns FAIL or OK. "*arg" is advanced to after the ')'.
*/
static int
eval_lambda(
char_u **arg,
typval_T *rettv,
evalarg_T *evalarg,
int verbose) // give error messages
{
int evaluate = evalarg != NULL
&& (evalarg->eval_flags & EVAL_EVALUATE);
typval_T base = *rettv;
int ret;
rettv->v_type = VAR_UNKNOWN;
if (**arg == '{')
{
// ->{lambda}()
ret = get_lambda_tv(arg, rettv, FALSE, evalarg);
}
else
{
// ->(lambda)()
++*arg;
ret = eval1(arg, rettv, evalarg);
*arg = skipwhite_and_linebreak(*arg, evalarg);
if (**arg != ')')
{
emsg(_(e_missing_close));
ret = FAIL;
}
++*arg;
}
if (ret != OK)
return FAIL;
else if (**arg != '(')
{
if (verbose)
{
if (*skipwhite(*arg) == '(')
emsg(_(e_nowhitespace));
else
semsg(_(e_missing_paren), "lambda");
}
clear_tv(rettv);
ret = FAIL;
}
else
ret = call_func_rettv(arg, evalarg, rettv, evaluate, NULL, &base);
// Clear the funcref afterwards, so that deleting it while
// evaluating the arguments is possible (see test55).
if (evaluate)
clear_tv(&base);
return ret;
}
/*
* Evaluate "->method()".
* "*arg" points to "method".
* Returns FAIL or OK. "*arg" is advanced to after the ')'.
*/
static int
eval_method(
char_u **arg,
typval_T *rettv,
evalarg_T *evalarg,
int verbose) // give error messages
{
char_u *name;
long len;
char_u *alias;
typval_T base = *rettv;
int ret;
int evaluate = evalarg != NULL
&& (evalarg->eval_flags & EVAL_EVALUATE);
rettv->v_type = VAR_UNKNOWN;
name = *arg;
len = get_name_len(arg, &alias, evaluate, TRUE);
if (alias != NULL)
name = alias;
if (len <= 0)
{
if (verbose)
emsg(_("E260: Missing name after ->"));
ret = FAIL;
}
else
{
*arg = skipwhite(*arg);
if (**arg != '(')
{
if (verbose)
semsg(_(e_missing_paren), name);
ret = FAIL;
}
else if (VIM_ISWHITE((*arg)[-1]))
{
if (verbose)
emsg(_(e_nowhitespace));
ret = FAIL;
}
else
ret = eval_func(arg, evalarg, name, len, rettv,
evaluate ? EVAL_EVALUATE : 0, &base);
}
// Clear the funcref afterwards, so that deleting it while
// evaluating the arguments is possible (see test55).
if (evaluate)
clear_tv(&base);
return ret;
}
/*
* Evaluate an "[expr]" or "[expr:expr]" index. Also "dict.key".
* "*arg" points to the '[' or '.'.
* Returns FAIL or OK. "*arg" is advanced to after the ']'.
*/
static int
eval_index(
char_u **arg,
typval_T *rettv,
evalarg_T *evalarg,
int verbose) // give error messages
{
int evaluate = evalarg != NULL
&& (evalarg->eval_flags & EVAL_EVALUATE);
int empty1 = FALSE, empty2 = FALSE;
typval_T var1, var2;
int range = FALSE;
char_u *key = NULL;
int keylen = -1;
int vim9 = in_vim9script();
if (check_can_index(rettv, evaluate, verbose) == FAIL)
return FAIL;
init_tv(&var1);
init_tv(&var2);
if (**arg == '.')
{
/*
* dict.name
*/
key = *arg + 1;
for (keylen = 0; eval_isdictc(key[keylen]); ++keylen)
;
if (keylen == 0)
return FAIL;
*arg = key + keylen;
}
else
{
/*
* something[idx]
*
* Get the (first) variable from inside the [].
*/
*arg = skipwhite_and_linebreak(*arg + 1, evalarg);
if (**arg == ':')
empty1 = TRUE;
else if (eval1(arg, &var1, evalarg) == FAIL) // recursive!
return FAIL;
else if (vim9 && **arg == ':')
{
semsg(_(e_white_space_required_before_and_after_str_at_str),
":", *arg);
clear_tv(&var1);
return FAIL;
}
else if (evaluate && tv_get_string_chk(&var1) == NULL)
{
// not a number or string
clear_tv(&var1);
return FAIL;
}
/*
* Get the second variable from inside the [:].
*/
*arg = skipwhite_and_linebreak(*arg, evalarg);
if (**arg == ':')
{
range = TRUE;
++*arg;
if (vim9 && !IS_WHITE_OR_NUL(**arg) && **arg != ']')
{
semsg(_(e_white_space_required_before_and_after_str_at_str),
":", *arg - 1);
if (!empty1)
clear_tv(&var1);
return FAIL;
}
*arg = skipwhite_and_linebreak(*arg, evalarg);
if (**arg == ']')
empty2 = TRUE;
else if (eval1(arg, &var2, evalarg) == FAIL) // recursive!
{
if (!empty1)
clear_tv(&var1);
return FAIL;
}
else if (evaluate && tv_get_string_chk(&var2) == NULL)
{
// not a number or string
if (!empty1)
clear_tv(&var1);
clear_tv(&var2);
return FAIL;
}
}
// Check for the ']'.
*arg = skipwhite_and_linebreak(*arg, evalarg);
if (**arg != ']')
{
if (verbose)
emsg(_(e_missbrac));
clear_tv(&var1);
if (range)
clear_tv(&var2);
return FAIL;
}
*arg = *arg + 1; // skip over the ']'
}
if (evaluate)
{
int res = eval_index_inner(rettv, range,
empty1 ? NULL : &var1, empty2 ? NULL : &var2, FALSE,
key, keylen, verbose);
if (!empty1)
clear_tv(&var1);
if (range)
clear_tv(&var2);
return res;
}
return OK;
}
/*
* Check if "rettv" can have an [index] or [sli:ce]
*/
int
check_can_index(typval_T *rettv, int evaluate, int verbose)
{
switch (rettv->v_type)
{
case VAR_FUNC:
case VAR_PARTIAL:
if (verbose)
emsg(_("E695: Cannot index a Funcref"));
return FAIL;
case VAR_FLOAT:
#ifdef FEAT_FLOAT
if (verbose)
emsg(_(e_float_as_string));
return FAIL;
#endif
case VAR_BOOL:
case VAR_SPECIAL:
case VAR_JOB:
case VAR_CHANNEL:
if (verbose)
emsg(_(e_cannot_index_special_variable));
return FAIL;
case VAR_UNKNOWN:
case VAR_ANY:
case VAR_VOID:
if (evaluate)
{
emsg(_(e_cannot_index_special_variable));
return FAIL;
}
// FALLTHROUGH
case VAR_STRING:
case VAR_LIST:
case VAR_DICT:
case VAR_BLOB:
break;
case VAR_NUMBER:
if (in_vim9script())
emsg(_(e_cannot_index_number));
break;
}
return OK;
}
/*
* slice() function
*/
void
f_slice(typval_T *argvars, typval_T *rettv)
{
if (check_can_index(argvars, TRUE, FALSE) == OK)
{
copy_tv(argvars, rettv);
eval_index_inner(rettv, TRUE, argvars + 1,
argvars[2].v_type == VAR_UNKNOWN ? NULL : argvars + 2,
TRUE, NULL, 0, FALSE);
}
}
/*
* Apply index or range to "rettv".
* "var1" is the first index, NULL for [:expr].
* "var2" is the second index, NULL for [expr] and [expr: ]
* "exclusive" is TRUE for slice(): second index is exclusive, use character
* index for string.
* Alternatively, "key" is not NULL, then key[keylen] is the dict index.
*/
int
eval_index_inner(
typval_T *rettv,
int is_range,
typval_T *var1,
typval_T *var2,
int exclusive,
char_u *key,
int keylen,
int verbose)
{
varnumber_T n1, n2 = 0;
long len;
n1 = 0;
if (var1 != NULL && rettv->v_type != VAR_DICT)
n1 = tv_get_number(var1);
if (is_range)
{
if (rettv->v_type == VAR_DICT)
{
if (verbose)
emsg(_(e_cannot_slice_dictionary));
return FAIL;
}
if (var2 != NULL)
n2 = tv_get_number(var2);
else
n2 = VARNUM_MAX;
}
switch (rettv->v_type)
{
case VAR_UNKNOWN:
case VAR_ANY:
case VAR_VOID:
case VAR_FUNC:
case VAR_PARTIAL:
case VAR_FLOAT:
case VAR_BOOL:
case VAR_SPECIAL:
case VAR_JOB:
case VAR_CHANNEL:
break; // not evaluating, skipping over subscript
case VAR_NUMBER:
case VAR_STRING:
{
char_u *s = tv_get_string(rettv);
len = (long)STRLEN(s);
if (in_vim9script() || exclusive)
{
if (is_range)
s = string_slice(s, n1, n2, exclusive);
else
s = char_from_string(s, n1);
}
else if (is_range)
{
// The resulting variable is a substring. If the indexes
// are out of range the result is empty.
if (n1 < 0)
{
n1 = len + n1;
if (n1 < 0)
n1 = 0;
}
if (n2 < 0)
n2 = len + n2;
else if (n2 >= len)
n2 = len;
if (exclusive)
--n2;
if (n1 >= len || n2 < 0 || n1 > n2)
s = NULL;
else
s = vim_strnsave(s + n1, n2 - n1 + 1);
}
else
{
// The resulting variable is a string of a single
// character. If the index is too big or negative the
// result is empty.
if (n1 >= len || n1 < 0)
s = NULL;
else
s = vim_strnsave(s + n1, 1);
}
clear_tv(rettv);
rettv->v_type = VAR_STRING;
rettv->vval.v_string = s;
}
break;
case VAR_BLOB:
len = blob_len(rettv->vval.v_blob);
if (is_range)
{
// The resulting variable is a sub-blob. If the indexes
// are out of range the result is empty.
if (n1 < 0)
{
n1 = len + n1;
if (n1 < 0)
n1 = 0;
}
if (n2 < 0)
n2 = len + n2;
else if (n2 >= len)
n2 = len - (exclusive ? 0 : 1);
if (exclusive)
--n2;
if (n1 >= len || n2 < 0 || n1 > n2)
{
clear_tv(rettv);
rettv->v_type = VAR_BLOB;
rettv->vval.v_blob = NULL;
}
else
{
blob_T *blob = blob_alloc();
long i;
if (blob != NULL)
{
if (ga_grow(&blob->bv_ga, n2 - n1 + 1) == FAIL)
{
blob_free(blob);
return FAIL;
}
blob->bv_ga.ga_len = n2 - n1 + 1;
for (i = n1; i <= n2; i++)
blob_set(blob, i - n1,
blob_get(rettv->vval.v_blob, i));
clear_tv(rettv);
rettv_blob_set(rettv, blob);
}
}
}
else
{
// The resulting variable is a byte value.
// If the index is too big or negative that is an error.
if (n1 < 0)
n1 = len + n1;
if (n1 < len && n1 >= 0)
{
int v = blob_get(rettv->vval.v_blob, n1);
clear_tv(rettv);
rettv->v_type = VAR_NUMBER;
rettv->vval.v_number = v;
}
else
semsg(_(e_blobidx), n1);
}
break;
case VAR_LIST:
if (var1 == NULL)
n1 = 0;
if (var2 == NULL)
n2 = VARNUM_MAX;
if (list_slice_or_index(rettv->vval.v_list,
is_range, n1, n2, exclusive, rettv, verbose) == FAIL)
return FAIL;
break;
case VAR_DICT:
{
dictitem_T *item;
typval_T tmp;
if (key == NULL)
{
key = tv_get_string_chk(var1);
if (key == NULL)
return FAIL;
}
item = dict_find(rettv->vval.v_dict, key, (int)keylen);
if (item == NULL && verbose)
semsg(_(e_dictkey), key);
if (item == NULL)
return FAIL;
copy_tv(&item->di_tv, &tmp);
clear_tv(rettv);
*rettv = tmp;
}
break;
}
return OK;
}
/*
* Return the function name of partial "pt".
*/
char_u *
partial_name(partial_T *pt)
{
if (pt->pt_name != NULL)
return pt->pt_name;
if (pt->pt_func != NULL)
return pt->pt_func->uf_name;
return (char_u *)"";
}
static void
partial_free(partial_T *pt)
{
int i;
for (i = 0; i < pt->pt_argc; ++i)
clear_tv(&pt->pt_argv[i]);
vim_free(pt->pt_argv);
dict_unref(pt->pt_dict);
if (pt->pt_name != NULL)
{
func_unref(pt->pt_name);
vim_free(pt->pt_name);
}
else
func_ptr_unref(pt->pt_func);
// Decrease the reference count for the context of a closure. If down
// to the minimum it may be time to free it.
if (pt->pt_funcstack != NULL)
{
--pt->pt_funcstack->fs_refcount;
funcstack_check_refcount(pt->pt_funcstack);
}
vim_free(pt);
}
/*
* Unreference a closure: decrement the reference count and free it when it
* becomes zero.
*/
void
partial_unref(partial_T *pt)
{
if (pt != NULL)
{
if (--pt->pt_refcount <= 0)
partial_free(pt);
// If the reference count goes down to one, the funcstack may be the
// only reference and can be freed if no other partials reference it.
else if (pt->pt_refcount == 1 && pt->pt_funcstack != NULL)
funcstack_check_refcount(pt->pt_funcstack);
}
}
/*
* Return the next (unique) copy ID.
* Used for serializing nested structures.
*/
int
get_copyID(void)
{
current_copyID += COPYID_INC;
return current_copyID;
}
/*
* Garbage collection for lists and dictionaries.
*
* We use reference counts to be able to free most items right away when they
* are no longer used. But for composite items it's possible that it becomes
* unused while the reference count is > 0: When there is a recursive
* reference. Example:
* :let l = [1, 2, 3]
* :let d = {9: l}
* :let l[1] = d
*
* Since this is quite unusual we handle this with garbage collection: every
* once in a while find out which lists and dicts are not referenced from any
* variable.
*
* Here is a good reference text about garbage collection (refers to Python
* but it applies to all reference-counting mechanisms):
* http://python.ca/nas/python/gc/
*/
/*
* Do garbage collection for lists and dicts.
* When "testing" is TRUE this is called from test_garbagecollect_now().
* Return TRUE if some memory was freed.
*/
int
garbage_collect(int testing)
{
int copyID;
int abort = FALSE;
buf_T *buf;
win_T *wp;
int did_free = FALSE;
tabpage_T *tp;
if (!testing)
{
// Only do this once.
want_garbage_collect = FALSE;
may_garbage_collect = FALSE;
garbage_collect_at_exit = FALSE;
}
// The execution stack can grow big, limit the size.
if (exestack.ga_maxlen - exestack.ga_len > 500)
{
size_t new_len;
char_u *pp;
int n;
// Keep 150% of the current size, with a minimum of the growth size.
n = exestack.ga_len / 2;
if (n < exestack.ga_growsize)
n = exestack.ga_growsize;
// Don't make it bigger though.
if (exestack.ga_len + n < exestack.ga_maxlen)
{
new_len = exestack.ga_itemsize * (exestack.ga_len + n);
pp = vim_realloc(exestack.ga_data, new_len);
if (pp == NULL)
return FAIL;
exestack.ga_maxlen = exestack.ga_len + n;
exestack.ga_data = pp;
}
}
// We advance by two because we add one for items referenced through
// previous_funccal.
copyID = get_copyID();
/*
* 1. Go through all accessible variables and mark all lists and dicts
* with copyID.
*/
// Don't free variables in the previous_funccal list unless they are only
// referenced through previous_funccal. This must be first, because if
// the item is referenced elsewhere the funccal must not be freed.
abort = abort || set_ref_in_previous_funccal(copyID);
// script-local variables
abort = abort || garbage_collect_scriptvars(copyID);
// buffer-local variables
FOR_ALL_BUFFERS(buf)
abort = abort || set_ref_in_item(&buf->b_bufvar.di_tv, copyID,
NULL, NULL);
// window-local variables
FOR_ALL_TAB_WINDOWS(tp, wp)
abort = abort || set_ref_in_item(&wp->w_winvar.di_tv, copyID,
NULL, NULL);
if (aucmd_win != NULL)
abort = abort || set_ref_in_item(&aucmd_win->w_winvar.di_tv, copyID,
NULL, NULL);
#ifdef FEAT_PROP_POPUP
FOR_ALL_POPUPWINS(wp)
abort = abort || set_ref_in_item(&wp->w_winvar.di_tv, copyID,
NULL, NULL);
FOR_ALL_TABPAGES(tp)
FOR_ALL_POPUPWINS_IN_TAB(tp, wp)
abort = abort || set_ref_in_item(&wp->w_winvar.di_tv, copyID,
NULL, NULL);
#endif
// tabpage-local variables
FOR_ALL_TABPAGES(tp)
abort = abort || set_ref_in_item(&tp->tp_winvar.di_tv, copyID,
NULL, NULL);
// global variables
abort = abort || garbage_collect_globvars(copyID);
// function-local variables
abort = abort || set_ref_in_call_stack(copyID);
// named functions (matters for closures)
abort = abort || set_ref_in_functions(copyID);
// function call arguments, if v:testing is set.
abort = abort || set_ref_in_func_args(copyID);
// v: vars
abort = abort || garbage_collect_vimvars(copyID);
// callbacks in buffers
abort = abort || set_ref_in_buffers(copyID);
#ifdef FEAT_LUA
abort = abort || set_ref_in_lua(copyID);
#endif
#ifdef FEAT_PYTHON
abort = abort || set_ref_in_python(copyID);
#endif
#ifdef FEAT_PYTHON3
abort = abort || set_ref_in_python3(copyID);
#endif
#ifdef FEAT_JOB_CHANNEL
abort = abort || set_ref_in_channel(copyID);
abort = abort || set_ref_in_job(copyID);
#endif
#ifdef FEAT_NETBEANS_INTG
abort = abort || set_ref_in_nb_channel(copyID);
#endif
#ifdef FEAT_TIMERS
abort = abort || set_ref_in_timer(copyID);
#endif
#ifdef FEAT_QUICKFIX
abort = abort || set_ref_in_quickfix(copyID);
#endif
#ifdef FEAT_TERMINAL
abort = abort || set_ref_in_term(copyID);
#endif
#ifdef FEAT_PROP_POPUP
abort = abort || set_ref_in_popups(copyID);
#endif
if (!abort)
{
/*
* 2. Free lists and dictionaries that are not referenced.
*/
did_free = free_unref_items(copyID);
/*
* 3. Check if any funccal can be freed now.
* This may call us back recursively.
*/
free_unref_funccal(copyID, testing);
}
else if (p_verbose > 0)
{
verb_msg(_("Not enough memory to set references, garbage collection aborted!"));
}
return did_free;
}
/*
* Free lists, dictionaries, channels and jobs that are no longer referenced.
*/
static int
free_unref_items(int copyID)
{
int did_free = FALSE;
// Let all "free" functions know that we are here. This means no
// dictionaries, lists, channels or jobs are to be freed, because we will
// do that here.
in_free_unref_items = TRUE;
/*
* PASS 1: free the contents of the items. We don't free the items
* themselves yet, so that it is possible to decrement refcount counters
*/
// Go through the list of dicts and free items without the copyID.
did_free |= dict_free_nonref(copyID);
// Go through the list of lists and free items without the copyID.
did_free |= list_free_nonref(copyID);
#ifdef FEAT_JOB_CHANNEL
// Go through the list of jobs and free items without the copyID. This
// must happen before doing channels, because jobs refer to channels, but
// the reference from the channel to the job isn't tracked.
did_free |= free_unused_jobs_contents(copyID, COPYID_MASK);
// Go through the list of channels and free items without the copyID.
did_free |= free_unused_channels_contents(copyID, COPYID_MASK);
#endif
/*
* PASS 2: free the items themselves.
*/
dict_free_items(copyID);
list_free_items(copyID);
#ifdef FEAT_JOB_CHANNEL
// Go through the list of jobs and free items without the copyID. This
// must happen before doing channels, because jobs refer to channels, but
// the reference from the channel to the job isn't tracked.
free_unused_jobs(copyID, COPYID_MASK);
// Go through the list of channels and free items without the copyID.
free_unused_channels(copyID, COPYID_MASK);
#endif
in_free_unref_items = FALSE;
return did_free;
}
/*
* Mark all lists and dicts referenced through hashtab "ht" with "copyID".
* "list_stack" is used to add lists to be marked. Can be NULL.
*
* Returns TRUE if setting references failed somehow.
*/
int
set_ref_in_ht(hashtab_T *ht, int copyID, list_stack_T **list_stack)
{
int todo;
int abort = FALSE;
hashitem_T *hi;
hashtab_T *cur_ht;
ht_stack_T *ht_stack = NULL;
ht_stack_T *tempitem;
cur_ht = ht;
for (;;)
{
if (!abort)
{
// Mark each item in the hashtab. If the item contains a hashtab
// it is added to ht_stack, if it contains a list it is added to
// list_stack.
todo = (int)cur_ht->ht_used;
for (hi = cur_ht->ht_array; todo > 0; ++hi)
if (!HASHITEM_EMPTY(hi))
{
--todo;
abort = abort || set_ref_in_item(&HI2DI(hi)->di_tv, copyID,
&ht_stack, list_stack);
}
}
if (ht_stack == NULL)
break;
// take an item from the stack
cur_ht = ht_stack->ht;
tempitem = ht_stack;
ht_stack = ht_stack->prev;
free(tempitem);
}
return abort;
}
/*
* Mark a dict and its items with "copyID".
* Returns TRUE if setting references failed somehow.
*/
int
set_ref_in_dict(dict_T *d, int copyID)
{
if (d != NULL && d->dv_copyID != copyID)
{
d->dv_copyID = copyID;
return set_ref_in_ht(&d->dv_hashtab, copyID, NULL);
}
return FALSE;
}
/*
* Mark a list and its items with "copyID".
* Returns TRUE if setting references failed somehow.
*/
int
set_ref_in_list(list_T *ll, int copyID)
{
if (ll != NULL && ll->lv_copyID != copyID)
{
ll->lv_copyID = copyID;
return set_ref_in_list_items(ll, copyID, NULL);
}
return FALSE;
}
/*
* Mark all lists and dicts referenced through list "l" with "copyID".
* "ht_stack" is used to add hashtabs to be marked. Can be NULL.
*
* Returns TRUE if setting references failed somehow.
*/
int
set_ref_in_list_items(list_T *l, int copyID, ht_stack_T **ht_stack)
{
listitem_T *li;
int abort = FALSE;
list_T *cur_l;
list_stack_T *list_stack = NULL;
list_stack_T *tempitem;
cur_l = l;
for (;;)
{
if (!abort && cur_l->lv_first != &range_list_item)
// Mark each item in the list. If the item contains a hashtab
// it is added to ht_stack, if it contains a list it is added to
// list_stack.
for (li = cur_l->lv_first; !abort && li != NULL; li = li->li_next)
abort = abort || set_ref_in_item(&li->li_tv, copyID,
ht_stack, &list_stack);
if (list_stack == NULL)
break;
// take an item from the stack
cur_l = list_stack->list;
tempitem = list_stack;
list_stack = list_stack->prev;
free(tempitem);
}
return abort;
}
/*
* Mark all lists and dicts referenced through typval "tv" with "copyID".
* "list_stack" is used to add lists to be marked. Can be NULL.
* "ht_stack" is used to add hashtabs to be marked. Can be NULL.
*
* Returns TRUE if setting references failed somehow.
*/
int
set_ref_in_item(
typval_T *tv,
int copyID,
ht_stack_T **ht_stack,
list_stack_T **list_stack)
{
int abort = FALSE;
if (tv->v_type == VAR_DICT)
{
dict_T *dd = tv->vval.v_dict;
if (dd != NULL && dd->dv_copyID != copyID)
{
// Didn't see this dict yet.
dd->dv_copyID = copyID;
if (ht_stack == NULL)
{
abort = set_ref_in_ht(&dd->dv_hashtab, copyID, list_stack);
}
else
{
ht_stack_T *newitem = ALLOC_ONE(ht_stack_T);
if (newitem == NULL)
abort = TRUE;
else
{
newitem->ht = &dd->dv_hashtab;
newitem->prev = *ht_stack;
*ht_stack = newitem;
}
}
}
}
else if (tv->v_type == VAR_LIST)
{
list_T *ll = tv->vval.v_list;
if (ll != NULL && ll->lv_copyID != copyID)
{
// Didn't see this list yet.
ll->lv_copyID = copyID;
if (list_stack == NULL)
{
abort = set_ref_in_list_items(ll, copyID, ht_stack);
}
else
{
list_stack_T *newitem = ALLOC_ONE(list_stack_T);
if (newitem == NULL)
abort = TRUE;
else
{
newitem->list = ll;
newitem->prev = *list_stack;
*list_stack = newitem;
}
}
}
}
else if (tv->v_type == VAR_FUNC)
{
abort = set_ref_in_func(tv->vval.v_string, NULL, copyID);
}
else if (tv->v_type == VAR_PARTIAL)
{
partial_T *pt = tv->vval.v_partial;
int i;
if (pt != NULL && pt->pt_copyID != copyID)
{
// Didn't see this partial yet.
pt->pt_copyID = copyID;
abort = set_ref_in_func(pt->pt_name, pt->pt_func, copyID);
if (pt->pt_dict != NULL)
{
typval_T dtv;
dtv.v_type = VAR_DICT;
dtv.vval.v_dict = pt->pt_dict;
set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
}
for (i = 0; i < pt->pt_argc; ++i)
abort = abort || set_ref_in_item(&pt->pt_argv[i], copyID,
ht_stack, list_stack);
if (pt->pt_funcstack != NULL)
{
typval_T *stack = pt->pt_funcstack->fs_ga.ga_data;
for (i = 0; i < pt->pt_funcstack->fs_ga.ga_len; ++i)
abort = abort || set_ref_in_item(stack + i, copyID,
ht_stack, list_stack);
}
}
}
#ifdef FEAT_JOB_CHANNEL
else if (tv->v_type == VAR_JOB)
{
job_T *job = tv->vval.v_job;
typval_T dtv;
if (job != NULL && job->jv_copyID != copyID)
{
job->jv_copyID = copyID;
if (job->jv_channel != NULL)
{
dtv.v_type = VAR_CHANNEL;
dtv.vval.v_channel = job->jv_channel;
set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
}
if (job->jv_exit_cb.cb_partial != NULL)
{
dtv.v_type = VAR_PARTIAL;
dtv.vval.v_partial = job->jv_exit_cb.cb_partial;
set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
}
}
}
else if (tv->v_type == VAR_CHANNEL)
{
channel_T *ch =tv->vval.v_channel;
ch_part_T part;
typval_T dtv;
jsonq_T *jq;
cbq_T *cq;
if (ch != NULL && ch->ch_copyID != copyID)
{
ch->ch_copyID = copyID;
for (part = PART_SOCK; part < PART_COUNT; ++part)
{
for (jq = ch->ch_part[part].ch_json_head.jq_next; jq != NULL;
jq = jq->jq_next)
set_ref_in_item(jq->jq_value, copyID, ht_stack, list_stack);
for (cq = ch->ch_part[part].ch_cb_head.cq_next; cq != NULL;
cq = cq->cq_next)
if (cq->cq_callback.cb_partial != NULL)
{
dtv.v_type = VAR_PARTIAL;
dtv.vval.v_partial = cq->cq_callback.cb_partial;
set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
}
if (ch->ch_part[part].ch_callback.cb_partial != NULL)
{
dtv.v_type = VAR_PARTIAL;
dtv.vval.v_partial =
ch->ch_part[part].ch_callback.cb_partial;
set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
}
}
if (ch->ch_callback.cb_partial != NULL)
{
dtv.v_type = VAR_PARTIAL;
dtv.vval.v_partial = ch->ch_callback.cb_partial;
set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
}
if (ch->ch_close_cb.cb_partial != NULL)
{
dtv.v_type = VAR_PARTIAL;
dtv.vval.v_partial = ch->ch_close_cb.cb_partial;
set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
}
}
}
#endif
return abort;
}
/*
* Return a string with the string representation of a variable.
* If the memory is allocated "tofree" is set to it, otherwise NULL.
* "numbuf" is used for a number.
* When "copyID" is not NULL replace recursive lists and dicts with "...".
* When both "echo_style" and "composite_val" are FALSE, put quotes around
* strings as "string()", otherwise does not put quotes around strings, as
* ":echo" displays values.
* When "restore_copyID" is FALSE, repeated items in dictionaries and lists
* are replaced with "...".
* May return NULL.
*/
char_u *
echo_string_core(
typval_T *tv,
char_u **tofree,
char_u *numbuf,
int copyID,
int echo_style,
int restore_copyID,
int composite_val)
{
static int recurse = 0;
char_u *r = NULL;
if (recurse >= DICT_MAXNEST)
{
if (!did_echo_string_emsg)
{
// Only give this message once for a recursive call to avoid
// flooding the user with errors. And stop iterating over lists
// and dicts.
did_echo_string_emsg = TRUE;
emsg(_("E724: variable nested too deep for displaying"));
}
*tofree = NULL;
return (char_u *)"{E724}";
}
++recurse;
switch (tv->v_type)
{
case VAR_STRING:
if (echo_style && !composite_val)
{
*tofree = NULL;
r = tv->vval.v_string;
if (r == NULL)
r = (char_u *)"";
}
else
{
*tofree = string_quote(tv->vval.v_string, FALSE);
r = *tofree;
}
break;
case VAR_FUNC:
if (echo_style)
{
*tofree = NULL;
r = tv->vval.v_string;
}
else
{
*tofree = string_quote(tv->vval.v_string, TRUE);
r = *tofree;
}
break;
case VAR_PARTIAL:
{
partial_T *pt = tv->vval.v_partial;
char_u *fname = string_quote(pt == NULL ? NULL
: partial_name(pt), FALSE);
garray_T ga;
int i;
char_u *tf;
ga_init2(&ga, 1, 100);
ga_concat(&ga, (char_u *)"function(");
if (fname != NULL)
{
ga_concat(&ga, fname);
vim_free(fname);
}
if (pt != NULL && pt->pt_argc > 0)
{
ga_concat(&ga, (char_u *)", [");
for (i = 0; i < pt->pt_argc; ++i)
{
if (i > 0)
ga_concat(&ga, (char_u *)", ");
ga_concat(&ga,
tv2string(&pt->pt_argv[i], &tf, numbuf, copyID));
vim_free(tf);
}
ga_concat(&ga, (char_u *)"]");
}
if (pt != NULL && pt->pt_dict != NULL)
{
typval_T dtv;
ga_concat(&ga, (char_u *)", ");
dtv.v_type = VAR_DICT;
dtv.vval.v_dict = pt->pt_dict;
ga_concat(&ga, tv2string(&dtv, &tf, numbuf, copyID));
vim_free(tf);
}
ga_concat(&ga, (char_u *)")");
*tofree = ga.ga_data;
r = *tofree;
break;
}
case VAR_BLOB:
r = blob2string(tv->vval.v_blob, tofree, numbuf);
break;
case VAR_LIST:
if (tv->vval.v_list == NULL)
{
// NULL list is equivalent to empty list.
*tofree = NULL;
r = (char_u *)"[]";
}
else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID
&& tv->vval.v_list->lv_len > 0)
{
*tofree = NULL;
r = (char_u *)"[...]";
}
else
{
int old_copyID = tv->vval.v_list->lv_copyID;
tv->vval.v_list->lv_copyID = copyID;
*tofree = list2string(tv, copyID, restore_copyID);
if (restore_copyID)
tv->vval.v_list->lv_copyID = old_copyID;
r = *tofree;
}
break;
case VAR_DICT:
if (tv->vval.v_dict == NULL)
{
// NULL dict is equivalent to empty dict.
*tofree = NULL;
r = (char_u *)"{}";
}
else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID
&& tv->vval.v_dict->dv_hashtab.ht_used != 0)
{
*tofree = NULL;
r = (char_u *)"{...}";
}
else
{
int old_copyID = tv->vval.v_dict->dv_copyID;
tv->vval.v_dict->dv_copyID = copyID;
*tofree = dict2string(tv, copyID, restore_copyID);
if (restore_copyID)
tv->vval.v_dict->dv_copyID = old_copyID;
r = *tofree;
}
break;
case VAR_NUMBER:
case VAR_UNKNOWN:
case VAR_ANY:
case VAR_VOID:
*tofree = NULL;
r = tv_get_string_buf(tv, numbuf);
break;
case VAR_JOB:
case VAR_CHANNEL:
*tofree = NULL;
r = tv_get_string_buf(tv, numbuf);
if (composite_val)
{
*tofree = string_quote(r, FALSE);
r = *tofree;
}
break;
case VAR_FLOAT:
#ifdef FEAT_FLOAT
*tofree = NULL;
vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv->vval.v_float);
r = numbuf;
break;
#endif
case VAR_BOOL:
case VAR_SPECIAL:
*tofree = NULL;
r = (char_u *)get_var_special_name(tv->vval.v_number);
break;
}
if (--recurse == 0)
did_echo_string_emsg = FALSE;
return r;
}
/*
* Return a string with the string representation of a variable.
* If the memory is allocated "tofree" is set to it, otherwise NULL.
* "numbuf" is used for a number.
* Does not put quotes around strings, as ":echo" displays values.
* When "copyID" is not NULL replace recursive lists and dicts with "...".
* May return NULL.
*/
char_u *
echo_string(
typval_T *tv,
char_u **tofree,
char_u *numbuf,
int copyID)
{
return echo_string_core(tv, tofree, numbuf, copyID, TRUE, FALSE, FALSE);
}
/*
* Return string "str" in ' quotes, doubling ' characters.
* If "str" is NULL an empty string is assumed.
* If "function" is TRUE make it function('string').
*/
char_u *
string_quote(char_u *str, int function)
{
unsigned len;
char_u *p, *r, *s;
len = (function ? 13 : 3);
if (str != NULL)
{
len += (unsigned)STRLEN(str);
for (p = str; *p != NUL; MB_PTR_ADV(p))
if (*p == '\'')
++len;
}
s = r = alloc(len);
if (r != NULL)
{
if (function)
{
STRCPY(r, "function('");
r += 10;
}
else
*r++ = '\'';
if (str != NULL)
for (p = str; *p != NUL; )
{
if (*p == '\'')
*r++ = '\'';
MB_COPY_CHAR(p, r);
}
*r++ = '\'';
if (function)
*r++ = ')';
*r++ = NUL;
}
return s;
}
#if defined(FEAT_FLOAT) || defined(PROTO)
/*
* Convert the string "text" to a floating point number.
* This uses strtod(). setlocale(LC_NUMERIC, "C") has been used to make sure
* this always uses a decimal point.
* Returns the length of the text that was consumed.
*/
int
string2float(
char_u *text,
float_T *value) // result stored here
{
char *s = (char *)text;
float_T f;
// MS-Windows does not deal with "inf" and "nan" properly.
if (STRNICMP(text, "inf", 3) == 0)
{
*value = INFINITY;
return 3;
}
if (STRNICMP(text, "-inf", 3) == 0)
{
*value = -INFINITY;
return 4;
}
if (STRNICMP(text, "nan", 3) == 0)
{
*value = NAN;
return 3;
}
f = strtod(s, &s);
*value = f;
return (int)((char_u *)s - text);
}
#endif
/*
* Convert the specified byte index of line 'lnum' in buffer 'buf' to a
* character index. Works only for loaded buffers. Returns -1 on failure.
* The index of the first byte and the first character is zero.
*/
int
buf_byteidx_to_charidx(buf_T *buf, int lnum, int byteidx)
{
char_u *str;
char_u *t;
int count;
if (buf == NULL || buf->b_ml.ml_mfp == NULL)
return -1;
if (lnum > buf->b_ml.ml_line_count)
lnum = buf->b_ml.ml_line_count;
str = ml_get_buf(buf, lnum, FALSE);
if (str == NULL)
return -1;
if (*str == NUL)
return 0;
// count the number of characters
t = str;
for (count = 0; *t != NUL && t <= str + byteidx; count++)
t += mb_ptr2len(t);
// In insert mode, when the cursor is at the end of a non-empty line,
// byteidx points to the NUL character immediately past the end of the
// string. In this case, add one to the character count.
if (*t == NUL && byteidx != 0 && t == str + byteidx)
count++;
return count - 1;
}
/*
* Convert the specified character index of line 'lnum' in buffer 'buf' to a
* byte index. Works only for loaded buffers. Returns -1 on failure.
* The index of the first byte and the first character is zero.
*/
int
buf_charidx_to_byteidx(buf_T *buf, int lnum, int charidx)
{
char_u *str;
char_u *t;
if (buf == NULL || buf->b_ml.ml_mfp == NULL)
return -1;
if (lnum > buf->b_ml.ml_line_count)
lnum = buf->b_ml.ml_line_count;
str = ml_get_buf(buf, lnum, FALSE);
if (str == NULL)
return -1;
// Convert the character offset to a byte offset
t = str;
while (*t != NUL && --charidx > 0)
t += mb_ptr2len(t);
return t - str;
}
/*
* Translate a String variable into a position.
* Returns NULL when there is an error.
*/
pos_T *
var2fpos(
typval_T *varp,
int dollar_lnum, // TRUE when $ is last line
int *fnum, // set to fnum for '0, 'A, etc.
int charcol) // return character column
{
char_u *name;
static pos_T pos;
pos_T *pp;
// Argument can be [lnum, col, coladd].
if (varp->v_type == VAR_LIST)
{
list_T *l;
int len;
int error = FALSE;
listitem_T *li;
l = varp->vval.v_list;
if (l == NULL)
return NULL;
// Get the line number
pos.lnum = list_find_nr(l, 0L, &error);
if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
return NULL; // invalid line number
if (charcol)
len = (long)mb_charlen(ml_get(pos.lnum));
else
len = (long)STRLEN(ml_get(pos.lnum));
// Get the column number
// We accept "$" for the column number: last column.
li = list_find(l, 1L);
if (li != NULL && li->li_tv.v_type == VAR_STRING
&& li->li_tv.vval.v_string != NULL
&& STRCMP(li->li_tv.vval.v_string, "$") == 0)
{
pos.col = len + 1;
}
else
{
pos.col = list_find_nr(l, 1L, &error);
if (error)
return NULL;
}
// Accept a position up to the NUL after the line.
if (pos.col == 0 || (int)pos.col > len + 1)
return NULL; // invalid column number
--pos.col;
// Get the virtual offset. Defaults to zero.
pos.coladd = list_find_nr(l, 2L, &error);
if (error)
pos.coladd = 0;
return &pos;
}
name = tv_get_string_chk(varp);
if (name == NULL)
return NULL;
if (name[0] == '.') // cursor
{
pos = curwin->w_cursor;
if (charcol)
pos.col = buf_byteidx_to_charidx(curbuf, pos.lnum, pos.col);
return &pos;
}
if (name[0] == 'v' && name[1] == NUL) // Visual start
{
if (VIsual_active)
pos = VIsual;
else
pos = curwin->w_cursor;
if (charcol)
pos.col = buf_byteidx_to_charidx(curbuf, pos.lnum, pos.col);
return &pos;
}
if (name[0] == '\'') // mark
{
pp = getmark_buf_fnum(curbuf, name[1], FALSE, fnum);
if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
return NULL;
if (charcol)
pp->col = buf_byteidx_to_charidx(curbuf, pp->lnum, pp->col);
return pp;
}
pos.coladd = 0;
if (name[0] == 'w' && dollar_lnum)
{
pos.col = 0;
if (name[1] == '0') // "w0": first visible line
{
update_topline();
// In silent Ex mode topline is zero, but that's not a valid line
// number; use one instead.
pos.lnum = curwin->w_topline > 0 ? curwin->w_topline : 1;
return &pos;
}
else if (name[1] == '$') // "w$": last visible line
{
validate_botline();
// In silent Ex mode botline is zero, return zero then.
pos.lnum = curwin->w_botline > 0 ? curwin->w_botline - 1 : 0;
return &pos;
}
}
else if (name[0] == '$') // last column or line
{
if (dollar_lnum)
{
pos.lnum = curbuf->b_ml.ml_line_count;
pos.col = 0;
}
else
{
pos.lnum = curwin->w_cursor.lnum;
if (charcol)
pos.col = (colnr_T)mb_charlen(ml_get_curline());
else
pos.col = (colnr_T)STRLEN(ml_get_curline());
}
return &pos;
}
return NULL;
}
/*
* Convert list in "arg" into a position and optional file number.
* When "fnump" is NULL there is no file number, only 3 items.
* Note that the column is passed on as-is, the caller may want to decrement
* it to use 1 for the first column.
* Return FAIL when conversion is not possible, doesn't check the position for
* validity.
*/
int
list2fpos(
typval_T *arg,
pos_T *posp,
int *fnump,
colnr_T *curswantp,
int charcol)
{
list_T *l = arg->vval.v_list;
long i = 0;
long n;
// List must be: [fnum, lnum, col, coladd, curswant], where "fnum" is only
// there when "fnump" isn't NULL; "coladd" and "curswant" are optional.
if (arg->v_type != VAR_LIST
|| l == NULL
|| l->lv_len < (fnump == NULL ? 2 : 3)
|| l->lv_len > (fnump == NULL ? 4 : 5))
return FAIL;
if (fnump != NULL)
{
n = list_find_nr(l, i++, NULL); // fnum
if (n < 0)
return FAIL;
if (n == 0)
n = curbuf->b_fnum; // current buffer
*fnump = n;
}
n = list_find_nr(l, i++, NULL); // lnum
if (n < 0)
return FAIL;
posp->lnum = n;
n = list_find_nr(l, i++, NULL); // col
if (n < 0)
return FAIL;
// If character position is specified, then convert to byte position
if (charcol)
{
buf_T *buf;
// Get the text for the specified line in a loaded buffer
buf = buflist_findnr(fnump == NULL ? curbuf->b_fnum : *fnump);
if (buf == NULL || buf->b_ml.ml_mfp == NULL)
return FAIL;
n = buf_charidx_to_byteidx(buf, posp->lnum, n) + 1;
}
posp->col = n;
n = list_find_nr(l, i, NULL); // off
if (n < 0)
posp->coladd = 0;
else
posp->coladd = n;
if (curswantp != NULL)
*curswantp = list_find_nr(l, i + 1, NULL); // curswant
return OK;
}
/*
* Get the length of an environment variable name.
* Advance "arg" to the first character after the name.
* Return 0 for error.
*/
int
get_env_len(char_u **arg)
{
char_u *p;
int len;
for (p = *arg; vim_isIDc(*p); ++p)
;
if (p == *arg) // no name found
return 0;
len = (int)(p - *arg);
*arg = p;
return len;
}
/*
* Get the length of the name of a function or internal variable.
* "arg" is advanced to after the name.
* Return 0 if something is wrong.
*/
int
get_id_len(char_u **arg)
{
char_u *p;
int len;
// Find the end of the name.
for (p = *arg; eval_isnamec(*p); ++p)
{
if (*p == ':')
{
// "s:" is start of "s:var", but "n:" is not and can be used in
// slice "[n:]". Also "xx:" is not a namespace.
len = (int)(p - *arg);
if ((len == 1 && vim_strchr(NAMESPACE_CHAR, **arg) == NULL)
|| len > 1)
break;
}
}
if (p == *arg) // no name found
return 0;
len = (int)(p - *arg);
*arg = p;
return len;
}
/*
* Get the length of the name of a variable or function.
* Only the name is recognized, does not handle ".key" or "[idx]".
* "arg" is advanced to the first non-white character after the name.
* Return -1 if curly braces expansion failed.
* Return 0 if something else is wrong.
* If the name contains 'magic' {}'s, expand them and return the
* expanded name in an allocated string via 'alias' - caller must free.
*/
int
get_name_len(
char_u **arg,
char_u **alias,
int evaluate,
int verbose)
{
int len;
char_u *p;
char_u *expr_start;
char_u *expr_end;
*alias = NULL; // default to no alias
if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
&& (*arg)[2] == (int)KE_SNR)
{
// hard coded <SNR>, already translated
*arg += 3;
return get_id_len(arg) + 3;
}
len = eval_fname_script(*arg);
if (len > 0)
{
// literal "<SID>", "s:" or "<SNR>"
*arg += len;
}
/*
* Find the end of the name; check for {} construction.
*/
p = find_name_end(*arg, &expr_start, &expr_end,
len > 0 ? 0 : FNE_CHECK_START);
if (expr_start != NULL)
{
char_u *temp_string;
if (!evaluate)
{
len += (int)(p - *arg);
*arg = skipwhite(p);
return len;
}
/*
* Include any <SID> etc in the expanded string:
* Thus the -len here.
*/
temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
if (temp_string == NULL)
return -1;
*alias = temp_string;
*arg = skipwhite(p);
return (int)STRLEN(temp_string);
}
len += get_id_len(arg);
// Only give an error when there is something, otherwise it will be
// reported at a higher level.
if (len == 0 && verbose && **arg != NUL)
semsg(_(e_invexpr2), *arg);
return len;
}
/*
* Find the end of a variable or function name, taking care of magic braces.
* If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
* start and end of the first magic braces item.
* "flags" can have FNE_INCL_BR and FNE_CHECK_START.
* Return a pointer to just after the name. Equal to "arg" if there is no
* valid name.
*/
char_u *
find_name_end(
char_u *arg,
char_u **expr_start,
char_u **expr_end,
int flags)
{
int mb_nest = 0;
int br_nest = 0;
char_u *p;
int len;
int vim9script = in_vim9script();
if (expr_start != NULL)
{
*expr_start = NULL;
*expr_end = NULL;
}
// Quick check for valid starting character.
if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg)
&& (*arg != '{' || vim9script))
return arg;
for (p = arg; *p != NUL
&& (eval_isnamec(*p)
|| (*p == '{' && !vim9script)
|| ((flags & FNE_INCL_BR) && (*p == '['
|| (*p == '.' && eval_isdictc(p[1]))))
|| mb_nest != 0
|| br_nest != 0); MB_PTR_ADV(p))
{
if (*p == '\'')
{
// skip over 'string' to avoid counting [ and ] inside it.
for (p = p + 1; *p != NUL && *p != '\''; MB_PTR_ADV(p))
;
if (*p == NUL)
break;
}
else if (*p == '"')
{
// skip over "str\"ing" to avoid counting [ and ] inside it.
for (p = p + 1; *p != NUL && *p != '"'; MB_PTR_ADV(p))
if (*p == '\\' && p[1] != NUL)
++p;
if (*p == NUL)
break;
}
else if (br_nest == 0 && mb_nest == 0 && *p == ':')
{
// "s:" is start of "s:var", but "n:" is not and can be used in
// slice "[n:]". Also "xx:" is not a namespace. But {ns}: is.
len = (int)(p - arg);
if ((len == 1 && vim_strchr(NAMESPACE_CHAR, *arg) == NULL)
|| (len > 1 && p[-1] != '}'))
break;
}
if (mb_nest == 0)
{
if (*p == '[')
++br_nest;
else if (*p == ']')
--br_nest;
}
if (br_nest == 0 && !vim9script)
{
if (*p == '{')
{
mb_nest++;
if (expr_start != NULL && *expr_start == NULL)
*expr_start = p;
}
else if (*p == '}')
{
mb_nest--;
if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
*expr_end = p;
}
}
}
return p;
}
/*
* Expands out the 'magic' {}'s in a variable/function name.
* Note that this can call itself recursively, to deal with
* constructs like foo{bar}{baz}{bam}
* The four pointer arguments point to "foo{expre}ss{ion}bar"
* "in_start" ^
* "expr_start" ^
* "expr_end" ^
* "in_end" ^
*
* Returns a new allocated string, which the caller must free.
* Returns NULL for failure.
*/
static char_u *
make_expanded_name(
char_u *in_start,
char_u *expr_start,
char_u *expr_end,
char_u *in_end)
{
char_u c1;
char_u *retval = NULL;
char_u *temp_result;
if (expr_end == NULL || in_end == NULL)
return NULL;
*expr_start = NUL;
*expr_end = NUL;
c1 = *in_end;
*in_end = NUL;
temp_result = eval_to_string(expr_start + 1, FALSE);
if (temp_result != NULL)
{
retval = alloc(STRLEN(temp_result) + (expr_start - in_start)
+ (in_end - expr_end) + 1);
if (retval != NULL)
{
STRCPY(retval, in_start);
STRCAT(retval, temp_result);
STRCAT(retval, expr_end + 1);
}
}
vim_free(temp_result);
*in_end = c1; // put char back for error messages
*expr_start = '{';
*expr_end = '}';
if (retval != NULL)
{
temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
if (expr_start != NULL)
{
// Further expansion!
temp_result = make_expanded_name(retval, expr_start,
expr_end, temp_result);
vim_free(retval);
retval = temp_result;
}
}
return retval;
}
/*
* Return TRUE if character "c" can be used in a variable or function name.
* Does not include '{' or '}' for magic braces.
*/
int
eval_isnamec(int c)
{
return ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR;
}
/*
* Return TRUE if character "c" can be used as the first character in a
* variable or function name (excluding '{' and '}').
*/
int
eval_isnamec1(int c)
{
return ASCII_ISALPHA(c) || c == '_';
}
/*
* Return TRUE if character "c" can be used as the first character of a
* dictionary key.
*/
int
eval_isdictc(int c)
{
return ASCII_ISALNUM(c) || c == '_';
}
/*
* Handle:
* - expr[expr], expr[expr:expr] subscript
* - ".name" lookup
* - function call with Funcref variable: func(expr)
* - method call: var->method()
*
* Can all be combined in any order: dict.func(expr)[idx]['func'](expr)->len()
*/
int
handle_subscript(
char_u **arg,
typval_T *rettv,
evalarg_T *evalarg,
int verbose) // give error messages
{
int evaluate = evalarg != NULL
&& (evalarg->eval_flags & EVAL_EVALUATE);
int ret = OK;
dict_T *selfdict = NULL;
int check_white = TRUE;
int getnext;
char_u *p;
while (ret == OK)
{
// When at the end of the line and ".name" or "->{" or "->X" follows in
// the next line then consume the line break.
p = eval_next_non_blank(*arg, evalarg, &getnext);
if (getnext
&& ((rettv->v_type == VAR_DICT && *p == '.' && eval_isdictc(p[1]))
|| (p[0] == '-' && p[1] == '>'
&& (p[2] == '{' || ASCII_ISALPHA(p[2])))))
{
*arg = eval_next_line(evalarg);
p = *arg;
check_white = FALSE;
}
if ((**arg == '(' && (!evaluate || rettv->v_type == VAR_FUNC
|| rettv->v_type == VAR_PARTIAL))
&& (!check_white || !VIM_ISWHITE(*(*arg - 1))))
{
ret = call_func_rettv(arg, evalarg, rettv, evaluate,
selfdict, NULL);
// Stop the expression evaluation when immediately aborting on
// error, or when an interrupt occurred or an exception was thrown
// but not caught.
if (aborting())
{
if (ret == OK)
clear_tv(rettv);
ret = FAIL;
}
dict_unref(selfdict);
selfdict = NULL;
}
else if (p[0] == '-' && p[1] == '>')
{
*arg = skipwhite(p + 2);
if (ret == OK)
{
if ((**arg == '{' && !in_vim9script()) || **arg == '(')
// expr->{lambda}() or expr->(lambda)()
ret = eval_lambda(arg, rettv, evalarg, verbose);
else
// expr->name()
ret = eval_method(arg, rettv, evalarg, verbose);
}
}
// "." is ".name" lookup when we found a dict or when evaluating and
// scriptversion is at least 2, where string concatenation is "..".
else if (**arg == '['
|| (**arg == '.' && (rettv->v_type == VAR_DICT
|| (!evaluate
&& (*arg)[1] != '.'
&& current_sctx.sc_version >= 2))))
{
dict_unref(selfdict);
if (rettv->v_type == VAR_DICT)
{
selfdict = rettv->vval.v_dict;
if (selfdict != NULL)
++selfdict->dv_refcount;
}
else
selfdict = NULL;
if (eval_index(arg, rettv, evalarg, verbose) == FAIL)
{
clear_tv(rettv);
ret = FAIL;
}
}
else
break;
}
// Turn "dict.Func" into a partial for "Func" bound to "dict".
// Don't do this when "Func" is already a partial that was bound
// explicitly (pt_auto is FALSE).
if (selfdict != NULL
&& (rettv->v_type == VAR_FUNC
|| (rettv->v_type == VAR_PARTIAL
&& (rettv->vval.v_partial->pt_auto
|| rettv->vval.v_partial->pt_dict == NULL))))
selfdict = make_partial(selfdict, rettv);
dict_unref(selfdict);
return ret;
}
/*
* Make a copy of an item.
* Lists and Dictionaries are also copied. A deep copy if "deep" is set.
* For deepcopy() "copyID" is zero for a full copy or the ID for when a
* reference to an already copied list/dict can be used.
* Returns FAIL or OK.
*/
int
item_copy(
typval_T *from,
typval_T *to,
int deep,
int copyID)
{
static int recurse = 0;
int ret = OK;
if (recurse >= DICT_MAXNEST)
{
emsg(_("E698: variable nested too deep for making a copy"));
return FAIL;
}
++recurse;
switch (from->v_type)
{
case VAR_NUMBER:
case VAR_FLOAT:
case VAR_STRING:
case VAR_FUNC:
case VAR_PARTIAL:
case VAR_BOOL:
case VAR_SPECIAL:
case VAR_JOB:
case VAR_CHANNEL:
copy_tv(from, to);
break;
case VAR_LIST:
to->v_type = VAR_LIST;
to->v_lock = 0;
if (from->vval.v_list == NULL)
to->vval.v_list = NULL;
else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
{
// use the copy made earlier
to->vval.v_list = from->vval.v_list->lv_copylist;
++to->vval.v_list->lv_refcount;
}
else
to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
if (to->vval.v_list == NULL)
ret = FAIL;
break;
case VAR_BLOB:
ret = blob_copy(from->vval.v_blob, to);
break;
case VAR_DICT:
to->v_type = VAR_DICT;
to->v_lock = 0;
if (from->vval.v_dict == NULL)
to->vval.v_dict = NULL;
else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
{
// use the copy made earlier
to->vval.v_dict = from->vval.v_dict->dv_copydict;
++to->vval.v_dict->dv_refcount;
}
else
to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
if (to->vval.v_dict == NULL)
ret = FAIL;
break;
case VAR_UNKNOWN:
case VAR_ANY:
case VAR_VOID:
internal_error_no_abort("item_copy(UNKNOWN)");
ret = FAIL;
}
--recurse;
return ret;
}
void
echo_one(typval_T *rettv, int with_space, int *atstart, int *needclr)
{
char_u *tofree;
char_u numbuf[NUMBUFLEN];
char_u *p = echo_string(rettv, &tofree, numbuf, get_copyID());
if (*atstart)
{
*atstart = FALSE;
// Call msg_start() after eval1(), evaluating the expression
// may cause a message to appear.
if (with_space)
{
// Mark the saved text as finishing the line, so that what
// follows is displayed on a new line when scrolling back
// at the more prompt.
msg_sb_eol();
msg_start();
}
}
else if (with_space)
msg_puts_attr(" ", echo_attr);
if (p != NULL)
for ( ; *p != NUL && !got_int; ++p)
{
if (*p == '\n' || *p == '\r' || *p == TAB)
{
if (*p != TAB && *needclr)
{
// remove any text still there from the command
msg_clr_eos();
*needclr = FALSE;
}
msg_putchar_attr(*p, echo_attr);
}
else
{
if (has_mbyte)
{
int i = (*mb_ptr2len)(p);
(void)msg_outtrans_len_attr(p, i, echo_attr);
p += i - 1;
}
else
(void)msg_outtrans_len_attr(p, 1, echo_attr);
}
}
vim_free(tofree);
}
/*
* ":echo expr1 ..." print each argument separated with a space, add a
* newline at the end.
* ":echon expr1 ..." print each argument plain.
*/
void
ex_echo(exarg_T *eap)
{
char_u *arg = eap->arg;
typval_T rettv;
char_u *p;
int needclr = TRUE;
int atstart = TRUE;
int did_emsg_before = did_emsg;
int called_emsg_before = called_emsg;
evalarg_T evalarg;
fill_evalarg_from_eap(&evalarg, eap, eap->skip);
if (eap->skip)
++emsg_skip;
while ((!ends_excmd2(eap->cmd, arg) || *arg == '"') && !got_int)
{
// If eval1() causes an error message the text from the command may
// still need to be cleared. E.g., "echo 22,44".
need_clr_eos = needclr;
p = arg;
if (eval1(&arg, &rettv, &evalarg) == FAIL)
{
/*
* Report the invalid expression unless the expression evaluation
* has been cancelled due to an aborting error, an interrupt, or an
* exception.
*/
if (!aborting() && did_emsg == did_emsg_before
&& called_emsg == called_emsg_before)
semsg(_(e_invexpr2), p);
need_clr_eos = FALSE;
break;
}
need_clr_eos = FALSE;
if (!eap->skip)
echo_one(&rettv, eap->cmdidx == CMD_echo, &atstart, &needclr);
clear_tv(&rettv);
arg = skipwhite(arg);
}
eap->nextcmd = check_nextcmd(arg);
clear_evalarg(&evalarg, eap);
if (eap->skip)
--emsg_skip;
else
{
// remove text that may still be there from the command
if (needclr)
msg_clr_eos();
if (eap->cmdidx == CMD_echo)
msg_end();
}
}
/*
* ":echohl {name}".
*/
void
ex_echohl(exarg_T *eap)
{
echo_attr = syn_name2attr(eap->arg);
}
/*
* Returns the :echo attribute
*/
int
get_echo_attr(void)
{
return echo_attr;
}
/*
* ":execute expr1 ..." execute the result of an expression.
* ":echomsg expr1 ..." Print a message
* ":echoerr expr1 ..." Print an error
* Each gets spaces around each argument and a newline at the end for
* echo commands
*/
void
ex_execute(exarg_T *eap)
{
char_u *arg = eap->arg;
typval_T rettv;
int ret = OK;
char_u *p;
garray_T ga;
int len;
ga_init2(&ga, 1, 80);
if (eap->skip)
++emsg_skip;
while (!ends_excmd2(eap->cmd, arg) || *arg == '"')
{
ret = eval1_emsg(&arg, &rettv, eap);
if (ret == FAIL)
break;
if (!eap->skip)
{
char_u buf[NUMBUFLEN];
if (eap->cmdidx == CMD_execute)
{
if (rettv.v_type == VAR_CHANNEL || rettv.v_type == VAR_JOB)
{
emsg(_(e_inval_string));
p = NULL;
}
else
p = tv_get_string_buf(&rettv, buf);
}
else
p = tv_stringify(&rettv, buf);
if (p == NULL)
{
clear_tv(&rettv);
ret = FAIL;
break;
}
len = (int)STRLEN(p);
if (ga_grow(&ga, len + 2) == FAIL)
{
clear_tv(&rettv);
ret = FAIL;
break;
}
if (ga.ga_len)
((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
ga.ga_len += len;
}
clear_tv(&rettv);
arg = skipwhite(arg);
}
if (ret != FAIL && ga.ga_data != NULL)
{
if (eap->cmdidx == CMD_echomsg || eap->cmdidx == CMD_echoerr)
{
// Mark the already saved text as finishing the line, so that what
// follows is displayed on a new line when scrolling back at the
// more prompt.
msg_sb_eol();
}
if (eap->cmdidx == CMD_echomsg)
{
msg_attr(ga.ga_data, echo_attr);
out_flush();
}
else if (eap->cmdidx == CMD_echoerr)
{
int save_did_emsg = did_emsg;
// We don't want to abort following commands, restore did_emsg.
emsg(ga.ga_data);
if (!force_abort)
did_emsg = save_did_emsg;
}
else if (eap->cmdidx == CMD_execute)
do_cmdline((char_u *)ga.ga_data,
eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
}
ga_clear(&ga);
if (eap->skip)
--emsg_skip;
eap->nextcmd = check_nextcmd(arg);
}
/*
* Skip over the name of an option: "&option", "&g:option" or "&l:option".
* "arg" points to the "&" or '+' when called, to "option" when returning.
* Returns NULL when no option name found. Otherwise pointer to the char
* after the option name.
*/
char_u *
find_option_end(char_u **arg, int *opt_flags)
{
char_u *p = *arg;
++p;
if (*p == 'g' && p[1] == ':')
{
*opt_flags = OPT_GLOBAL;
p += 2;
}
else if (*p == 'l' && p[1] == ':')
{
*opt_flags = OPT_LOCAL;
p += 2;
}
else
*opt_flags = 0;
if (!ASCII_ISALPHA(*p))
return NULL;
*arg = p;
if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
p += 4; // termcap option
else
while (ASCII_ISALPHA(*p))
++p;
return p;
}
/*
* Display script name where an item was last set.
* Should only be invoked when 'verbose' is non-zero.
*/
void
last_set_msg(sctx_T script_ctx)
{
char_u *p;
if (script_ctx.sc_sid != 0)
{
p = home_replace_save(NULL, get_scriptname(script_ctx.sc_sid));
if (p != NULL)
{
verbose_enter();
msg_puts(_("\n\tLast set from "));
msg_puts((char *)p);
if (script_ctx.sc_lnum > 0)
{
msg_puts(_(line_msg));
msg_outnum((long)script_ctx.sc_lnum);
}
verbose_leave();
vim_free(p);
}
}
}
#endif // FEAT_EVAL
/*
* Perform a substitution on "str" with pattern "pat" and substitute "sub".
* When "sub" is NULL "expr" is used, must be a VAR_FUNC or VAR_PARTIAL.
* "flags" can be "g" to do a global substitute.
* Returns an allocated string, NULL for error.
*/
char_u *
do_string_sub(
char_u *str,
char_u *pat,
char_u *sub,
typval_T *expr,
char_u *flags)
{
int sublen;
regmatch_T regmatch;
int i;
int do_all;
char_u *tail;
char_u *end;
garray_T ga;
char_u *ret;
char_u *save_cpo;
char_u *zero_width = NULL;
// Make 'cpoptions' empty, so that the 'l' flag doesn't work here
save_cpo = p_cpo;
p_cpo = empty_option;
ga_init2(&ga, 1, 200);
do_all = (flags[0] == 'g');
regmatch.rm_ic = p_ic;
regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
if (regmatch.regprog != NULL)
{
tail = str;
end = str + STRLEN(str);
while (vim_regexec_nl(®match, str, (colnr_T)(tail - str)))
{
// Skip empty match except for first match.
if (regmatch.startp[0] == regmatch.endp[0])
{
if (zero_width == regmatch.startp[0])
{
// avoid getting stuck on a match with an empty string
i = mb_ptr2len(tail);
mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail,
(size_t)i);
ga.ga_len += i;
tail += i;
continue;
}
zero_width = regmatch.startp[0];
}
/*
* Get some space for a temporary buffer to do the substitution
* into. It will contain:
* - The text up to where the match is.
* - The substituted text.
* - The text after the match.
*/
sublen = vim_regsub(®match, sub, expr, tail, FALSE, TRUE, FALSE);
if (ga_grow(&ga, (int)((end - tail) + sublen -
(regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
{
ga_clear(&ga);
break;
}
// copy the text up to where the match is
i = (int)(regmatch.startp[0] - tail);
mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
// add the substituted text
(void)vim_regsub(®match, sub, expr, (char_u *)ga.ga_data
+ ga.ga_len + i, TRUE, TRUE, FALSE);
ga.ga_len += i + sublen - 1;
tail = regmatch.endp[0];
if (*tail == NUL)
break;
if (!do_all)
break;
}
if (ga.ga_data != NULL)
STRCPY((char *)ga.ga_data + ga.ga_len, tail);
vim_regfree(regmatch.regprog);
}
ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
ga_clear(&ga);
if (p_cpo == empty_option)
p_cpo = save_cpo;
else
{
// Darn, evaluating {sub} expression or {expr} changed the value.
// If it's still empty it was changed and restored, need to restore in
// the complicated way.
if (*p_cpo == NUL)
set_option_value((char_u *)"cpo", 0L, save_cpo, 0);
free_string_option(save_cpo);
}
return ret;
}
|
279035.c | /* NOCW */
/*
Please read the README file for condition of use, before
using this software.
Maurice Gittens <[email protected]> January 1997
*/
#include <unistd.h>
#include <stdio.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <strings.h>
#include <stdlib.h>
#include <openssl/rsa.h>
#include <openssl/evp.h>
#include <openssl/objects.h>
#include <openssl/x509.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/ssl.h>
#include "loadkeys.h"
#define PUBFILE "cert.pem"
#define PRIVFILE "privkey.pem"
#define STDIN 0
#define STDOUT 1
void main_encrypt(void);
void main_decrypt(void);
static const char *usage = "Usage: example1 [-d]\n";
int main(int argc, char *argv[])
{
ERR_load_crypto_strings();
if ((argc == 1))
{
main_encrypt();
}
else if ((argc == 2) && !strcmp(argv[1],"-d"))
{
main_decrypt();
}
else
{
printf("%s",usage);
exit(1);
}
return 0;
}
void main_encrypt(void)
{
unsigned int ebuflen;
EVP_CIPHER_CTX ectx;
unsigned char iv[EVP_MAX_IV_LENGTH];
unsigned char *ekey[1];
int readlen;
int ekeylen, net_ekeylen;
EVP_PKEY *pubKey[1];
char buf[512];
char ebuf[512];
memset(iv, '\0', sizeof(iv));
pubKey[0] = ReadPublicKey(PUBFILE);
if(!pubKey[0])
{
fprintf(stderr,"Error: can't load public key");
exit(1);
}
ekey[0] = malloc(EVP_PKEY_size(pubKey[0]));
if (!ekey[0])
{
EVP_PKEY_free(pubKey[0]);
perror("malloc");
exit(1);
}
EVP_SealInit(&ectx,
EVP_des_ede3_cbc(),
ekey,
&ekeylen,
iv,
pubKey,
1);
net_ekeylen = htonl(ekeylen);
write(STDOUT, (char*)&net_ekeylen, sizeof(net_ekeylen));
write(STDOUT, ekey[0], ekeylen);
write(STDOUT, iv, sizeof(iv));
while(1)
{
readlen = read(STDIN, buf, sizeof(buf));
if (readlen <= 0)
{
if (readlen < 0)
perror("read");
break;
}
EVP_SealUpdate(&ectx, ebuf, &ebuflen, buf, readlen);
write(STDOUT, ebuf, ebuflen);
}
EVP_SealFinal(&ectx, ebuf, &ebuflen);
write(STDOUT, ebuf, ebuflen);
EVP_PKEY_free(pubKey[0]);
free(ekey[0]);
}
void main_decrypt(void)
{
char buf[520];
char ebuf[512];
unsigned int buflen;
EVP_CIPHER_CTX ectx;
unsigned char iv[EVP_MAX_IV_LENGTH];
unsigned char *encryptKey;
unsigned int ekeylen;
EVP_PKEY *privateKey;
memset(iv, '\0', sizeof(iv));
privateKey = ReadPrivateKey(PRIVFILE);
if (!privateKey)
{
fprintf(stderr, "Error: can't load private key");
exit(1);
}
read(STDIN, &ekeylen, sizeof(ekeylen));
ekeylen = ntohl(ekeylen);
if (ekeylen != EVP_PKEY_size(privateKey))
{
EVP_PKEY_free(privateKey);
fprintf(stderr, "keylength mismatch");
exit(1);
}
encryptKey = malloc(sizeof(char) * ekeylen);
if (!encryptKey)
{
EVP_PKEY_free(privateKey);
perror("malloc");
exit(1);
}
read(STDIN, encryptKey, ekeylen);
read(STDIN, iv, sizeof(iv));
EVP_OpenInit(&ectx,
EVP_des_ede3_cbc(),
encryptKey,
ekeylen,
iv,
privateKey);
while(1)
{
int readlen = read(STDIN, ebuf, sizeof(ebuf));
if (readlen <= 0)
{
if (readlen < 0)
perror("read");
break;
}
EVP_OpenUpdate(&ectx, buf, &buflen, ebuf, readlen);
write(STDOUT, buf, buflen);
}
EVP_OpenFinal(&ectx, buf, &buflen);
write(STDOUT, buf, buflen);
EVP_PKEY_free(privateKey);
free(encryptKey);
}
|
243662.c | /* Test of u8_width() function.
Copyright (C) 2007-2018 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 <https://www.gnu.org/licenses/>. */
/* Written by Bruno Haible <[email protected]>, 2007. */
#include <config.h>
#include "uniwidth.h"
#include "macros.h"
int
main ()
{
static const uint8_t input[] =
#define INPUT1_OFFSET 0
#define INPUT1_LENGTH 13
"Danilo \305\240egan"
#define INPUT2_OFFSET 13
#define INPUT2_LENGTH 14
"Danilo S\314\214egan"
#define INPUT3_OFFSET 27
#define INPUT3_LENGTH 23
"\320\224\320\260\320\275\320\270\320\273\320\276 \320\250\320\265\320\263\320\260\320\275"
#define INPUT4_OFFSET 50
#define INPUT4_LENGTH 9
"\345\210\230\345\206\233\346\260\221"
;
{ /* "Danilo Šegan" */
ASSERT (u8_width (input + INPUT1_OFFSET, INPUT1_LENGTH, "UTF-8") == 12);
}
{ /* "Danilo Šegan" decomposed */
ASSERT (u8_width (input + INPUT2_OFFSET, INPUT2_LENGTH, "UTF-8") == 12);
}
{ /* "Данило Шеган" */
ASSERT (u8_width (input + INPUT3_OFFSET, INPUT3_LENGTH, "UTF-8") == 12);
ASSERT (u8_width (input + INPUT3_OFFSET, INPUT3_LENGTH, "EUC-JP") == 23);
}
{ /* 刘军民 */
ASSERT (u8_width (input + INPUT4_OFFSET, INPUT4_LENGTH, "UTF-8") == 6);
ASSERT (u8_width (input + INPUT4_OFFSET, INPUT4_LENGTH, "GB2312") == 6);
}
return 0;
}
|
264124.c | /*
* mididrv.c - mididrv.c wrapper for the SDL UI.
*
* Written by
* Marco van den Heuvel <[email protected]>
*
* This file is part of VICE, the Versatile Commodore Emulator.
* See README for copyright notice.
*
* 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 "vice.h"
#ifdef HAVE_MIDI
#if defined(UNIX_COMPILE) && !defined(MACOSX_SUPPORT)
#include "../unix/mididrv.c"
#endif
#if defined(MACOSX_SUPPORT)
#include "../unix/macosx/mididrv.c"
#endif
#if defined(WIN32_COMPILE) && !defined(__XBOX__)
#include "../win32/mididrv.c"
#endif
#endif
|
622408.c | /* $Id: isdigit.c 506 2010-12-29 13:19:53Z solar $ */
/* isdigit( int )
This file is part of the Public Domain C Library (PDCLib).
Permission is granted to use, modify, and / or redistribute at will.
*/
#include <ctype.h>
#ifndef REGTEST
#include <locale.h>
int isdigit( int c )
{
return ( _PDCLIB_lconv.ctype[c].flags & _PDCLIB_CTYPE_DIGIT );
}
#endif
#ifdef TEST
#include <_PDCLIB_test.h>
int main( void )
{
TESTCASE( isdigit( '0' ) );
TESTCASE( isdigit( '9' ) );
TESTCASE( ! isdigit( ' ' ) );
TESTCASE( ! isdigit( 'a' ) );
TESTCASE( ! isdigit( '@' ) );
return TEST_RESULTS;
}
#endif
|
483094.c | /* CTF format support.
Copyright (C) 2012-2020 Free Software Foundation, Inc.
Contributed by Hui Zhu <[email protected]>
Contributed by Yao Qi <[email protected]>
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 "tracectf.h"
#include "tracepoint.h"
#include "regcache.h"
#include <sys/stat.h>
#include "exec.h"
#include "completer.h"
#include "inferior.h"
#include "gdbthread.h"
#include "tracefile.h"
#include <ctype.h>
#include <algorithm>
#include "gdbsupport/filestuff.h"
#include "gdbarch.h"
/* The CTF target. */
static const target_info ctf_target_info = {
"ctf",
N_("CTF file"),
N_("(Use a CTF directory as a target.\n\
Specify the filename of the CTF directory.")
};
class ctf_target final : public tracefile_target
{
public:
const target_info &info () const override
{ return ctf_target_info; }
void close () override;
void fetch_registers (struct regcache *, int) override;
enum target_xfer_status xfer_partial (enum target_object object,
const char *annex,
gdb_byte *readbuf,
const gdb_byte *writebuf,
ULONGEST offset, ULONGEST len,
ULONGEST *xfered_len) override;
void files_info () override;
int trace_find (enum trace_find_type type, int num,
CORE_ADDR addr1, CORE_ADDR addr2, int *tpp) override;
bool get_trace_state_variable_value (int tsv, LONGEST *val) override;
traceframe_info_up traceframe_info () override;
};
/* GDB saves trace buffers and other information (such as trace
status) got from the remote target into Common Trace Format (CTF).
The following types of information are expected to save in CTF:
1. The length (in bytes) of register cache. Event "register" will
be defined in metadata, which includes the length.
2. Trace status. Event "status" is defined in metadata, which
includes all aspects of trace status.
3. Uploaded trace variables. Event "tsv_def" is defined in
metadata, which is about all aspects of a uploaded trace variable.
Uploaded tracepoints. Event "tp_def" is defined in meta, which
is about all aspects of an uploaded tracepoint. Note that the
"sequence" (a CTF type, which is a dynamically-sized array.) is
used for "actions" "step_actions" and "cmd_strings".
4. Trace frames. Each trace frame is composed by several blocks
of different types ('R', 'M', 'V'). One trace frame is saved in
one CTF packet and the blocks of this frame are saved as events.
4.1: The trace frame related information (such as the number of
tracepoint associated with this frame) is saved in the packet
context.
4.2: The block 'M', 'R' and 'V' are saved in event "memory",
"register" and "tsv" respectively.
4.3: When iterating over events, babeltrace can't tell iterator
goes to a new packet, so we need a marker or anchor to tell GDB
that iterator goes into a new packet or frame. We define event
"frame". */
#define CTF_MAGIC 0xC1FC1FC1
#define CTF_SAVE_MAJOR 1
#define CTF_SAVE_MINOR 8
#define CTF_METADATA_NAME "metadata"
#define CTF_DATASTREAM_NAME "datastream"
/* Reserved event id. */
#define CTF_EVENT_ID_REGISTER 0
#define CTF_EVENT_ID_TSV 1
#define CTF_EVENT_ID_MEMORY 2
#define CTF_EVENT_ID_FRAME 3
#define CTF_EVENT_ID_STATUS 4
#define CTF_EVENT_ID_TSV_DEF 5
#define CTF_EVENT_ID_TP_DEF 6
#define CTF_PID (2)
/* The state kept while writing the CTF datastream file. */
struct trace_write_handler
{
/* File descriptor of metadata. */
FILE *metadata_fd;
/* File descriptor of traceframes. */
FILE *datastream_fd;
/* This is the content size of the current packet. */
size_t content_size;
/* This is the start offset of current packet. */
long packet_start;
};
/* Write metadata in FORMAT. */
static void
ctf_save_write_metadata (struct trace_write_handler *handler,
const char *format, ...)
ATTRIBUTE_PRINTF (2, 3);
static void
ctf_save_write_metadata (struct trace_write_handler *handler,
const char *format, ...)
{
va_list args;
va_start (args, format);
if (vfprintf (handler->metadata_fd, format, args) < 0)
error (_("Unable to write metadata file (%s)"),
safe_strerror (errno));
va_end (args);
}
/* Write BUF of length SIZE to datastream file represented by
HANDLER. */
static int
ctf_save_write (struct trace_write_handler *handler,
const gdb_byte *buf, size_t size)
{
if (fwrite (buf, size, 1, handler->datastream_fd) != 1)
error (_("Unable to write file for saving trace data (%s)"),
safe_strerror (errno));
handler->content_size += size;
return 0;
}
/* Write a unsigned 32-bit integer to datastream file represented by
HANDLER. */
#define ctf_save_write_uint32(HANDLER, U32) \
ctf_save_write (HANDLER, (gdb_byte *) &U32, 4)
/* Write a signed 32-bit integer to datastream file represented by
HANDLER. */
#define ctf_save_write_int32(HANDLER, INT32) \
ctf_save_write ((HANDLER), (gdb_byte *) &(INT32), 4)
/* Set datastream file position. Update HANDLER->content_size
if WHENCE is SEEK_CUR. */
static int
ctf_save_fseek (struct trace_write_handler *handler, long offset,
int whence)
{
gdb_assert (whence != SEEK_END);
gdb_assert (whence != SEEK_SET
|| offset <= handler->content_size + handler->packet_start);
if (fseek (handler->datastream_fd, offset, whence))
error (_("Unable to seek file for saving trace data (%s)"),
safe_strerror (errno));
if (whence == SEEK_CUR)
handler->content_size += offset;
return 0;
}
/* Change the datastream file position to align on ALIGN_SIZE,
and write BUF to datastream file. The size of BUF is SIZE. */
static int
ctf_save_align_write (struct trace_write_handler *handler,
const gdb_byte *buf,
size_t size, size_t align_size)
{
long offset
= (align_up (handler->content_size, align_size)
- handler->content_size);
if (ctf_save_fseek (handler, offset, SEEK_CUR))
return -1;
if (ctf_save_write (handler, buf, size))
return -1;
return 0;
}
/* Write events to next new packet. */
static void
ctf_save_next_packet (struct trace_write_handler *handler)
{
handler->packet_start += (handler->content_size + 4);
ctf_save_fseek (handler, handler->packet_start, SEEK_SET);
handler->content_size = 0;
}
/* Write the CTF metadata header. */
static void
ctf_save_metadata_header (struct trace_write_handler *handler)
{
ctf_save_write_metadata (handler, "/* CTF %d.%d */\n",
CTF_SAVE_MAJOR, CTF_SAVE_MINOR);
ctf_save_write_metadata (handler,
"typealias integer { size = 8; align = 8; "
"signed = false; encoding = ascii;}"
" := ascii;\n");
ctf_save_write_metadata (handler,
"typealias integer { size = 8; align = 8; "
"signed = false; }"
" := uint8_t;\n");
ctf_save_write_metadata (handler,
"typealias integer { size = 16; align = 16;"
"signed = false; } := uint16_t;\n");
ctf_save_write_metadata (handler,
"typealias integer { size = 32; align = 32;"
"signed = false; } := uint32_t;\n");
ctf_save_write_metadata (handler,
"typealias integer { size = 64; align = 64;"
"signed = false; base = hex;}"
" := uint64_t;\n");
ctf_save_write_metadata (handler,
"typealias integer { size = 32; align = 32;"
"signed = true; } := int32_t;\n");
ctf_save_write_metadata (handler,
"typealias integer { size = 64; align = 64;"
"signed = true; } := int64_t;\n");
ctf_save_write_metadata (handler,
"typealias string { encoding = ascii;"
" } := chars;\n");
ctf_save_write_metadata (handler, "\n");
/* Get the byte order of the host and write CTF data in this byte
order. */
#if WORDS_BIGENDIAN
#define HOST_ENDIANNESS "be"
#else
#define HOST_ENDIANNESS "le"
#endif
ctf_save_write_metadata (handler,
"\ntrace {\n"
" major = %u;\n"
" minor = %u;\n"
" byte_order = %s;\n"
" packet.header := struct {\n"
" uint32_t magic;\n"
" };\n"
"};\n"
"\n"
"stream {\n"
" packet.context := struct {\n"
" uint32_t content_size;\n"
" uint32_t packet_size;\n"
" uint16_t tpnum;\n"
" };\n"
" event.header := struct {\n"
" uint32_t id;\n"
" };\n"
"};\n",
CTF_SAVE_MAJOR, CTF_SAVE_MINOR,
HOST_ENDIANNESS);
ctf_save_write_metadata (handler, "\n");
}
/* CTF trace writer. */
struct ctf_trace_file_writer
{
struct trace_file_writer base;
/* States related to writing CTF trace file. */
struct trace_write_handler tcs;
};
/* This is the implementation of trace_file_write_ops method
dtor. */
static void
ctf_dtor (struct trace_file_writer *self)
{
struct ctf_trace_file_writer *writer
= (struct ctf_trace_file_writer *) self;
if (writer->tcs.metadata_fd != NULL)
fclose (writer->tcs.metadata_fd);
if (writer->tcs.datastream_fd != NULL)
fclose (writer->tcs.datastream_fd);
}
/* This is the implementation of trace_file_write_ops method
target_save. */
static int
ctf_target_save (struct trace_file_writer *self,
const char *dirname)
{
/* Don't support save trace file to CTF format in the target. */
return 0;
}
/* This is the implementation of trace_file_write_ops method
start. It creates the directory DIRNAME, metadata and datastream
in the directory. */
static void
ctf_start (struct trace_file_writer *self, const char *dirname)
{
struct ctf_trace_file_writer *writer
= (struct ctf_trace_file_writer *) self;
mode_t hmode = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH;
/* Create DIRNAME. */
if (mkdir (dirname, hmode) && errno != EEXIST)
error (_("Unable to open directory '%s' for saving trace data (%s)"),
dirname, safe_strerror (errno));
memset (&writer->tcs, '\0', sizeof (writer->tcs));
std::string file_name = string_printf ("%s/%s", dirname, CTF_METADATA_NAME);
writer->tcs.metadata_fd
= gdb_fopen_cloexec (file_name.c_str (), "w").release ();
if (writer->tcs.metadata_fd == NULL)
error (_("Unable to open file '%s' for saving trace data (%s)"),
file_name.c_str (), safe_strerror (errno));
ctf_save_metadata_header (&writer->tcs);
file_name = string_printf ("%s/%s", dirname, CTF_DATASTREAM_NAME);
writer->tcs.datastream_fd
= gdb_fopen_cloexec (file_name.c_str (), "w").release ();
if (writer->tcs.datastream_fd == NULL)
error (_("Unable to open file '%s' for saving trace data (%s)"),
file_name.c_str (), safe_strerror (errno));
}
/* This is the implementation of trace_file_write_ops method
write_header. Write the types of events on trace variable and
frame. */
static void
ctf_write_header (struct trace_file_writer *self)
{
struct ctf_trace_file_writer *writer
= (struct ctf_trace_file_writer *) self;
ctf_save_write_metadata (&writer->tcs, "\n");
ctf_save_write_metadata (&writer->tcs,
"event {\n\tname = \"memory\";\n\tid = %u;\n"
"\tfields := struct { \n"
"\t\tuint64_t address;\n"
"\t\tuint16_t length;\n"
"\t\tuint8_t contents[length];\n"
"\t};\n"
"};\n", CTF_EVENT_ID_MEMORY);
ctf_save_write_metadata (&writer->tcs, "\n");
ctf_save_write_metadata (&writer->tcs,
"event {\n\tname = \"tsv\";\n\tid = %u;\n"
"\tfields := struct { \n"
"\t\tuint64_t val;\n"
"\t\tuint32_t num;\n"
"\t};\n"
"};\n", CTF_EVENT_ID_TSV);
ctf_save_write_metadata (&writer->tcs, "\n");
ctf_save_write_metadata (&writer->tcs,
"event {\n\tname = \"frame\";\n\tid = %u;\n"
"\tfields := struct { \n"
"\t};\n"
"};\n", CTF_EVENT_ID_FRAME);
ctf_save_write_metadata (&writer->tcs, "\n");
ctf_save_write_metadata (&writer->tcs,
"event {\n\tname = \"tsv_def\";\n"
"\tid = %u;\n\tfields := struct { \n"
"\t\tint64_t initial_value;\n"
"\t\tint32_t number;\n"
"\t\tint32_t builtin;\n"
"\t\tchars name;\n"
"\t};\n"
"};\n", CTF_EVENT_ID_TSV_DEF);
ctf_save_write_metadata (&writer->tcs, "\n");
ctf_save_write_metadata (&writer->tcs,
"event {\n\tname = \"tp_def\";\n"
"\tid = %u;\n\tfields := struct { \n"
"\t\tuint64_t addr;\n"
"\t\tuint64_t traceframe_usage;\n"
"\t\tint32_t number;\n"
"\t\tint32_t enabled;\n"
"\t\tint32_t step;\n"
"\t\tint32_t pass;\n"
"\t\tint32_t hit_count;\n"
"\t\tint32_t type;\n"
"\t\tchars cond;\n"
"\t\tuint32_t action_num;\n"
"\t\tchars actions[action_num];\n"
"\t\tuint32_t step_action_num;\n"
"\t\tchars step_actions[step_action_num];\n"
"\t\tchars at_string;\n"
"\t\tchars cond_string;\n"
"\t\tuint32_t cmd_num;\n"
"\t\tchars cmd_strings[cmd_num];\n"
"\t};\n"
"};\n", CTF_EVENT_ID_TP_DEF);
gdb_assert (writer->tcs.content_size == 0);
gdb_assert (writer->tcs.packet_start == 0);
/* Create a new packet to contain this event. */
self->ops->frame_ops->start (self, 0);
}
/* This is the implementation of trace_file_write_ops method
write_regblock_type. Write the type of register event in
metadata. */
static void
ctf_write_regblock_type (struct trace_file_writer *self, int size)
{
struct ctf_trace_file_writer *writer
= (struct ctf_trace_file_writer *) self;
ctf_save_write_metadata (&writer->tcs, "\n");
ctf_save_write_metadata (&writer->tcs,
"event {\n\tname = \"register\";\n\tid = %u;\n"
"\tfields := struct { \n"
"\t\tascii contents[%d];\n"
"\t};\n"
"};\n",
CTF_EVENT_ID_REGISTER, size);
}
/* This is the implementation of trace_file_write_ops method
write_status. */
static void
ctf_write_status (struct trace_file_writer *self,
struct trace_status *ts)
{
struct ctf_trace_file_writer *writer
= (struct ctf_trace_file_writer *) self;
uint32_t id;
ctf_save_write_metadata (&writer->tcs, "\n");
ctf_save_write_metadata (&writer->tcs,
"event {\n\tname = \"status\";\n\tid = %u;\n"
"\tfields := struct { \n"
"\t\tint32_t stop_reason;\n"
"\t\tint32_t stopping_tracepoint;\n"
"\t\tint32_t traceframe_count;\n"
"\t\tint32_t traceframes_created;\n"
"\t\tint32_t buffer_free;\n"
"\t\tint32_t buffer_size;\n"
"\t\tint32_t disconnected_tracing;\n"
"\t\tint32_t circular_buffer;\n"
"\t};\n"
"};\n",
CTF_EVENT_ID_STATUS);
id = CTF_EVENT_ID_STATUS;
/* Event Id. */
ctf_save_align_write (&writer->tcs, (gdb_byte *) &id, 4, 4);
ctf_save_write_int32 (&writer->tcs, ts->stop_reason);
ctf_save_write_int32 (&writer->tcs, ts->stopping_tracepoint);
ctf_save_write_int32 (&writer->tcs, ts->traceframe_count);
ctf_save_write_int32 (&writer->tcs, ts->traceframes_created);
ctf_save_write_int32 (&writer->tcs, ts->buffer_free);
ctf_save_write_int32 (&writer->tcs, ts->buffer_size);
ctf_save_write_int32 (&writer->tcs, ts->disconnected_tracing);
ctf_save_write_int32 (&writer->tcs, ts->circular_buffer);
}
/* This is the implementation of trace_file_write_ops method
write_uploaded_tsv. */
static void
ctf_write_uploaded_tsv (struct trace_file_writer *self,
struct uploaded_tsv *tsv)
{
struct ctf_trace_file_writer *writer
= (struct ctf_trace_file_writer *) self;
int32_t int32;
int64_t int64;
const gdb_byte zero = 0;
/* Event Id. */
int32 = CTF_EVENT_ID_TSV_DEF;
ctf_save_align_write (&writer->tcs, (gdb_byte *) &int32, 4, 4);
/* initial_value */
int64 = tsv->initial_value;
ctf_save_align_write (&writer->tcs, (gdb_byte *) &int64, 8, 8);
/* number */
ctf_save_write_int32 (&writer->tcs, tsv->number);
/* builtin */
ctf_save_write_int32 (&writer->tcs, tsv->builtin);
/* name */
if (tsv->name != NULL)
ctf_save_write (&writer->tcs, (gdb_byte *) tsv->name,
strlen (tsv->name));
ctf_save_write (&writer->tcs, &zero, 1);
}
/* This is the implementation of trace_file_write_ops method
write_uploaded_tp. */
static void
ctf_write_uploaded_tp (struct trace_file_writer *self,
struct uploaded_tp *tp)
{
struct ctf_trace_file_writer *writer
= (struct ctf_trace_file_writer *) self;
int32_t int32;
int64_t int64;
uint32_t u32;
const gdb_byte zero = 0;
/* Event Id. */
int32 = CTF_EVENT_ID_TP_DEF;
ctf_save_align_write (&writer->tcs, (gdb_byte *) &int32, 4, 4);
/* address */
int64 = tp->addr;
ctf_save_align_write (&writer->tcs, (gdb_byte *) &int64, 8, 8);
/* traceframe_usage */
int64 = tp->traceframe_usage;
ctf_save_align_write (&writer->tcs, (gdb_byte *) &int64, 8, 8);
/* number */
ctf_save_write_int32 (&writer->tcs, tp->number);
/* enabled */
ctf_save_write_int32 (&writer->tcs, tp->enabled);
/* step */
ctf_save_write_int32 (&writer->tcs, tp->step);
/* pass */
ctf_save_write_int32 (&writer->tcs, tp->pass);
/* hit_count */
ctf_save_write_int32 (&writer->tcs, tp->hit_count);
/* type */
ctf_save_write_int32 (&writer->tcs, tp->type);
/* condition */
if (tp->cond != NULL)
ctf_save_write (&writer->tcs, (gdb_byte *) tp->cond.get (),
strlen (tp->cond.get ()));
ctf_save_write (&writer->tcs, &zero, 1);
/* actions */
u32 = tp->actions.size ();
ctf_save_align_write (&writer->tcs, (gdb_byte *) &u32, 4, 4);
for (const auto &act : tp->actions)
ctf_save_write (&writer->tcs, (gdb_byte *) act.get (),
strlen (act.get ()) + 1);
/* step_actions */
u32 = tp->step_actions.size ();
ctf_save_align_write (&writer->tcs, (gdb_byte *) &u32, 4, 4);
for (const auto &act : tp->step_actions)
ctf_save_write (&writer->tcs, (gdb_byte *) act.get (),
strlen (act.get ()) + 1);
/* at_string */
if (tp->at_string != NULL)
ctf_save_write (&writer->tcs, (gdb_byte *) tp->at_string.get (),
strlen (tp->at_string.get ()));
ctf_save_write (&writer->tcs, &zero, 1);
/* cond_string */
if (tp->cond_string != NULL)
ctf_save_write (&writer->tcs, (gdb_byte *) tp->cond_string.get (),
strlen (tp->cond_string.get ()));
ctf_save_write (&writer->tcs, &zero, 1);
/* cmd_strings */
u32 = tp->cmd_strings.size ();
ctf_save_align_write (&writer->tcs, (gdb_byte *) &u32, 4, 4);
for (const auto &act : tp->cmd_strings)
ctf_save_write (&writer->tcs, (gdb_byte *) act.get (),
strlen (act.get ()) + 1);
}
/* This is the implementation of trace_file_write_ops method
write_tdesc. */
static void
ctf_write_tdesc (struct trace_file_writer *self)
{
/* Nothing so far. */
}
/* This is the implementation of trace_file_write_ops method
write_definition_end. */
static void
ctf_write_definition_end (struct trace_file_writer *self)
{
self->ops->frame_ops->end (self);
}
/* This is the implementation of trace_file_write_ops method
end. */
static void
ctf_end (struct trace_file_writer *self)
{
struct ctf_trace_file_writer *writer = (struct ctf_trace_file_writer *) self;
gdb_assert (writer->tcs.content_size == 0);
}
/* This is the implementation of trace_frame_write_ops method
start. */
static void
ctf_write_frame_start (struct trace_file_writer *self, uint16_t tpnum)
{
struct ctf_trace_file_writer *writer
= (struct ctf_trace_file_writer *) self;
uint32_t id = CTF_EVENT_ID_FRAME;
uint32_t u32;
/* Step 1: Write packet context. */
/* magic. */
u32 = CTF_MAGIC;
ctf_save_write_uint32 (&writer->tcs, u32);
/* content_size and packet_size.. We still don't know the value,
write it later. */
ctf_save_fseek (&writer->tcs, 4, SEEK_CUR);
ctf_save_fseek (&writer->tcs, 4, SEEK_CUR);
/* Tracepoint number. */
ctf_save_write (&writer->tcs, (gdb_byte *) &tpnum, 2);
/* Step 2: Write event "frame". */
/* Event Id. */
ctf_save_align_write (&writer->tcs, (gdb_byte *) &id, 4, 4);
}
/* This is the implementation of trace_frame_write_ops method
write_r_block. */
static void
ctf_write_frame_r_block (struct trace_file_writer *self,
gdb_byte *buf, int32_t size)
{
struct ctf_trace_file_writer *writer
= (struct ctf_trace_file_writer *) self;
uint32_t id = CTF_EVENT_ID_REGISTER;
/* Event Id. */
ctf_save_align_write (&writer->tcs, (gdb_byte *) &id, 4, 4);
/* array contents. */
ctf_save_align_write (&writer->tcs, buf, size, 1);
}
/* This is the implementation of trace_frame_write_ops method
write_m_block_header. */
static void
ctf_write_frame_m_block_header (struct trace_file_writer *self,
uint64_t addr, uint16_t length)
{
struct ctf_trace_file_writer *writer
= (struct ctf_trace_file_writer *) self;
uint32_t event_id = CTF_EVENT_ID_MEMORY;
/* Event Id. */
ctf_save_align_write (&writer->tcs, (gdb_byte *) &event_id, 4, 4);
/* Address. */
ctf_save_align_write (&writer->tcs, (gdb_byte *) &addr, 8, 8);
/* Length. */
ctf_save_align_write (&writer->tcs, (gdb_byte *) &length, 2, 2);
}
/* This is the implementation of trace_frame_write_ops method
write_m_block_memory. */
static void
ctf_write_frame_m_block_memory (struct trace_file_writer *self,
gdb_byte *buf, uint16_t length)
{
struct ctf_trace_file_writer *writer
= (struct ctf_trace_file_writer *) self;
/* Contents. */
ctf_save_align_write (&writer->tcs, (gdb_byte *) buf, length, 1);
}
/* This is the implementation of trace_frame_write_ops method
write_v_block. */
static void
ctf_write_frame_v_block (struct trace_file_writer *self,
int32_t num, uint64_t val)
{
struct ctf_trace_file_writer *writer
= (struct ctf_trace_file_writer *) self;
uint32_t id = CTF_EVENT_ID_TSV;
/* Event Id. */
ctf_save_align_write (&writer->tcs, (gdb_byte *) &id, 4, 4);
/* val. */
ctf_save_align_write (&writer->tcs, (gdb_byte *) &val, 8, 8);
/* num. */
ctf_save_align_write (&writer->tcs, (gdb_byte *) &num, 4, 4);
}
/* This is the implementation of trace_frame_write_ops method
end. */
static void
ctf_write_frame_end (struct trace_file_writer *self)
{
struct ctf_trace_file_writer *writer
= (struct ctf_trace_file_writer *) self;
uint32_t u32;
uint32_t t;
/* Write the content size to packet header. */
ctf_save_fseek (&writer->tcs, writer->tcs.packet_start + 4,
SEEK_SET);
u32 = writer->tcs.content_size * TARGET_CHAR_BIT;
t = writer->tcs.content_size;
ctf_save_write_uint32 (&writer->tcs, u32);
/* Write the packet size. */
u32 += 4 * TARGET_CHAR_BIT;
ctf_save_write_uint32 (&writer->tcs, u32);
writer->tcs.content_size = t;
/* Write zero at the end of the packet. */
ctf_save_fseek (&writer->tcs, writer->tcs.packet_start + t,
SEEK_SET);
u32 = 0;
ctf_save_write_uint32 (&writer->tcs, u32);
writer->tcs.content_size = t;
ctf_save_next_packet (&writer->tcs);
}
/* Operations to write various types of trace frames into CTF
format. */
static const struct trace_frame_write_ops ctf_write_frame_ops =
{
ctf_write_frame_start,
ctf_write_frame_r_block,
ctf_write_frame_m_block_header,
ctf_write_frame_m_block_memory,
ctf_write_frame_v_block,
ctf_write_frame_end,
};
/* Operations to write trace buffers into CTF format. */
static const struct trace_file_write_ops ctf_write_ops =
{
ctf_dtor,
ctf_target_save,
ctf_start,
ctf_write_header,
ctf_write_regblock_type,
ctf_write_status,
ctf_write_uploaded_tsv,
ctf_write_uploaded_tp,
ctf_write_tdesc,
ctf_write_definition_end,
NULL,
&ctf_write_frame_ops,
ctf_end,
};
/* Return a trace writer for CTF format. */
struct trace_file_writer *
ctf_trace_file_writer_new (void)
{
struct ctf_trace_file_writer *writer = XNEW (struct ctf_trace_file_writer);
writer->base.ops = &ctf_write_ops;
return (struct trace_file_writer *) writer;
}
#if HAVE_LIBBABELTRACE
/* Use libbabeltrace to read CTF data. The libbabeltrace provides
iterator to iterate over each event in CTF data and APIs to get
details of event and packet, so it is very convenient to use
libbabeltrace to access events in CTF. */
#include <babeltrace/babeltrace.h>
#include <babeltrace/ctf/events.h>
#include <babeltrace/ctf/iterator.h>
/* The struct pointer for current CTF directory. */
static int handle_id = -1;
static struct bt_context *ctx = NULL;
static struct bt_ctf_iter *ctf_iter = NULL;
/* The position of the first packet containing trace frame. */
static struct bt_iter_pos *start_pos;
/* The name of CTF directory. */
static char *trace_dirname;
static ctf_target ctf_ops;
/* Destroy ctf iterator and context. */
static void
ctf_destroy (void)
{
if (ctf_iter != NULL)
{
bt_ctf_iter_destroy (ctf_iter);
ctf_iter = NULL;
}
if (ctx != NULL)
{
bt_context_put (ctx);
ctx = NULL;
}
}
/* Open CTF trace data in DIRNAME. */
static void
ctf_open_dir (const char *dirname)
{
struct bt_iter_pos begin_pos;
unsigned int count, i;
struct bt_ctf_event_decl * const *list;
ctx = bt_context_create ();
if (ctx == NULL)
error (_("Unable to create bt_context"));
handle_id = bt_context_add_trace (ctx, dirname, "ctf", NULL, NULL, NULL);
if (handle_id < 0)
{
ctf_destroy ();
error (_("Unable to use libbabeltrace on directory \"%s\""),
dirname);
}
begin_pos.type = BT_SEEK_BEGIN;
ctf_iter = bt_ctf_iter_create (ctx, &begin_pos, NULL);
if (ctf_iter == NULL)
{
ctf_destroy ();
error (_("Unable to create bt_iterator"));
}
/* Look for the declaration of register block. Get the length of
array "contents" to set trace_regblock_size. */
bt_ctf_get_event_decl_list (handle_id, ctx, &list, &count);
for (i = 0; i < count; i++)
if (strcmp ("register", bt_ctf_get_decl_event_name (list[i])) == 0)
{
const struct bt_ctf_field_decl * const *field_list;
const struct bt_declaration *decl;
bt_ctf_get_decl_fields (list[i], BT_EVENT_FIELDS, &field_list,
&count);
gdb_assert (count == 1);
gdb_assert (0 == strcmp ("contents",
bt_ctf_get_decl_field_name (field_list[0])));
decl = bt_ctf_get_decl_from_field_decl (field_list[0]);
trace_regblock_size = bt_ctf_get_array_len (decl);
break;
}
}
#define SET_INT32_FIELD(EVENT, SCOPE, VAR, FIELD) \
(VAR)->FIELD = (int) bt_ctf_get_int64 (bt_ctf_get_field ((EVENT), \
(SCOPE), \
#FIELD))
#define SET_ENUM_FIELD(EVENT, SCOPE, VAR, TYPE, FIELD) \
(VAR)->FIELD = (TYPE) bt_ctf_get_int64 (bt_ctf_get_field ((EVENT), \
(SCOPE), \
#FIELD))
/* EVENT is the "status" event and TS is filled in. */
static void
ctf_read_status (struct bt_ctf_event *event, struct trace_status *ts)
{
const struct bt_definition *scope
= bt_ctf_get_top_level_scope (event, BT_EVENT_FIELDS);
SET_ENUM_FIELD (event, scope, ts, enum trace_stop_reason, stop_reason);
SET_INT32_FIELD (event, scope, ts, stopping_tracepoint);
SET_INT32_FIELD (event, scope, ts, traceframe_count);
SET_INT32_FIELD (event, scope, ts, traceframes_created);
SET_INT32_FIELD (event, scope, ts, buffer_free);
SET_INT32_FIELD (event, scope, ts, buffer_size);
SET_INT32_FIELD (event, scope, ts, disconnected_tracing);
SET_INT32_FIELD (event, scope, ts, circular_buffer);
bt_iter_next (bt_ctf_get_iter (ctf_iter));
}
/* Read the events "tsv_def" one by one, extract its contents and fill
in the list UPLOADED_TSVS. */
static void
ctf_read_tsv (struct uploaded_tsv **uploaded_tsvs)
{
gdb_assert (ctf_iter != NULL);
while (1)
{
struct bt_ctf_event *event;
const struct bt_definition *scope;
const struct bt_definition *def;
uint32_t event_id;
struct uploaded_tsv *utsv = NULL;
event = bt_ctf_iter_read_event (ctf_iter);
scope = bt_ctf_get_top_level_scope (event,
BT_STREAM_EVENT_HEADER);
event_id = bt_ctf_get_uint64 (bt_ctf_get_field (event, scope,
"id"));
if (event_id != CTF_EVENT_ID_TSV_DEF)
break;
scope = bt_ctf_get_top_level_scope (event,
BT_EVENT_FIELDS);
def = bt_ctf_get_field (event, scope, "number");
utsv = get_uploaded_tsv ((int32_t) bt_ctf_get_int64 (def),
uploaded_tsvs);
def = bt_ctf_get_field (event, scope, "builtin");
utsv->builtin = (int32_t) bt_ctf_get_int64 (def);
def = bt_ctf_get_field (event, scope, "initial_value");
utsv->initial_value = bt_ctf_get_int64 (def);
def = bt_ctf_get_field (event, scope, "name");
utsv->name = xstrdup (bt_ctf_get_string (def));
if (bt_iter_next (bt_ctf_get_iter (ctf_iter)) < 0)
break;
}
}
/* Read the value of element whose index is NUM from CTF and write it
to the corresponding VAR->ARRAY. */
#define SET_ARRAY_FIELD(EVENT, SCOPE, VAR, NUM, ARRAY) \
do \
{ \
uint32_t lu32, i; \
const struct bt_definition *def; \
\
lu32 = (uint32_t) bt_ctf_get_uint64 (bt_ctf_get_field ((EVENT), \
(SCOPE), \
#NUM)); \
def = bt_ctf_get_field ((EVENT), (SCOPE), #ARRAY); \
for (i = 0; i < lu32; i++) \
{ \
const struct bt_definition *element \
= bt_ctf_get_index ((EVENT), def, i); \
\
(VAR)->ARRAY.emplace_back \
(xstrdup (bt_ctf_get_string (element))); \
} \
} \
while (0)
/* Read a string from CTF and set VAR->FIELD. If the length of string
is zero, set VAR->FIELD to NULL. */
#define SET_STRING_FIELD(EVENT, SCOPE, VAR, FIELD) \
do \
{ \
const char *p = bt_ctf_get_string (bt_ctf_get_field ((EVENT), \
(SCOPE), \
#FIELD)); \
\
if (strlen (p) > 0) \
(VAR)->FIELD.reset (xstrdup (p)); \
else \
(VAR)->FIELD = NULL; \
} \
while (0)
/* Read the events "tp_def" one by one, extract its contents and fill
in the list UPLOADED_TPS. */
static void
ctf_read_tp (struct uploaded_tp **uploaded_tps)
{
gdb_assert (ctf_iter != NULL);
while (1)
{
struct bt_ctf_event *event;
const struct bt_definition *scope;
uint32_t u32;
int32_t int32;
uint64_t u64;
struct uploaded_tp *utp = NULL;
event = bt_ctf_iter_read_event (ctf_iter);
scope = bt_ctf_get_top_level_scope (event,
BT_STREAM_EVENT_HEADER);
u32 = bt_ctf_get_uint64 (bt_ctf_get_field (event, scope,
"id"));
if (u32 != CTF_EVENT_ID_TP_DEF)
break;
scope = bt_ctf_get_top_level_scope (event,
BT_EVENT_FIELDS);
int32 = (int32_t) bt_ctf_get_int64 (bt_ctf_get_field (event,
scope,
"number"));
u64 = bt_ctf_get_uint64 (bt_ctf_get_field (event, scope,
"addr"));
utp = get_uploaded_tp (int32, u64, uploaded_tps);
SET_INT32_FIELD (event, scope, utp, enabled);
SET_INT32_FIELD (event, scope, utp, step);
SET_INT32_FIELD (event, scope, utp, pass);
SET_INT32_FIELD (event, scope, utp, hit_count);
SET_ENUM_FIELD (event, scope, utp, enum bptype, type);
/* Read 'cmd_strings'. */
SET_ARRAY_FIELD (event, scope, utp, cmd_num, cmd_strings);
/* Read 'actions'. */
SET_ARRAY_FIELD (event, scope, utp, action_num, actions);
/* Read 'step_actions'. */
SET_ARRAY_FIELD (event, scope, utp, step_action_num,
step_actions);
SET_STRING_FIELD(event, scope, utp, at_string);
SET_STRING_FIELD(event, scope, utp, cond_string);
if (bt_iter_next (bt_ctf_get_iter (ctf_iter)) < 0)
break;
}
}
/* This is the implementation of target_ops method to_open. Open CTF
trace data, read trace status, trace state variables and tracepoint
definitions from the first packet. Set the start position at the
second packet which contains events on trace blocks. */
static void
ctf_target_open (const char *dirname, int from_tty)
{
struct bt_ctf_event *event;
uint32_t event_id;
const struct bt_definition *scope;
struct uploaded_tsv *uploaded_tsvs = NULL;
struct uploaded_tp *uploaded_tps = NULL;
if (!dirname)
error (_("No CTF directory specified."));
ctf_open_dir (dirname);
target_preopen (from_tty);
/* Skip the first packet which about the trace status. The first
event is "frame". */
event = bt_ctf_iter_read_event (ctf_iter);
scope = bt_ctf_get_top_level_scope (event, BT_STREAM_EVENT_HEADER);
event_id = bt_ctf_get_uint64 (bt_ctf_get_field (event, scope, "id"));
if (event_id != CTF_EVENT_ID_FRAME)
error (_("Wrong event id of the first event"));
/* The second event is "status". */
bt_iter_next (bt_ctf_get_iter (ctf_iter));
event = bt_ctf_iter_read_event (ctf_iter);
scope = bt_ctf_get_top_level_scope (event, BT_STREAM_EVENT_HEADER);
event_id = bt_ctf_get_uint64 (bt_ctf_get_field (event, scope, "id"));
if (event_id != CTF_EVENT_ID_STATUS)
error (_("Wrong event id of the second event"));
ctf_read_status (event, current_trace_status ());
ctf_read_tsv (&uploaded_tsvs);
ctf_read_tp (&uploaded_tps);
event = bt_ctf_iter_read_event (ctf_iter);
/* EVENT can be NULL if we've already gone to the end of stream of
events. */
if (event != NULL)
{
scope = bt_ctf_get_top_level_scope (event,
BT_STREAM_EVENT_HEADER);
event_id = bt_ctf_get_uint64 (bt_ctf_get_field (event,
scope, "id"));
if (event_id != CTF_EVENT_ID_FRAME)
error (_("Wrong event id of the first event of the second packet"));
}
start_pos = bt_iter_get_pos (bt_ctf_get_iter (ctf_iter));
gdb_assert (start_pos->type == BT_SEEK_RESTORE);
trace_dirname = xstrdup (dirname);
push_target (&ctf_ops);
inferior_appeared (current_inferior (), CTF_PID);
thread_info *thr = add_thread_silent (&ctf_ops, ptid_t (CTF_PID));
switch_to_thread (thr);
merge_uploaded_trace_state_variables (&uploaded_tsvs);
merge_uploaded_tracepoints (&uploaded_tps);
post_create_inferior (&ctf_ops, from_tty);
}
/* This is the implementation of target_ops method to_close. Destroy
CTF iterator and context. */
void
ctf_target::close ()
{
ctf_destroy ();
xfree (trace_dirname);
trace_dirname = NULL;
switch_to_no_thread (); /* Avoid confusion from thread stuff. */
exit_inferior_silent (current_inferior ());
trace_reset_local_state ();
}
/* This is the implementation of target_ops method to_files_info.
Print the directory name of CTF trace data. */
void
ctf_target::files_info ()
{
printf_filtered ("\t`%s'\n", trace_dirname);
}
/* This is the implementation of target_ops method to_fetch_registers.
Iterate over events whose name is "register" in current frame,
extract contents from events, and set REGCACHE with the contents.
If no matched events are found, mark registers unavailable. */
void
ctf_target::fetch_registers (struct regcache *regcache, int regno)
{
struct gdbarch *gdbarch = regcache->arch ();
struct bt_ctf_event *event = NULL;
struct bt_iter_pos *pos;
/* An uninitialized reg size says we're not going to be
successful at getting register blocks. */
if (trace_regblock_size == 0)
return;
gdb_assert (ctf_iter != NULL);
/* Save the current position. */
pos = bt_iter_get_pos (bt_ctf_get_iter (ctf_iter));
gdb_assert (pos->type == BT_SEEK_RESTORE);
while (1)
{
const char *name;
struct bt_ctf_event *event1;
event1 = bt_ctf_iter_read_event (ctf_iter);
name = bt_ctf_event_name (event1);
if (name == NULL || strcmp (name, "frame") == 0)
break;
else if (strcmp (name, "register") == 0)
{
event = event1;
break;
}
if (bt_iter_next (bt_ctf_get_iter (ctf_iter)) < 0)
break;
}
/* Restore the position. */
bt_iter_set_pos (bt_ctf_get_iter (ctf_iter), pos);
if (event != NULL)
{
int offset, regsize, regn;
const struct bt_definition *scope
= bt_ctf_get_top_level_scope (event,
BT_EVENT_FIELDS);
const struct bt_definition *array
= bt_ctf_get_field (event, scope, "contents");
gdb_byte *regs = (gdb_byte *) bt_ctf_get_char_array (array);
/* Assume the block is laid out in GDB register number order,
each register with the size that it has in GDB. */
offset = 0;
for (regn = 0; regn < gdbarch_num_regs (gdbarch); regn++)
{
regsize = register_size (gdbarch, regn);
/* Make sure we stay within block bounds. */
if (offset + regsize >= trace_regblock_size)
break;
if (regcache->get_register_status (regn) == REG_UNKNOWN)
{
if (regno == regn)
{
regcache->raw_supply (regno, regs + offset);
break;
}
else if (regno == -1)
{
regcache->raw_supply (regn, regs + offset);
}
}
offset += regsize;
}
}
else
tracefile_fetch_registers (regcache, regno);
}
/* This is the implementation of target_ops method to_xfer_partial.
Iterate over events whose name is "memory" in
current frame, extract the address and length from events. If
OFFSET is within the range, read the contents from events to
READBUF. */
enum target_xfer_status
ctf_target::xfer_partial (enum target_object object,
const char *annex, gdb_byte *readbuf,
const gdb_byte *writebuf, ULONGEST offset,
ULONGEST len, ULONGEST *xfered_len)
{
/* We're only doing regular memory for now. */
if (object != TARGET_OBJECT_MEMORY)
return TARGET_XFER_E_IO;
if (readbuf == NULL)
error (_("ctf_xfer_partial: trace file is read-only"));
if (get_traceframe_number () != -1)
{
struct bt_iter_pos *pos;
enum target_xfer_status res;
/* Records the lowest available address of all blocks that
intersects the requested range. */
ULONGEST low_addr_available = 0;
gdb_assert (ctf_iter != NULL);
/* Save the current position. */
pos = bt_iter_get_pos (bt_ctf_get_iter (ctf_iter));
gdb_assert (pos->type == BT_SEEK_RESTORE);
/* Iterate through the traceframe's blocks, looking for
memory. */
while (1)
{
ULONGEST amt;
uint64_t maddr;
uint16_t mlen;
const struct bt_definition *scope;
const struct bt_definition *def;
struct bt_ctf_event *event
= bt_ctf_iter_read_event (ctf_iter);
const char *name = bt_ctf_event_name (event);
if (name == NULL || strcmp (name, "frame") == 0)
break;
else if (strcmp (name, "memory") != 0)
{
if (bt_iter_next (bt_ctf_get_iter (ctf_iter)) < 0)
break;
continue;
}
scope = bt_ctf_get_top_level_scope (event,
BT_EVENT_FIELDS);
def = bt_ctf_get_field (event, scope, "address");
maddr = bt_ctf_get_uint64 (def);
def = bt_ctf_get_field (event, scope, "length");
mlen = (uint16_t) bt_ctf_get_uint64 (def);
/* If the block includes the first part of the desired
range, return as much it has; GDB will re-request the
remainder, which might be in a different block of this
trace frame. */
if (maddr <= offset && offset < (maddr + mlen))
{
const struct bt_definition *array
= bt_ctf_get_field (event, scope, "contents");
gdb_byte *contents;
int k;
contents = (gdb_byte *) xmalloc (mlen);
for (k = 0; k < mlen; k++)
{
const struct bt_definition *element
= bt_ctf_get_index (event, array, k);
contents[k] = (gdb_byte) bt_ctf_get_uint64 (element);
}
amt = (maddr + mlen) - offset;
if (amt > len)
amt = len;
memcpy (readbuf, &contents[offset - maddr], amt);
xfree (contents);
/* Restore the position. */
bt_iter_set_pos (bt_ctf_get_iter (ctf_iter), pos);
if (amt == 0)
return TARGET_XFER_EOF;
else
{
*xfered_len = amt;
return TARGET_XFER_OK;
}
}
if (offset < maddr && maddr < (offset + len))
if (low_addr_available == 0 || low_addr_available > maddr)
low_addr_available = maddr;
if (bt_iter_next (bt_ctf_get_iter (ctf_iter)) < 0)
break;
}
/* Restore the position. */
bt_iter_set_pos (bt_ctf_get_iter (ctf_iter), pos);
/* Requested memory is unavailable in the context of traceframes,
and this address falls within a read-only section, fallback
to reading from executable, up to LOW_ADDR_AVAILABLE */
if (offset < low_addr_available)
len = std::min (len, low_addr_available - offset);
res = exec_read_partial_read_only (readbuf, offset, len, xfered_len);
if (res == TARGET_XFER_OK)
return TARGET_XFER_OK;
else
{
/* No use trying further, we know some memory starting
at MEMADDR isn't available. */
*xfered_len = len;
return TARGET_XFER_UNAVAILABLE;
}
}
else
{
/* Fallback to reading from read-only sections. */
return section_table_read_available_memory (readbuf, offset, len, xfered_len);
}
}
/* This is the implementation of target_ops method
to_get_trace_state_variable_value.
Iterate over events whose name is "tsv" in current frame. When the
trace variable is found, set the value of it to *VAL and return
true, otherwise return false. */
bool
ctf_target::get_trace_state_variable_value (int tsvnum, LONGEST *val)
{
struct bt_iter_pos *pos;
bool found = false;
gdb_assert (ctf_iter != NULL);
/* Save the current position. */
pos = bt_iter_get_pos (bt_ctf_get_iter (ctf_iter));
gdb_assert (pos->type == BT_SEEK_RESTORE);
/* Iterate through the traceframe's blocks, looking for 'V'
block. */
while (1)
{
struct bt_ctf_event *event
= bt_ctf_iter_read_event (ctf_iter);
const char *name = bt_ctf_event_name (event);
if (name == NULL || strcmp (name, "frame") == 0)
break;
else if (strcmp (name, "tsv") == 0)
{
const struct bt_definition *scope;
const struct bt_definition *def;
scope = bt_ctf_get_top_level_scope (event,
BT_EVENT_FIELDS);
def = bt_ctf_get_field (event, scope, "num");
if (tsvnum == (int32_t) bt_ctf_get_uint64 (def))
{
def = bt_ctf_get_field (event, scope, "val");
*val = bt_ctf_get_uint64 (def);
found = true;
}
}
if (bt_iter_next (bt_ctf_get_iter (ctf_iter)) < 0)
break;
}
/* Restore the position. */
bt_iter_set_pos (bt_ctf_get_iter (ctf_iter), pos);
return found;
}
/* Return the tracepoint number in "frame" event. */
static int
ctf_get_tpnum_from_frame_event (struct bt_ctf_event *event)
{
/* The packet context of events has a field "tpnum". */
const struct bt_definition *scope
= bt_ctf_get_top_level_scope (event, BT_STREAM_PACKET_CONTEXT);
uint64_t tpnum
= bt_ctf_get_uint64 (bt_ctf_get_field (event, scope, "tpnum"));
return (int) tpnum;
}
/* Return the address at which the current frame was collected. */
static CORE_ADDR
ctf_get_traceframe_address (void)
{
struct bt_ctf_event *event = NULL;
struct bt_iter_pos *pos;
CORE_ADDR addr = 0;
gdb_assert (ctf_iter != NULL);
pos = bt_iter_get_pos (bt_ctf_get_iter (ctf_iter));
gdb_assert (pos->type == BT_SEEK_RESTORE);
while (1)
{
const char *name;
struct bt_ctf_event *event1;
event1 = bt_ctf_iter_read_event (ctf_iter);
name = bt_ctf_event_name (event1);
if (name == NULL)
break;
else if (strcmp (name, "frame") == 0)
{
event = event1;
break;
}
if (bt_iter_next (bt_ctf_get_iter (ctf_iter)) < 0)
break;
}
if (event != NULL)
{
int tpnum = ctf_get_tpnum_from_frame_event (event);
struct tracepoint *tp
= get_tracepoint_by_number_on_target (tpnum);
if (tp && tp->loc)
addr = tp->loc->address;
}
/* Restore the position. */
bt_iter_set_pos (bt_ctf_get_iter (ctf_iter), pos);
return addr;
}
/* This is the implementation of target_ops method to_trace_find.
Iterate the events whose name is "frame", extract the tracepoint
number in it. Return traceframe number when matched. */
int
ctf_target::trace_find (enum trace_find_type type, int num,
CORE_ADDR addr1, CORE_ADDR addr2, int *tpp)
{
int tfnum = 0;
int found = 0;
if (num == -1)
{
if (tpp != NULL)
*tpp = -1;
return -1;
}
gdb_assert (ctf_iter != NULL);
/* Set iterator back to the start. */
bt_iter_set_pos (bt_ctf_get_iter (ctf_iter), start_pos);
while (1)
{
struct bt_ctf_event *event;
const char *name;
event = bt_ctf_iter_read_event (ctf_iter);
name = bt_ctf_event_name (event);
if (event == NULL || name == NULL)
break;
if (strcmp (name, "frame") == 0)
{
CORE_ADDR tfaddr;
if (type == tfind_number)
{
/* Looking for a specific trace frame. */
if (tfnum == num)
found = 1;
}
else
{
/* Start from the _next_ trace frame. */
if (tfnum > get_traceframe_number ())
{
switch (type)
{
case tfind_tp:
{
struct tracepoint *tp = get_tracepoint (num);
if (tp != NULL
&& (tp->number_on_target
== ctf_get_tpnum_from_frame_event (event)))
found = 1;
break;
}
case tfind_pc:
tfaddr = ctf_get_traceframe_address ();
if (tfaddr == addr1)
found = 1;
break;
case tfind_range:
tfaddr = ctf_get_traceframe_address ();
if (addr1 <= tfaddr && tfaddr <= addr2)
found = 1;
break;
case tfind_outside:
tfaddr = ctf_get_traceframe_address ();
if (!(addr1 <= tfaddr && tfaddr <= addr2))
found = 1;
break;
default:
internal_error (__FILE__, __LINE__, _("unknown tfind type"));
}
}
}
if (found)
{
if (tpp != NULL)
*tpp = ctf_get_tpnum_from_frame_event (event);
/* Skip the event "frame". */
bt_iter_next (bt_ctf_get_iter (ctf_iter));
return tfnum;
}
tfnum++;
}
if (bt_iter_next (bt_ctf_get_iter (ctf_iter)) < 0)
break;
}
return -1;
}
/* This is the implementation of target_ops method to_traceframe_info.
Iterate the events whose name is "memory", in current
frame, extract memory range information, and return them in
traceframe_info. */
traceframe_info_up
ctf_target::traceframe_info ()
{
traceframe_info_up info (new struct traceframe_info);
const char *name;
struct bt_iter_pos *pos;
gdb_assert (ctf_iter != NULL);
/* Save the current position. */
pos = bt_iter_get_pos (bt_ctf_get_iter (ctf_iter));
gdb_assert (pos->type == BT_SEEK_RESTORE);
do
{
struct bt_ctf_event *event
= bt_ctf_iter_read_event (ctf_iter);
name = bt_ctf_event_name (event);
if (name == NULL || strcmp (name, "register") == 0
|| strcmp (name, "frame") == 0)
;
else if (strcmp (name, "memory") == 0)
{
const struct bt_definition *scope
= bt_ctf_get_top_level_scope (event,
BT_EVENT_FIELDS);
const struct bt_definition *def;
def = bt_ctf_get_field (event, scope, "address");
CORE_ADDR start = bt_ctf_get_uint64 (def);
def = bt_ctf_get_field (event, scope, "length");
int length = (uint16_t) bt_ctf_get_uint64 (def);
info->memory.emplace_back (start, length);
}
else if (strcmp (name, "tsv") == 0)
{
int vnum;
const struct bt_definition *scope
= bt_ctf_get_top_level_scope (event,
BT_EVENT_FIELDS);
const struct bt_definition *def;
def = bt_ctf_get_field (event, scope, "num");
vnum = (int) bt_ctf_get_uint64 (def);
info->tvars.push_back (vnum);
}
else
{
warning (_("Unhandled trace block type (%s) "
"while building trace frame info."),
name);
}
if (bt_iter_next (bt_ctf_get_iter (ctf_iter)) < 0)
break;
}
while (name != NULL && strcmp (name, "frame") != 0);
/* Restore the position. */
bt_iter_set_pos (bt_ctf_get_iter (ctf_iter), pos);
return info;
}
#endif
/* module initialization */
void _initialize_ctf ();
void
_initialize_ctf ()
{
#if HAVE_LIBBABELTRACE
add_target (ctf_target_info, ctf_target_open, filename_completer);
#endif
}
|
764979.c | /*
*
***** BEGIN LICENSE BLOCK *****
Copyright (C) 2009-2018 Olof Hagsand and Benny Holmgren
This file is part of CLIXON.
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.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 3 or later (the "GPL"),
in which case the provisions of the GPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of the GPL, and not to allow others to
use your version of this file under the terms of Apache License version 2,
indicate your decision by deleting the provisions above and replace them with
the notice and other provisions required by the GPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the Apache License version 2 or the GPL.
***** END LICENSE BLOCK *****
*/
#ifdef HAVE_CONFIG_H
#include "clixon_config.h" /* generated by config & autoconf */
#endif
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdarg.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#include <time.h>
#include <syslog.h>
#include <grp.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/param.h>
#ifdef HAVE_SYS_UCRED_H
#include <sys/types.h>
#include <sys/ucred.h>
#endif
#define __USE_GNU
#include <sys/socket.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cligen/cligen.h>
/* clicon */
#include <clixon/clixon.h>
#include "backend_socket.h"
#include "backend_client.h"
#include "backend_handle.h"
static int
config_socket_init_ipv4(clicon_handle h,
char *dst)
{
int s;
struct sockaddr_in addr;
uint16_t port;
port = clicon_sock_port(h);
/* create inet socket */
if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
clicon_err(OE_UNIX, errno, "socket");
return -1;
}
// setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*)&one, sizeof(one));
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
if (inet_pton(addr.sin_family, dst, &addr.sin_addr) != 1){
clicon_err(OE_UNIX, errno, "inet_pton: %s (Expected IPv4 address. Check settings of CLICON_SOCK_FAMILY and CLICON_SOCK)", dst);
goto err; /* Could check getaddrinfo */
}
if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0){
clicon_err(OE_UNIX, errno, "bind");
goto err;
}
clicon_debug(1, "Listen on server socket at %s:%hu", dst, port);
if (listen(s, 5) < 0){
clicon_err(OE_UNIX, errno, "listen");
goto err;
}
return s;
err:
close(s);
return -1;
}
/*! Open a socket and bind it to a file descriptor
*
* The socket is accessed via CLICON_SOCK option, has 770 permissions
* and group according to CLICON_SOCK_GROUP option.
*/
static int
config_socket_init_unix(clicon_handle h,
char *sock)
{
int s;
struct sockaddr_un addr;
mode_t old_mask;
char *config_group;
gid_t gid;
struct stat st;
if (lstat(sock, &st) == 0 && unlink(sock) < 0){
clicon_err(OE_UNIX, errno, "unlink(%s)", sock);
return -1;
}
/* then find configuration group (for clients) and find its groupid */
if ((config_group = clicon_sock_group(h)) == NULL){
clicon_err(OE_FATAL, 0, "clicon_sock_group option not set");
return -1;
}
if (group_name2gid(config_group, &gid) < 0)
return -1;
#if 0
if (gid == 0)
clicon_log(LOG_WARNING, "%s: No such group: %s\n", __FUNCTION__, config_group);
#endif
/* create unix socket */
if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
clicon_err(OE_UNIX, errno, "socket");
return -1;
}
// setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*)&one, sizeof(one));
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, sock, sizeof(addr.sun_path)-1);
old_mask = umask(S_IRWXO | S_IXGRP | S_IXUSR);
if (bind(s, (struct sockaddr *)&addr, SUN_LEN(&addr)) < 0){
clicon_err(OE_UNIX, errno, "bind");
umask(old_mask);
goto err;
}
umask(old_mask);
/* change socket path file group */
if (lchown(sock, -1, gid) < 0){
clicon_err(OE_UNIX, errno, "lchown(%s, %s)", sock, config_group);
goto err;
}
clicon_debug(1, "Listen on server socket at %s", addr.sun_path);
if (listen(s, 5) < 0){
clicon_err(OE_UNIX, errno, "listen");
goto err;
}
return s;
err:
close(s);
return -1;
}
int
backend_socket_init(clicon_handle h)
{
char *sock;
if ((sock = clicon_sock(h)) == NULL){
clicon_err(OE_FATAL, 0, "CLICON_SOCK option not set");
return -1;
}
switch (clicon_sock_family(h)){
case AF_UNIX:
return config_socket_init_unix(h, sock);
break;
case AF_INET:
return config_socket_init_ipv4(h, sock);
break;
}
return 0;
}
/*! Accept new socket client
* XXX: credentials not properly implemented
*/
int
backend_accept_client(int fd,
void *arg)
{
int retval = -1;
clicon_handle h = (clicon_handle)arg;
int s;
struct sockaddr_un from;
socklen_t len;
struct client_entry *ce;
#ifdef DONT_WORK /* XXX HAVE_SYS_UCRED_H */
struct xucred credentials; /* FreeBSD. */
socklen_t clen;
#elif defined(SO_PEERCRED)
struct ucred credentials; /* Linux. */
socklen_t clen;
#endif
char *config_group;
struct group *gr;
char *mem;
int i;
clicon_debug(2, "%s", __FUNCTION__);
len = sizeof(from);
if ((s = accept(fd, (struct sockaddr*)&from, &len)) < 0){
clicon_err(OE_UNIX, errno, "accept");
goto done;
}
#if defined(SO_PEERCRED)
/* fill in the user data structure */
clen = sizeof(credentials);
if(getsockopt(s, SOL_SOCKET, SO_PEERCRED/* XXX finns ej i freebsd*/, &credentials, &clen)){
clicon_err(OE_UNIX, errno, "getsockopt");
goto done;
}
#endif
if ((ce = backend_client_add(h, (struct sockaddr*)&from)) == NULL)
goto done;
#if defined(SO_PEERCRED)
ce->ce_pid = credentials.pid;
ce->ce_uid = credentials.uid;
#endif
ce->ce_handle = h;
/* check credentials of caller (not properly implemented yet) */
if ((config_group = clicon_sock_group(h)) == NULL){
clicon_err(OE_FATAL, 0, "clicon_sock_group option not set");
goto done;
}
if ((gr = getgrnam(config_group)) != NULL){
i = 0; /* one of mem should correspond to ce->ce_uid */
while ((mem = gr->gr_mem[i++]) != NULL)
;
}
#if 0
{ /* XXX */
int ii;
struct client_entry *c;
for (c = ce_list, ii=0; c; c = c->ce_next, ii++);
clicon_debug(1, "Open client socket (nr:%d pid:%d [Total: %d])",
ce->ce_nr, ce->ce_pid, ii);
}
#endif
ce->ce_s = s;
/*
* Here we register callbacks for actual data socket
*/
if (event_reg_fd(s, from_client, (void*)ce, "local netconf client socket") < 0)
goto done;
retval = 0;
done:
return retval;
}
|
839057.c | /******************************************************************************
*
* Copyright (c) 2019 Intel.
*
* 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.
*
*******************************************************************************/
/**
* @brief XRAN layer common functionality for both O-DU and O-RU as well as C-plane and
* U-plane
* @file xran_common.c
* @ingroup group_source_xran
* @author Intel Corporation
**/
#include <assert.h>
#include <err.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <time.h>
#include "xran_common.h"
#include "ethdi.h"
#include "xran_pkt.h"
#include "xran_pkt_up.h"
#include "xran_up_api.h"
#include "xran_lib_mlog_tasks_id.h"
#include "../src/xran_printf.h"
#include <rte_mbuf.h>
#include "xran_mlog_lnx.h"
static struct timespec sleeptime = {.tv_nsec = 1E3 }; /* 1 us */
#define MBUFS_CNT 16
extern long interval_us;
extern int xran_process_rx_sym(void *arg,
struct rte_mbuf *mbuf,
void *iq_data_start,
uint16_t size,
uint8_t CC_ID,
uint8_t Ant_ID,
uint8_t frame_id,
uint8_t subframe_id,
uint8_t slot_id,
uint8_t symb_id,
uint16_t num_prbu,
uint16_t start_prbu,
uint16_t sym_inc,
uint16_t rb,
uint16_t sect_id,
uint32_t *mb_free);
extern int xran_process_prach_sym(void *arg,
struct rte_mbuf *mbuf,
void *iq_data_start,
uint16_t size,
uint8_t CC_ID,
uint8_t Ant_ID,
uint8_t frame_id,
uint8_t subframe_id,
uint8_t slot_id,
uint8_t symb_id,
uint16_t num_prbu,
uint16_t start_prbu,
uint16_t sym_inc,
uint16_t rb,
uint16_t sect_id,
uint32_t *mb_free);
extern int32_t xran_process_srs_sym(void *arg,
struct rte_mbuf *mbuf,
void *iq_data_start,
uint16_t size,
uint8_t CC_ID,
uint8_t Ant_ID,
uint8_t frame_id,
uint8_t subframe_id,
uint8_t slot_id,
uint8_t symb_id,
uint16_t num_prbu,
uint16_t start_prbu,
uint16_t sym_inc,
uint16_t rb,
uint16_t sect_id,
uint32_t *mb_free);
extern int32_t xran_pkt_validate(void *arg,
struct rte_mbuf *mbuf,
void *iq_data_start,
uint16_t size,
uint8_t CC_ID,
uint8_t Ant_ID,
uint8_t frame_id,
uint8_t subframe_id,
uint8_t slot_id,
uint8_t symb_id,
struct ecpri_seq_id *seq_id,
uint16_t num_prbu,
uint16_t start_prbu,
uint16_t sym_inc,
uint16_t rb,
uint16_t sect_id);
struct cb_elem_entry *xran_create_cb(XranSymCallbackFn cb_fn, void *cb_data)
{
struct cb_elem_entry * cb_elm = (struct cb_elem_entry *)malloc(sizeof(struct cb_elem_entry));
if(cb_elm){
cb_elm->pSymCallback = cb_fn;
cb_elm->pSymCallbackTag = cb_data;
}
return cb_elm;
}
int xran_destroy_cb(struct cb_elem_entry * cb_elm)
{
if(cb_elm)
free(cb_elm);
return 0;
}
int process_mbuf(struct rte_mbuf *pkt)
{
void *iq_samp_buf;
struct ecpri_seq_id seq;
static int symbol_total_bytes = 0;
int num_bytes = 0;
struct xran_device_ctx * p_x_ctx = xran_dev_get_ctx();
struct xran_common_counters *pCnt = &p_x_ctx->fh_counters;
uint8_t CC_ID = 0;
uint8_t Ant_ID = 0;
uint8_t frame_id = 0;
uint8_t subframe_id = 0;
uint8_t slot_id = 0;
uint8_t symb_id = 0;
uint16_t num_prbu;
uint16_t start_prbu;
uint16_t sym_inc;
uint16_t rb;
uint16_t sect_id;
uint8_t compMeth = 0;
uint8_t iqWidth = 0;
void *pHandle = NULL;
int ret = MBUF_FREE;
uint32_t mb_free = 0;
int32_t valid_res = 0;
int expect_comp = (p_x_ctx->fh_cfg.ru_conf.compMeth != XRAN_COMPMETHOD_NONE);
if(p_x_ctx->xran2phy_mem_ready == 0)
return MBUF_FREE;
num_bytes = xran_extract_iq_samples(pkt,
&iq_samp_buf,
&CC_ID,
&Ant_ID,
&frame_id,
&subframe_id,
&slot_id,
&symb_id,
&seq,
&num_prbu,
&start_prbu,
&sym_inc,
&rb,
§_id,
expect_comp,
&compMeth,
&iqWidth);
if (num_bytes <= 0){
print_err("num_bytes is wrong [%d]\n", num_bytes);
return MBUF_FREE;
}
valid_res = xran_pkt_validate(NULL,
pkt,
iq_samp_buf,
num_bytes,
CC_ID,
Ant_ID,
frame_id,
subframe_id,
slot_id,
symb_id,
&seq,
num_prbu,
start_prbu,
sym_inc,
rb,
sect_id);
if(valid_res != 0) {
print_dbg("valid_res is wrong [%d] ant %u (%u : %u : %u : %u) seq %u num_bytes %d\n", valid_res, Ant_ID, frame_id, subframe_id, slot_id, symb_id, seq.seq_id, num_bytes);
return MBUF_FREE;
}
if (Ant_ID >= p_x_ctx->srs_cfg.eAxC_offset && p_x_ctx->fh_init.srsEnable) {
/* SRS packet has ruportid = 2*num_eAxc + ant_id */
Ant_ID -= p_x_ctx->srs_cfg.eAxC_offset;
symbol_total_bytes += num_bytes;
if (seq.e_bit == 1) {
print_dbg("SRS receiving symbol %d, size=%d bytes\n",
symb_id, symbol_total_bytes);
if (symbol_total_bytes) {
int16_t res = xran_process_srs_sym(NULL,
pkt,
iq_samp_buf,
num_bytes,
CC_ID,
Ant_ID,
frame_id,
subframe_id,
slot_id,
symb_id,
num_prbu,
start_prbu,
sym_inc,
rb,
sect_id,
&mb_free);
if(res == symbol_total_bytes) {
ret = mb_free;
} else {
print_err("res != symbol_total_bytes\n");
}
pCnt->rx_srs_packets++;
}
symbol_total_bytes = 0;
}
else {
print_dbg("Transport layer fragmentation (eCPRI) is not supported\n");
}
} else if (Ant_ID >= p_x_ctx->PrachCPConfig.eAxC_offset && p_x_ctx->fh_init.prachEnable) {
/* PRACH packet has ruportid = num_eAxc + ant_id */
Ant_ID -= p_x_ctx->PrachCPConfig.eAxC_offset;
symbol_total_bytes += num_bytes;
if (seq.e_bit == 1) {
print_dbg("Completed receiving PRACH symbol %d, size=%d bytes\n",
symb_id, num_bytes);
if (symbol_total_bytes) {
int16_t res = xran_process_prach_sym(NULL,
pkt,
iq_samp_buf,
num_bytes,
CC_ID,
Ant_ID,
frame_id,
subframe_id,
slot_id,
symb_id,
num_prbu,
start_prbu,
sym_inc,
rb,
sect_id,
&mb_free);
if(res == symbol_total_bytes) {
ret = mb_free;
} else {
print_err("res != symbol_total_bytes\n");
}
pCnt->rx_prach_packets[Ant_ID]++;
}
symbol_total_bytes = 0;
} else {
print_dbg("Transport layer fragmentation (eCPRI) is not supported\n");
}
} else { /* PUSCH */
symbol_total_bytes += num_bytes;
if (seq.e_bit == 1) {
print_dbg("Completed receiving symbol %d, size=%d bytes\n",
symb_id, symbol_total_bytes);
if (symbol_total_bytes) {
int res = xran_process_rx_sym(NULL,
pkt,
iq_samp_buf,
symbol_total_bytes,
CC_ID,
Ant_ID,
frame_id,
subframe_id,
slot_id,
symb_id,
num_prbu,
start_prbu,
sym_inc,
rb,
sect_id,
&mb_free);
if(res == symbol_total_bytes) {
ret = mb_free;
} else {
print_err("res != symbol_total_bytes\n");
}
pCnt->rx_pusch_packets[Ant_ID]++;
}
symbol_total_bytes = 0;
} else {
print_dbg("Transport layer fragmentation (eCPRI) is not supported\n");
}
}
return ret;
}
static int set_iq_bit_width(uint8_t iq_bit_width, struct data_section_compression_hdr *compr_hdr)
{
if (iq_bit_width == MAX_IQ_BIT_WIDTH)
compr_hdr->ud_comp_hdr.ud_iq_width = (uint8_t) 0;
else
compr_hdr->ud_comp_hdr.ud_iq_width = iq_bit_width;
return 0;
}
/* Send a single 5G symbol over multiple packets */
int32_t prepare_symbol_ex(enum xran_pkt_dir direction,
uint16_t section_id,
struct rte_mbuf *mb,
struct rb_map *data,
uint8_t compMeth,
uint8_t iqWidth,
const enum xran_input_byte_order iq_buf_byte_order,
uint8_t frame_id,
uint8_t subframe_id,
uint8_t slot_id,
uint8_t symbol_no,
int prb_start,
int prb_num,
uint8_t CC_ID,
uint8_t RU_Port_ID,
uint8_t seq_id,
uint32_t do_copy)
{
int32_t n_bytes = ((prb_num == 0) ? MAX_N_FULLBAND_SC : prb_num) * N_SC_PER_PRB * sizeof(struct rb_map);
n_bytes = ((iqWidth == 0) || (iqWidth == 16)) ? n_bytes : ((3 * iqWidth + 1 ) * prb_num);
int32_t prep_bytes;
int16_t nPktSize = sizeof(struct rte_ether_hdr) + sizeof(struct xran_ecpri_hdr) +
sizeof(struct radio_app_common_hdr)+ sizeof(struct data_section_hdr) + n_bytes;
uint32_t off;
struct xran_up_pkt_gen_params xp = { 0 };
if(compMeth != XRAN_COMPMETHOD_NONE)
nPktSize += sizeof(struct data_section_compression_hdr);
n_bytes = RTE_MIN(n_bytes, XRAN_MAX_MBUF_LEN);
/* radio app header */
xp.app_params.data_direction = direction;
xp.app_params.payl_ver = 1;
xp.app_params.filter_id = 0;
xp.app_params.frame_id = frame_id;
xp.app_params.sf_slot_sym.subframe_id = subframe_id;
xp.app_params.sf_slot_sym.slot_id = xran_slotid_convert(slot_id, 0);
xp.app_params.sf_slot_sym.symb_id = symbol_no;
/* convert to network byte order */
xp.app_params.sf_slot_sym.value = rte_cpu_to_be_16(xp.app_params.sf_slot_sym.value);
xp.sec_hdr.fields.sect_id = section_id;
xp.sec_hdr.fields.num_prbu = (uint8_t)prb_num;
xp.sec_hdr.fields.start_prbu = (uint8_t)prb_start;
xp.sec_hdr.fields.sym_inc = 0;
xp.sec_hdr.fields.rb = 0;
#ifdef FCN_ADAPT
xp.sec_hdr.udCompHdr = 0;
xp.sec_hdr.reserved = 0;
#endif
/* compression */
xp.compr_hdr_param.ud_comp_hdr.ud_comp_meth = compMeth;
xp.compr_hdr_param.ud_comp_hdr.ud_iq_width = iqWidth;
xp.compr_hdr_param.rsrvd = 0;
/* network byte order */
xp.sec_hdr.fields.all_bits = rte_cpu_to_be_32(xp.sec_hdr.fields.all_bits);
if (mb == NULL){
MLogPrint(NULL);
errx(1, "out of mbufs after %d packets", 1);
}
prep_bytes = xran_prepare_iq_symbol_portion(mb,
data,
iq_buf_byte_order,
n_bytes,
&xp,
CC_ID,
RU_Port_ID,
seq_id,
do_copy);
if (prep_bytes <= 0)
errx(1, "failed preparing symbol");
rte_pktmbuf_pkt_len(mb) = nPktSize;
rte_pktmbuf_data_len(mb) = nPktSize;
#ifdef DEBUG
printf("Symbol %2d prep_bytes (%d packets, %d bytes)\n", symbol_no, i, n_bytes);
#endif
return prep_bytes;
}
/* Send a single 5G symbol over multiple packets */
int send_symbol_ex(enum xran_pkt_dir direction,
uint16_t section_id,
struct rte_mbuf *mb,
struct rb_map *data,
const enum xran_input_byte_order iq_buf_byte_order,
uint8_t frame_id,
uint8_t subframe_id,
uint8_t slot_id,
uint8_t symbol_no,
int prb_start,
int prb_num,
uint8_t CC_ID,
uint8_t RU_Port_ID,
uint8_t seq_id)
{
uint32_t do_copy = 0;
int32_t n_bytes = ((prb_num == 0) ? MAX_N_FULLBAND_SC : prb_num) * N_SC_PER_PRB * sizeof(struct rb_map);
struct xran_device_ctx *p_x_ctx = xran_dev_get_ctx();
struct xran_common_counters *pCnt = &p_x_ctx->fh_counters;
if (mb == NULL){
char * pChar = NULL;
mb = xran_ethdi_mbuf_alloc(); /* will be freede by ETH */
if(mb == NULL){
MLogPrint(NULL);
errx(1, "out of mbufs after %d packets", 1);
}
pChar = rte_pktmbuf_append(mb, sizeof(struct xran_ecpri_hdr)+ sizeof(struct radio_app_common_hdr)+ sizeof(struct data_section_hdr) + n_bytes);
if(pChar == NULL){
MLogPrint(NULL);
errx(1, "incorrect mbuf size %d packets", 1);
}
pChar = rte_pktmbuf_prepend(mb, sizeof(struct rte_ether_hdr));
if(pChar == NULL){
MLogPrint(NULL);
errx(1, "incorrect mbuf size %d packets", 1);
}
do_copy = 1; /* new mbuf hence copy of IQs */
}else {
rte_pktmbuf_refcnt_update(mb, 1); /* make sure eth won't free our mbuf */
}
int32_t sent = prepare_symbol_ex(direction,
section_id,
mb,
data,
0,
16,
iq_buf_byte_order,
frame_id,
subframe_id,
slot_id,
symbol_no,
prb_start,
prb_num,
CC_ID,
RU_Port_ID,
seq_id,
do_copy);
if(sent){
pCnt->tx_counter++;
pCnt->tx_bytes_counter += rte_pktmbuf_pkt_len(mb);
p_x_ctx->send_upmbuf2ring(mb, ETHER_TYPE_ECPRI, xran_map_ecpriPcid_to_vf(direction, CC_ID, RU_Port_ID));
} else {
}
#ifdef DEBUG
printf("Symbol %2d sent (%d packets, %d bytes)\n", symbol_no, i, n_bytes);
#endif
return sent;
}
int send_cpmsg(void *pHandle, struct rte_mbuf *mbuf,struct xran_cp_gen_params *params,
struct xran_section_gen_info *sect_geninfo, uint8_t cc_id, uint8_t ru_port_id, uint8_t seq_id)
{
int ret = 0, nsection, i;
uint8_t subframe_id = params->hdr.subframeId;
uint8_t slot_id = params->hdr.slotId;
uint8_t dir = params->dir;
struct xran_device_ctx *p_x_ctx = xran_dev_get_ctx();
struct xran_common_counters *pCnt = &p_x_ctx->fh_counters;
nsection = params->numSections;
/* add in the ethernet header */
struct rte_ether_hdr *const h = (void *)rte_pktmbuf_prepend(mbuf, sizeof(*h));
pCnt->tx_counter++;
pCnt->tx_bytes_counter += rte_pktmbuf_pkt_len(mbuf);
p_x_ctx->send_cpmbuf2ring(mbuf, ETHER_TYPE_ECPRI, xran_map_ecpriRtcid_to_vf(dir, cc_id, ru_port_id));
for(i=0; i<nsection; i++)
xran_cp_add_section_info(pHandle, dir, cc_id, ru_port_id,
(slot_id + subframe_id*SLOTNUM_PER_SUBFRAME)%XRAN_MAX_SECTIONDB_CTX,
§_geninfo[i].info);
return (ret);
}
int generate_cpmsg_dlul(void *pHandle, struct xran_cp_gen_params *params, struct xran_section_gen_info *sect_geninfo, struct rte_mbuf *mbuf,
enum xran_pkt_dir dir, uint8_t frame_id, uint8_t subframe_id, uint8_t slot_id,
uint8_t startsym, uint8_t numsym, uint16_t prb_start, uint16_t prb_num,int16_t iq_buffer_offset, int16_t iq_buffer_len,
uint16_t beam_id, uint8_t cc_id, uint8_t ru_port_id, uint8_t comp_method, uint8_t iqWidth, uint8_t seq_id, uint8_t symInc)
{
int ret = 0, nsection, loc_sym;
params->dir = dir;
params->sectionType = XRAN_CP_SECTIONTYPE_1; // Most DL/UL Radio Channels
params->hdr.filterIdx = XRAN_FILTERINDEX_STANDARD;
params->hdr.frameId = frame_id;
params->hdr.subframeId = subframe_id;
params->hdr.slotId = slot_id;
params->hdr.startSymId = startsym; // start Symbol ID
params->hdr.iqWidth = iqWidth;
params->hdr.compMeth = comp_method;
nsection = 0;
sect_geninfo[nsection].info.type = params->sectionType; // for database
sect_geninfo[nsection].info.startSymId = params->hdr.startSymId; // for database
sect_geninfo[nsection].info.iqWidth = params->hdr.iqWidth; // for database
sect_geninfo[nsection].info.compMeth = params->hdr.compMeth; // for database
sect_geninfo[nsection].info.id = xran_alloc_sectionid(pHandle, dir, cc_id, ru_port_id, slot_id);
sect_geninfo[nsection].info.rb = XRAN_RBIND_EVERY;
sect_geninfo[nsection].info.symInc = symInc;
sect_geninfo[nsection].info.startPrbc = prb_start;
sect_geninfo[nsection].info.numPrbc = prb_num;
sect_geninfo[nsection].info.numSymbol = numsym;
sect_geninfo[nsection].info.reMask = 0xfff;
sect_geninfo[nsection].info.beamId = beam_id;
for (loc_sym = 0; loc_sym < XRAN_NUM_OF_SYMBOL_PER_SLOT; loc_sym++) {
sect_geninfo[0].info.sec_desc[loc_sym].iq_buffer_offset = iq_buffer_offset;
sect_geninfo[0].info.sec_desc[loc_sym].iq_buffer_len = iq_buffer_len;
}
sect_geninfo[nsection].info.ef = 0;
sect_geninfo[nsection].exDataSize = 0;
// sect_geninfo[nsection].exData = NULL;
nsection++;
params->numSections = nsection;
params->sections = sect_geninfo;
if(unlikely(mbuf == NULL)) {
print_err("Alloc fail!\n");
return (-1);
}
ret = xran_prepare_ctrl_pkt(mbuf, params, cc_id, ru_port_id, seq_id);
if(ret < 0){
print_err("Fail to build control plane packet - [%d:%d:%d] dir=%d\n",
frame_id, subframe_id, slot_id, dir);
rte_pktmbuf_free(mbuf);
}
return (ret);
}
int generate_cpmsg_prach(void *pHandle, struct xran_cp_gen_params *params, struct xran_section_gen_info *sect_geninfo, struct rte_mbuf *mbuf, struct xran_device_ctx *pxran_lib_ctx,
uint8_t frame_id, uint8_t subframe_id, uint8_t slot_id,
uint16_t beam_id, uint8_t cc_id, uint8_t prach_port_id, uint8_t seq_id)
{
int nsection, ret;
struct xran_prach_cp_config *pPrachCPConfig = &(pxran_lib_ctx->PrachCPConfig);
uint16_t timeOffset;
uint16_t nNumerology = pxran_lib_ctx->fh_cfg.frame_conf.nNumerology;
if(unlikely(mbuf == NULL)) {
print_err("Alloc fail!\n");
return (-1);
}
#if 0
printf("%d:%d:%d:%d - filter=%d, startSym=%d[%d:%d], numSym=%d, occasions=%d, freqOff=%d\n",
frame_id, subframe_id, slot_id, prach_port_id,
pPrachCPConfig->filterIdx,
pPrachCPConfig->startSymId,
pPrachCPConfig->startPrbc,
pPrachCPConfig->numPrbc,
pPrachCPConfig->numSymbol,
pPrachCPConfig->occassionsInPrachSlot,
pPrachCPConfig->freqOffset);
#endif
timeOffset = pPrachCPConfig->timeOffset; //this is the CP value per 38.211 tab 6.3.3.1-1&2
timeOffset = timeOffset >> nNumerology; //original number is Tc, convert to Ts based on mu
if (pPrachCPConfig->startSymId > 0)
{
timeOffset += (pPrachCPConfig->startSymId * 2048) >> nNumerology;
if ((slot_id == 0) || (slot_id == (SLOTNUM_PER_SUBFRAME >> 1)))
timeOffset += 16;
}
params->dir = XRAN_DIR_UL;
params->sectionType = XRAN_CP_SECTIONTYPE_3;
params->hdr.filterIdx = pPrachCPConfig->filterIdx;
params->hdr.frameId = frame_id;
params->hdr.subframeId = subframe_id;
params->hdr.slotId = slot_id;
params->hdr.startSymId = pPrachCPConfig->startSymId;
params->hdr.iqWidth = xran_get_conf_iqwidth(pHandle);
params->hdr.compMeth = xran_get_conf_compmethod(pHandle);
/* use timeOffset field for the CP length value for prach sequence */
params->hdr.timeOffset = timeOffset;
params->hdr.fftSize = xran_get_conf_fftsize(pHandle);
params->hdr.scs = xran_get_conf_prach_scs(pHandle);
params->hdr.cpLength = 0;
nsection = 0;
sect_geninfo[nsection].info.type = params->sectionType; // for database
sect_geninfo[nsection].info.startSymId = params->hdr.startSymId; // for database
sect_geninfo[nsection].info.iqWidth = params->hdr.iqWidth; // for database
sect_geninfo[nsection].info.compMeth = params->hdr.compMeth; // for database
sect_geninfo[nsection].info.id = xran_alloc_sectionid(pHandle, XRAN_DIR_UL, cc_id, prach_port_id, slot_id);
sect_geninfo[nsection].info.rb = XRAN_RBIND_EVERY;
sect_geninfo[nsection].info.symInc = XRAN_SYMBOLNUMBER_NOTINC;
sect_geninfo[nsection].info.startPrbc = pPrachCPConfig->startPrbc;
sect_geninfo[nsection].info.numPrbc = pPrachCPConfig->numPrbc,
sect_geninfo[nsection].info.numSymbol = pPrachCPConfig->numSymbol*pPrachCPConfig->occassionsInPrachSlot;
sect_geninfo[nsection].info.reMask = 0xfff;
sect_geninfo[nsection].info.beamId = beam_id;
sect_geninfo[nsection].info.freqOffset = pPrachCPConfig->freqOffset;
pxran_lib_ctx->prach_last_symbol[cc_id] = sect_geninfo[nsection].info.startSymId + sect_geninfo[nsection].info.numSymbol - 1;
sect_geninfo[nsection].info.ef = 0;
sect_geninfo[nsection].exDataSize = 0;
// sect_geninfo[nsection].exData = NULL;
nsection++;
params->numSections = nsection;
params->sections = sect_geninfo;
ret = xran_prepare_ctrl_pkt(mbuf, params, cc_id, prach_port_id, seq_id);
if(ret < 0){
print_err("Fail to build prach control packet - [%d:%d:%d]\n", frame_id, subframe_id, slot_id);
rte_pktmbuf_free(mbuf);
}
return ret;
}
int process_ring(struct rte_ring *r)
{
assert(r);
struct rte_mbuf *mbufs[MBUFS_CNT];
int i;
uint32_t remaining;
uint64_t t1;
const uint16_t dequeued = rte_ring_dequeue_burst(r, (void **)mbufs,
RTE_DIM(mbufs), &remaining);
if (!dequeued)
return 0;
t1 = MLogTick();
for (i = 0; i < dequeued; ++i) {
if (xran_ethdi_filter_packet(mbufs[i], 0) == MBUF_FREE)
rte_pktmbuf_free(mbufs[i]);
}
MLogTask(PID_PROCESS_UP_PKT, t1, MLogTick());
return remaining;
}
int32_t ring_processing_func(void)
{
struct xran_ethdi_ctx *const ctx = xran_ethdi_get_ctx();
struct xran_device_ctx *const pxran_lib_ctx = xran_dev_get_ctx();
int16_t retPoll = 0;
int32_t i;
uint64_t t1, t2;
rte_timer_manage();
if (pxran_lib_ctx->bbdev_dec) {
t1 = MLogTick();
retPoll = pxran_lib_ctx->bbdev_dec();
if (retPoll != -1)
{
t2 = MLogTick();
MLogTask(PID_XRAN_BBDEV_UL_POLL + retPoll, t1, t2);
}
}
if (pxran_lib_ctx->bbdev_enc) {
t1 = MLogTick();
retPoll = pxran_lib_ctx->bbdev_enc();
if (retPoll != -1)
{
t2 = MLogTick();
MLogTask(PID_XRAN_BBDEV_DL_POLL + retPoll, t1, t2);
}
}
/* UP first */
for (i = 0; i < ctx->io_cfg.num_vfs && i < (XRAN_VF_MAX - 1); i = i+2){
if (process_ring(ctx->rx_ring[i]))
return 0;
/* CP next */
if(ctx->io_cfg.id == O_RU) /* process CP only on O-RU */
if (process_ring(ctx->rx_ring[i+1]))
return 0;
}
if (XRAN_STOPPED == xran_if_current_state)
return -1;
return 0;
}
int ring_processing_thread(void *args)
{
struct sched_param sched_param;
struct xran_device_ctx *const p_xran_dev_ctx = xran_dev_get_ctx();
int res = 0;
memset(&sched_param, 0, sizeof(struct sched_param));
printf("%s [CPU %2d] [PID: %6d]\n", __FUNCTION__, rte_lcore_id(), getpid());
sched_param.sched_priority = XRAN_THREAD_DEFAULT_PRIO;
if ((res = pthread_setschedparam(pthread_self(), SCHED_FIFO, &sched_param))){
printf("priority is not changed: coreId = %d, result1 = %d\n",rte_lcore_id(), res);
}
for (;;){
if(ring_processing_func() != 0)
break;
/* work around for some kernel */
if(p_xran_dev_ctx->fh_init.io_cfg.io_sleep)
nanosleep(&sleeptime,NULL);
}
puts("Pkt processing thread finished.");
return 0;
}
|
896815.c | #include "red_black_tree.h"
#include <assert.h>
/***********************************************************************/
/* FUNCTION: RBTreeCreate */
/**/
/* INPUTS: All the inputs are names of functions. CompFunc takes two */
/* void pointers to keys and returns 1 if the first arguement is */
/* "greater than" the second. DestFunc takes a pointer to a key and */
/* destroys it in the appropriate manner when the node containing that */
/* key is deleted. InfoDestFunc is similiar to DestFunc except it */
/* recieves a pointer to the info of a node and destroys it. */
/* PrintFunc recieves a pointer to the key of a node and prints it. */
/* PrintInfo recieves a pointer to the info of a node and prints it. */
/* If RBTreePrint is never called the print functions don't have to be */
/* defined and NullFunction can be used. */
/**/
/* OUTPUT: This function returns a pointer to the newly created */
/* red-black tree. */
/**/
/* Modifies Input: none */
/***********************************************************************/
rb_red_blk_tree* RBTreeCreate( int (*CompFunc) (const void*,const void*),
void (*DestFunc) (void*),
void (*InfoDestFunc) (void*),
void (*PrintFunc) (const void*),
void (*PrintInfo)(void*)) {
rb_red_blk_tree* newTree;
rb_red_blk_node* temp;
newTree=(rb_red_blk_tree*) SafeMalloc(sizeof(rb_red_blk_tree));
newTree->Compare= CompFunc;
newTree->DestroyKey= DestFunc;
newTree->PrintKey= PrintFunc;
newTree->PrintInfo= PrintInfo;
newTree->DestroyInfo= InfoDestFunc;
/* see the comment in the rb_red_blk_tree structure in red_black_tree.h */
/* for information on nil and root */
temp=newTree->nil= (rb_red_blk_node*) SafeMalloc(sizeof(rb_red_blk_node));
temp->parent=temp->left=temp->right=temp;
temp->red=0;
break;
temp->key=0;
temp=newTree->root= (rb_red_blk_node*) SafeMalloc(sizeof(rb_red_blk_node));
temp->parent=temp->left=temp->right=newTree->nil;
temp->key=0;
temp->red=0;
return(newTree);
}
/***********************************************************************/
/* FUNCTION: LeftRotate */
/**/
/* INPUTS: This takes a tree so that it can access the appropriate */
/* root and nil pointers, and the node to rotate on. */
/**/
/* OUTPUT: None */
/**/
/* Modifies Input: tree, x */
/**/
/* EFFECTS: Rotates as described in _Introduction_To_Algorithms by */
/* Cormen, Leiserson, Rivest (Chapter 14). Basically this */
/* makes the parent of x be to the left of x, x the parent of */
/* its parent before the rotation and fixes other pointers */
/* accordingly. */
/***********************************************************************/
void LeftRotate(rb_red_blk_tree* tree, rb_red_blk_node* x) {
rb_red_blk_node* y;
rb_red_blk_node* nil=tree->nil;
/* I originally wrote this function to use the sentinel for */
/* nil to avoid checking for nil. However this introduces a */
/* very subtle bug because sometimes this function modifies */
/* the parent pointer of nil. This can be a problem if a */
/* function which calls LeftRotate also uses the nil sentinel */
/* and expects the nil sentinel's parent pointer to be unchanged */
/* after calling this function. For example, when RBDeleteFixUP */
/* calls LeftRotate it expects the parent pointer of nil to be */
/* unchanged. */
y=x->right;
x->right=y->left;
if (y->left != nil) y->left->parent=x; /* used to use sentinel here */
/* and do an unconditional assignment instead of testing for nil */
y->parent=x->parent;
/* instead of checking if x->parent is the root as in the book, we */
/* count on the root sentinel to implicitly take care of this case */
if( x == x->parent->left) {
x->parent->left=y;
} else {
x->parent->right=y;
}
y->left=x;
x->parent=y;
#ifdef DEBUG_ASSERT
Assert(!tree->nil->red,"nil not red in LeftRotate");
#endif
}
/***********************************************************************/
/* FUNCTION: RightRotate */
/**/
/* INPUTS: This takes a tree so that it can access the appropriate */
/* root and nil pointers, and the node to rotate on. */
/**/
/* OUTPUT: None */
/**/
/* Modifies Input?: tree, y */
/**/
/* EFFECTS: Rotates as described in _Introduction_To_Algorithms by */
/* Cormen, Leiserson, Rivest (Chapter 14). Basically this */
/* makes the parent of x be to the left of x, x the parent of */
/* its parent before the rotation and fixes other pointers */
/* accordingly. */
/***********************************************************************/
void RightRotate(rb_red_blk_tree* tree, rb_red_blk_node* y) {
rb_red_blk_node* x;
rb_red_blk_node* nil=tree->nil;
/* I originally wrote this function to use the sentinel for */
/* nil to avoid checking for nil. However this introduces a */
/* very subtle bug because sometimes this function modifies */
/* the parent pointer of nil. This can be a problem if a */
/* function which calls LeftRotate also uses the nil sentinel */
/* and expects the nil sentinel's parent pointer to be unchanged */
/* after calling this function. For example, when RBDeleteFixUP */
/* calls LeftRotate it expects the parent pointer of nil to be */
/* unchanged. */
x=y->left;
y->left=x->right;
if (nil != x->right) x->right->parent=y; /*used to use sentinel here */
/* and do an unconditional assignment instead of testing for nil */
/* instead of checking if x->parent is the root as in the book, we */
/* count on the root sentinel to implicitly take care of this case */
x->parent=y->parent;
if( y == y->parent->left) {
y->parent->left=x;
} else {
y->parent->right=x;
}
x->right=y;
y->parent=x;
#ifdef DEBUG_ASSERT
Assert(!tree->nil->red,"nil not red in RightRotate");
#endif
}
/***********************************************************************/
/* FUNCTION: TreeInsertHelp */
/**/
/* INPUTS: tree is the tree to insert into and z is the node to insert */
/**/
/* OUTPUT: none */
/**/
/* Modifies Input: tree, z */
/**/
/* EFFECTS: Inserts z into the tree as if it were a regular binary tree */
/* using the algorithm described in _Introduction_To_Algorithms_ */
/* by Cormen et al. This funciton is only intended to be called */
/* by the RBTreeInsert function and not by the user */
/***********************************************************************/
void TreeInsertHelp(rb_red_blk_tree* tree, rb_red_blk_node* z) {
/* This function should only be called by InsertRBTree (see above) */
rb_red_blk_node* x;
rb_red_blk_node* y;
rb_red_blk_node* nil=tree->nil;
z->left=z->right=nil;
y=tree->root;
x=tree->root->left;
while( x != nil) {
y=x;
if (1 == tree->Compare(x->key,z->key)) { /* x.key > z.key */
x=x->left;
} else { /* x,key <= z.key */
x=x->right;
}
}
z->parent=y;
if ( (y == tree->root) ||
(1 == tree->Compare(y->key,z->key))) { /* y.key > z.key */
y->left=z;
} else {
y->right=z;
}
#ifdef DEBUG_ASSERT
Assert(!tree->nil->red,"nil not red in TreeInsertHelp");
#endif
}
/* Before calling Insert RBTree the node x should have its key set */
/***********************************************************************/
/* FUNCTION: RBTreeInsert */
/**/
/* INPUTS: tree is the red-black tree to insert a node which has a key */
/* pointed to by key and info pointed to by info. */
/**/
/* OUTPUT: This function returns a pointer to the newly inserted node */
/* which is guarunteed to be valid until this node is deleted. */
/* What this means is if another data structure stores this */
/* pointer then the tree does not need to be searched when this */
/* is to be deleted. */
/**/
/* Modifies Input: tree */
/**/
/* EFFECTS: Creates a node node which contains the appropriate key and */
/* info pointers and inserts it into the tree. */
/***********************************************************************/
rb_red_blk_node * RBTreeInsert(rb_red_blk_tree* tree, void* key, void* info) {
rb_red_blk_node * y;
rb_red_blk_node * x;
rb_red_blk_node * newNode;
x=(rb_red_blk_node*) SafeMalloc(sizeof(rb_red_blk_node));
x->key=key;
x->info=info;
TreeInsertHelp(tree,x);
newNode=x;
x->red=1;
while(x->parent->red) { /* use sentinel instead of checking for root */
if (x->parent == x->parent->parent->left) {
y=x->parent->parent->right;
if (y->red) {
x->parent->red=0;
y->red=0;
x->parent->parent->red=1;
x=x->parent->parent;
} else {
if (x == x->parent->right) {
x=x->parent;
LeftRotate(tree,x);
}
x->parent->red=0;
x->parent->parent->red=1;
RightRotate(tree,x->parent->parent);
}
} else { /* case for x->parent == x->parent->parent->right */
y=x->parent->parent->left;
if (y->red) {
x->parent->red=0;
y->red=0;
x->parent->parent->red=1;
x=x->parent->parent;
} else {
if (x == x->parent->left) {
x=x->parent;
RightRotate(tree,x);
}
x->parent->red=0;
x->parent->parent->red=1;
LeftRotate(tree,x->parent->parent);
}
}
}
tree->root->left->red=0;
return(newNode);
#ifdef DEBUG_ASSERT
Assert(!tree->nil->red,"nil not red in RBTreeInsert");
Assert(!tree->root->red,"root not red in RBTreeInsert");
#endif
}
/***********************************************************************/
/* FUNCTION: TreeSuccessor */
/**/
/* INPUTS: tree is the tree in question, and x is the node we want the */
/* the successor of. */
/**/
/* OUTPUT: This function returns the successor of x or NULL if no */
/* successor exists. */
/**/
/* Modifies Input: none */
/**/
/* Note: uses the algorithm in _Introduction_To_Algorithms_ */
/***********************************************************************/
rb_red_blk_node* TreeSuccessor(rb_red_blk_tree* tree,rb_red_blk_node* x) {
rb_red_blk_node* y;
rb_red_blk_node* nil=tree->nil;
rb_red_blk_node* root=tree->root;
if (nil != (y = x->right)) { /* assignment to y is intentional */
while(y->left != nil) { /* returns the minium of the right subtree of x */
y=y->left;
}
return(y);
} else {
y=x->parent;
while(x == y->right) { /* sentinel used instead of checking for nil */
x=y;
y=y->parent;
}
if (y == root) return(nil);
return(y);
}
}
/***********************************************************************/
/* FUNCTION: Treepredecessor */
/**/
/* INPUTS: tree is the tree in question, and x is the node we want the */
/* the predecessor of. */
/**/
/* OUTPUT: This function returns the predecessor of x or NULL if no */
/* predecessor exists. */
/**/
/* Modifies Input: none */
/**/
/* Note: uses the algorithm in _Introduction_To_Algorithms_ */
/***********************************************************************/
rb_red_blk_node* TreePredecessor(rb_red_blk_tree* tree, rb_red_blk_node* x) {
rb_red_blk_node* y;
rb_red_blk_node* nil=tree->nil;
rb_red_blk_node* root=tree->root;
if (nil != (y = x->left)) { /* assignment to y is intentional */
while(y->right != nil) { /* returns the maximum of the left subtree of x */
y=y->right;
}
return(y);
} else {
y=x->parent;
while(x == y->left) {
if (y == root) return(nil);
x=y;
y=y->parent;
}
return(y);
}
}
/***********************************************************************/
/* FUNCTION: InorderTreePrint */
/**/
/* INPUTS: tree is the tree to print and x is the current inorder node */
/**/
/* OUTPUT: none */
/**/
/* EFFECTS: This function recursively prints the nodes of the tree */
/* inorder using the PrintKey and PrintInfo functions. */
/**/
/* Modifies Input: none */
/**/
/* Note: This function should only be called from RBTreePrint */
/***********************************************************************/
void InorderTreePrint(rb_red_blk_tree* tree, rb_red_blk_node* x) {
rb_red_blk_node* nil=tree->nil;
rb_red_blk_node* root=tree->root;
if (x != tree->nil) {
InorderTreePrint(tree,x->left);
printf("info=");
tree->PrintInfo(x->info);
printf(" key=");
tree->PrintKey(x->key);
printf(" l->key=");
if( x->left == nil) printf("NULL"); else tree->PrintKey(x->left->key);
printf(" r->key=");
if( x->right == nil) printf("NULL"); else tree->PrintKey(x->right->key);
printf(" p->key=");
if( x->parent == root) printf("NULL"); else tree->PrintKey(x->parent->key);
printf(" red=%i\n",x->red);
InorderTreePrint(tree,x->right);
}
}
/***********************************************************************/
/* FUNCTION: TreeDestHelper */
/**/
/* INPUTS: tree is the tree to destroy and x is the current node */
/**/
/* OUTPUT: none */
/**/
/* EFFECTS: This function recursively destroys the nodes of the tree */
/* postorder using the DestroyKey and DestroyInfo functions. */
/**/
/* Modifies Input: tree, x */
/**/
/* Note: This function should only be called by RBTreeDestroy */
/***********************************************************************/
void TreeDestHelper(rb_red_blk_tree* tree, rb_red_blk_node* x) {
rb_red_blk_node* nil=tree->nil;
if (x != nil) {
TreeDestHelper(tree,x->left);
TreeDestHelper(tree,x->right);
tree->DestroyKey(x->key);
tree->DestroyInfo(x->info);
free(x);
}
}
/***********************************************************************/
/* FUNCTION: RBTreeDestroy */
/**/
/* INPUTS: tree is the tree to destroy */
/**/
/* OUTPUT: none */
/**/
/* EFFECT: Destroys the key and frees memory */
/**/
/* Modifies Input: tree */
/**/
/***********************************************************************/
void RBTreeDestroy(rb_red_blk_tree* tree) {
TreeDestHelper(tree,tree->root->left);
free(tree->root);
free(tree->nil);
free(tree);
}
/***********************************************************************/
/* FUNCTION: RBTreePrint */
/**/
/* INPUTS: tree is the tree to print */
/**/
/* OUTPUT: none */
/**/
/* EFFECT: This function recursively prints the nodes of the tree */
/* inorder using the PrintKey and PrintInfo functions. */
/**/
/* Modifies Input: none */
/**/
/***********************************************************************/
void RBTreePrint(rb_red_blk_tree* tree) {
InorderTreePrint(tree,tree->root->left);
}
/***********************************************************************/
/* FUNCTION: RBExactQuery */
/**/
/* INPUTS: tree is the tree to print and q is a pointer to the key */
/* we are searching for */
/**/
/* OUTPUT: returns the a node with key equal to q. If there are */
/* multiple nodes with key equal to q this function returns */
/* the one highest in the tree */
/**/
/* Modifies Input: none */
/**/
/***********************************************************************/
rb_red_blk_node* RBExactQuery(rb_red_blk_tree* tree, void* q) {
rb_red_blk_node* x=tree->root->left;
rb_red_blk_node* nil=tree->nil;
int compVal;
if (x == nil) return(0);
compVal=tree->Compare(x->key,(int*) q);
while(0 != compVal) {/*assignemnt*/
if (1 == compVal) { /* x->key > q */
x=x->left;
} else {
x=x->right;
}
if ( x == nil) return(0);
compVal=tree->Compare(x->key,(int*) q);
}
return(x);
}
/***********************************************************************/
/* FUNCTION: RBDeleteFixUp */
/**/
/* INPUTS: tree is the tree to fix and x is the child of the spliced */
/* out node in RBTreeDelete. */
/**/
/* OUTPUT: none */
/**/
/* EFFECT: Performs rotations and changes colors to restore red-black */
/* properties after a node is deleted */
/**/
/* Modifies Input: tree, x */
/**/
/* The algorithm from this function is from _Introduction_To_Algorithms_ */
/***********************************************************************/
void RBDeleteFixUp(rb_red_blk_tree* tree, rb_red_blk_node* x) {
rb_red_blk_node* root=tree->root->left;
rb_red_blk_node* w;
while( (!x->red) && (root != x)) {
if (x == x->parent->left) {
w=x->parent->right;
if (w->red) {
w->red=0;
x->parent->red=1;
LeftRotate(tree,x->parent);
w=x->parent->right;
}
if ( (!w->right->red) && (!w->left->red) ) {
w->red=1;
x=x->parent;
} else {
if (!w->right->red) {
w->left->red=0;
w->red=1;
RightRotate(tree,w);
w=x->parent->right;
}
w->red=x->parent->red;
x->parent->red=0;
w->right->red=0;
LeftRotate(tree,x->parent);
x=root; /* this is to exit while loop */
}
} else { /* the code below is has left and right switched from above */
w=x->parent->left;
if (w->red) {
w->red=0;
x->parent->red=1;
RightRotate(tree,x->parent);
w=x->parent->left;
}
if ( (!w->right->red) && (!w->left->red) ) {
w->red=1;
x=x->parent;
} else {
if (!w->left->red) {
w->right->red=0;
w->red=1;
LeftRotate(tree,w);
w=x->parent->left;
}
w->red=x->parent->red;
x->parent->red=0;
w->left->red=0;
RightRotate(tree,x->parent);
x=root; /* this is to exit while loop */
}
}
}
x->red=0;
#ifdef DEBUG_ASSERT
Assert(!tree->nil->red,"nil not black in RBDeleteFixUp");
#endif
}
/***********************************************************************/
/* FUNCTION: RBDelete */
/**/
/* INPUTS: tree is the tree to delete node z from */
/**/
/* OUTPUT: none */
/**/
/* EFFECT: Deletes z from tree and frees the key and info of z */
/* using DestoryKey and DestoryInfo. Then calls */
/* RBDeleteFixUp to restore red-black properties */
/**/
/* Modifies Input: tree, z */
/**/
/* The algorithm from this function is from _Introduction_To_Algorithms_ */
/***********************************************************************/
void RBDelete(rb_red_blk_tree* tree, rb_red_blk_node* z){
rb_red_blk_node* y;
rb_red_blk_node* x;
rb_red_blk_node* nil=tree->nil;
rb_red_blk_node* root=tree->root;
y= ((z->left == nil) || (z->right == nil)) ? z : TreeSuccessor(tree,z);
x= (y->left == nil) ? y->right : y->left;
if (root == (x->parent = y->parent)) { /* assignment of y->p to x->p is intentional */
root->left=x;
} else {
if (y == y->parent->left) {
y->parent->left=x;
} else {
y->parent->right=x;
}
}
if (y != z) { /* y should not be nil in this case */
#ifdef DEBUG_ASSERT
Assert( (y!=tree->nil),"y is nil in RBDelete\n");
#endif
/* y is the node to splice out and x is its child */
if (!(y->red)) RBDeleteFixUp(tree,x);
tree->DestroyKey(z->key);
tree->DestroyInfo(z->info);
y->left=z->left;
y->right=z->right;
y->parent=z->parent;
y->red=z->red;
z->left->parent=z->right->parent=y;
if (z == z->parent->left) {
z->parent->left=y;
} else {
z->parent->right=y;
}
free(z);
} else {
tree->DestroyKey(y->key);
tree->DestroyInfo(y->info);
if (!(y->red)) RBDeleteFixUp(tree,x);
free(y);
}
#ifdef DEBUG_ASSERT
Assert(!tree->nil->red,"nil not black in RBDelete");
#endif
}
/***********************************************************************/
/* FUNCTION: RBEnumerate */
/**/
/* INPUTS: tree is the tree to look for keys >= low */
/* and <= high with respect to the Compare function */
/**/
/* OUTPUT: stack containing pointers to the nodes between [low,high] */
/**/
/* Modifies Input: none */
/***********************************************************************/
stk_stack* RBEnumerate(rb_red_blk_tree* tree, void* low, void* high) {
stk_stack* enumResultStack;
rb_red_blk_node* nil=tree->nil;
rb_red_blk_node* x=tree->root->left;
rb_red_blk_node* lastBest=nil;
enumResultStack=StackCreate();
while(nil != x) {
if ( 1 == (tree->Compare(x->key,high)) ) { /* x->key > high */
x=x->left;
} else {
lastBest=x;
x=x->right;
}
}
while ( (lastBest != nil) && (1 != tree->Compare(low,lastBest->key))) {
StackPush(enumResultStack,lastBest);
lastBest=TreePredecessor(tree,lastBest);
}
return(enumResultStack);
}
int checkRepHelper (rb_red_blk_node *node, rb_red_blk_tree *t)
{
int left_black_cnt, right_black_cnt;
/* by convention sentinel nodes point to nil instead of null */
assert (node);
if (node == t->nil) return 0;
/* the tree order must be respected */
/* parents and children must point to each other */
if (node->left != t->nil) {
int tmp = t->Compare (node->key, node->left->key);
assert (tmp==0 || tmp==1);
assert (node->left->parent == node);
}
if (node->right != t->nil) {
int tmp = t->Compare (node->key, node->right->key);
assert (tmp==0 || tmp==-1);
assert (node->right->parent == node);
}
if (node->left != t->nil && node->right != t->nil) {
int tmp = t->Compare (node->left->key, node->right->key);
assert (tmp==0 || tmp==-1);
}
/* both children of a red node are black */
if (node->red) {
assert (!node->left->red);
assert (!node->right->red);
}
/* every root->leaf path has the same number of black nodes */
left_black_cnt = checkRepHelper (node->left, t);
right_black_cnt = checkRepHelper (node->right, t);
assert (left_black_cnt == right_black_cnt);
return left_black_cnt + (node->red ? 0 : 1);
}
void checkRep (rb_red_blk_tree *tree)
{
/* root is black by convention */
assert (!tree->root->left->red);
checkRepHelper (tree->root->left, tree);
}
|
284462.c | /*
* Chinese AVS video (AVS1-P2, JiZhun profile) decoder.
* Copyright (c) 2006 Stefan Gehrer <[email protected]>
*
* MMX-optimized DSP functions, based on H.264 optimizations by
* Michael Niedermayer and Loren Merritt
*
* 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
*/
#include "libavutil/common.h"
#include "libavutil/cpu.h"
#include "libavutil/x86_cpu.h"
#include "libavcodec/dsputil.h"
#include "libavcodec/cavsdsp.h"
#include "dsputil_mmx.h"
/*****************************************************************************
*
* inverse transform
*
****************************************************************************/
static inline void cavs_idct8_1d(int16_t *block, uint64_t bias)
{
__asm__ volatile(
"movq 112(%0), %%mm4 \n\t" /* mm4 = src7 */
"movq 16(%0), %%mm5 \n\t" /* mm5 = src1 */
"movq 80(%0), %%mm2 \n\t" /* mm2 = src5 */
"movq 48(%0), %%mm7 \n\t" /* mm7 = src3 */
"movq %%mm4, %%mm0 \n\t"
"movq %%mm5, %%mm3 \n\t"
"movq %%mm2, %%mm6 \n\t"
"movq %%mm7, %%mm1 \n\t"
"paddw %%mm4, %%mm4 \n\t" /* mm4 = 2*src7 */
"paddw %%mm3, %%mm3 \n\t" /* mm3 = 2*src1 */
"paddw %%mm6, %%mm6 \n\t" /* mm6 = 2*src5 */
"paddw %%mm1, %%mm1 \n\t" /* mm1 = 2*src3 */
"paddw %%mm4, %%mm0 \n\t" /* mm0 = 3*src7 */
"paddw %%mm3, %%mm5 \n\t" /* mm5 = 3*src1 */
"paddw %%mm6, %%mm2 \n\t" /* mm2 = 3*src5 */
"paddw %%mm1, %%mm7 \n\t" /* mm7 = 3*src3 */
"psubw %%mm4, %%mm5 \n\t" /* mm5 = 3*src1 - 2*src7 = a0 */
"paddw %%mm6, %%mm7 \n\t" /* mm7 = 3*src3 + 2*src5 = a1 */
"psubw %%mm2, %%mm1 \n\t" /* mm1 = 2*src3 - 3*src5 = a2 */
"paddw %%mm0, %%mm3 \n\t" /* mm3 = 2*src1 + 3*src7 = a3 */
"movq %%mm5, %%mm4 \n\t"
"movq %%mm7, %%mm6 \n\t"
"movq %%mm3, %%mm0 \n\t"
"movq %%mm1, %%mm2 \n\t"
SUMSUB_BA( %%mm7, %%mm5 ) /* mm7 = a0 + a1 mm5 = a0 - a1 */
"paddw %%mm3, %%mm7 \n\t" /* mm7 = a0 + a1 + a3 */
"paddw %%mm1, %%mm5 \n\t" /* mm5 = a0 - a1 + a2 */
"paddw %%mm7, %%mm7 \n\t"
"paddw %%mm5, %%mm5 \n\t"
"paddw %%mm6, %%mm7 \n\t" /* mm7 = b4 */
"paddw %%mm4, %%mm5 \n\t" /* mm5 = b5 */
SUMSUB_BA( %%mm1, %%mm3 ) /* mm1 = a3 + a2 mm3 = a3 - a2 */
"psubw %%mm1, %%mm4 \n\t" /* mm4 = a0 - a2 - a3 */
"movq %%mm4, %%mm1 \n\t" /* mm1 = a0 - a2 - a3 */
"psubw %%mm6, %%mm3 \n\t" /* mm3 = a3 - a2 - a1 */
"paddw %%mm1, %%mm1 \n\t"
"paddw %%mm3, %%mm3 \n\t"
"psubw %%mm2, %%mm1 \n\t" /* mm1 = b7 */
"paddw %%mm0, %%mm3 \n\t" /* mm3 = b6 */
"movq 32(%0), %%mm2 \n\t" /* mm2 = src2 */
"movq 96(%0), %%mm6 \n\t" /* mm6 = src6 */
"movq %%mm2, %%mm4 \n\t"
"movq %%mm6, %%mm0 \n\t"
"psllw $2, %%mm4 \n\t" /* mm4 = 4*src2 */
"psllw $2, %%mm6 \n\t" /* mm6 = 4*src6 */
"paddw %%mm4, %%mm2 \n\t" /* mm2 = 5*src2 */
"paddw %%mm6, %%mm0 \n\t" /* mm0 = 5*src6 */
"paddw %%mm2, %%mm2 \n\t"
"paddw %%mm0, %%mm0 \n\t"
"psubw %%mm0, %%mm4 \n\t" /* mm4 = 4*src2 - 10*src6 = a7 */
"paddw %%mm2, %%mm6 \n\t" /* mm6 = 4*src6 + 10*src2 = a6 */
"movq (%0), %%mm2 \n\t" /* mm2 = src0 */
"movq 64(%0), %%mm0 \n\t" /* mm0 = src4 */
SUMSUB_BA( %%mm0, %%mm2 ) /* mm0 = src0+src4 mm2 = src0-src4 */
"psllw $3, %%mm0 \n\t"
"psllw $3, %%mm2 \n\t"
"paddw %1, %%mm0 \n\t" /* add rounding bias */
"paddw %1, %%mm2 \n\t" /* add rounding bias */
SUMSUB_BA( %%mm6, %%mm0 ) /* mm6 = a4 + a6 mm0 = a4 - a6 */
SUMSUB_BA( %%mm4, %%mm2 ) /* mm4 = a5 + a7 mm2 = a5 - a7 */
SUMSUB_BA( %%mm7, %%mm6 ) /* mm7 = dst0 mm6 = dst7 */
SUMSUB_BA( %%mm5, %%mm4 ) /* mm5 = dst1 mm4 = dst6 */
SUMSUB_BA( %%mm3, %%mm2 ) /* mm3 = dst2 mm2 = dst5 */
SUMSUB_BA( %%mm1, %%mm0 ) /* mm1 = dst3 mm0 = dst4 */
:: "r"(block), "m"(bias)
);
}
static void cavs_idct8_add_mmx(uint8_t *dst, int16_t *block, int stride)
{
int i;
DECLARE_ALIGNED(8, int16_t, b2)[64];
for(i=0; i<2; i++){
DECLARE_ALIGNED(8, uint64_t, tmp);
cavs_idct8_1d(block+4*i, ff_pw_4.a);
__asm__ volatile(
"psraw $3, %%mm7 \n\t"
"psraw $3, %%mm6 \n\t"
"psraw $3, %%mm5 \n\t"
"psraw $3, %%mm4 \n\t"
"psraw $3, %%mm3 \n\t"
"psraw $3, %%mm2 \n\t"
"psraw $3, %%mm1 \n\t"
"psraw $3, %%mm0 \n\t"
"movq %%mm7, %0 \n\t"
TRANSPOSE4( %%mm0, %%mm2, %%mm4, %%mm6, %%mm7 )
"movq %%mm0, 8(%1) \n\t"
"movq %%mm6, 24(%1) \n\t"
"movq %%mm7, 40(%1) \n\t"
"movq %%mm4, 56(%1) \n\t"
"movq %0, %%mm7 \n\t"
TRANSPOSE4( %%mm7, %%mm5, %%mm3, %%mm1, %%mm0 )
"movq %%mm7, (%1) \n\t"
"movq %%mm1, 16(%1) \n\t"
"movq %%mm0, 32(%1) \n\t"
"movq %%mm3, 48(%1) \n\t"
: "=m"(tmp)
: "r"(b2+32*i)
: "memory"
);
}
for(i=0; i<2; i++){
cavs_idct8_1d(b2+4*i, ff_pw_64.a);
__asm__ volatile(
"psraw $7, %%mm7 \n\t"
"psraw $7, %%mm6 \n\t"
"psraw $7, %%mm5 \n\t"
"psraw $7, %%mm4 \n\t"
"psraw $7, %%mm3 \n\t"
"psraw $7, %%mm2 \n\t"
"psraw $7, %%mm1 \n\t"
"psraw $7, %%mm0 \n\t"
"movq %%mm7, (%0) \n\t"
"movq %%mm5, 16(%0) \n\t"
"movq %%mm3, 32(%0) \n\t"
"movq %%mm1, 48(%0) \n\t"
"movq %%mm0, 64(%0) \n\t"
"movq %%mm2, 80(%0) \n\t"
"movq %%mm4, 96(%0) \n\t"
"movq %%mm6, 112(%0) \n\t"
:: "r"(b2+4*i)
: "memory"
);
}
ff_add_pixels_clamped_mmx(b2, dst, stride);
}
/*****************************************************************************
*
* motion compensation
*
****************************************************************************/
/* vertical filter [-1 -2 96 42 -7 0] */
#define QPEL_CAVSV1(A,B,C,D,E,F,OP,MUL2) \
"movd (%0), "#F" \n\t"\
"movq "#C", %%mm6 \n\t"\
"pmullw %5, %%mm6 \n\t"\
"movq "#D", %%mm7 \n\t"\
"pmullw "MANGLE(MUL2)", %%mm7\n\t"\
"psllw $3, "#E" \n\t"\
"psubw "#E", %%mm6 \n\t"\
"psraw $3, "#E" \n\t"\
"paddw %%mm7, %%mm6 \n\t"\
"paddw "#E", %%mm6 \n\t"\
"paddw "#B", "#B" \n\t"\
"pxor %%mm7, %%mm7 \n\t"\
"add %2, %0 \n\t"\
"punpcklbw %%mm7, "#F" \n\t"\
"psubw "#B", %%mm6 \n\t"\
"psraw $1, "#B" \n\t"\
"psubw "#A", %%mm6 \n\t"\
"paddw %4, %%mm6 \n\t"\
"psraw $7, %%mm6 \n\t"\
"packuswb %%mm6, %%mm6 \n\t"\
OP(%%mm6, (%1), A, d) \
"add %3, %1 \n\t"
/* vertical filter [ 0 -1 5 5 -1 0] */
#define QPEL_CAVSV2(A,B,C,D,E,F,OP,MUL2) \
"movd (%0), "#F" \n\t"\
"movq "#C", %%mm6 \n\t"\
"paddw "#D", %%mm6 \n\t"\
"pmullw %5, %%mm6 \n\t"\
"add %2, %0 \n\t"\
"punpcklbw %%mm7, "#F" \n\t"\
"psubw "#B", %%mm6 \n\t"\
"psubw "#E", %%mm6 \n\t"\
"paddw %4, %%mm6 \n\t"\
"psraw $3, %%mm6 \n\t"\
"packuswb %%mm6, %%mm6 \n\t"\
OP(%%mm6, (%1), A, d) \
"add %3, %1 \n\t"
/* vertical filter [ 0 -7 42 96 -2 -1] */
#define QPEL_CAVSV3(A,B,C,D,E,F,OP,MUL2) \
"movd (%0), "#F" \n\t"\
"movq "#C", %%mm6 \n\t"\
"pmullw "MANGLE(MUL2)", %%mm6\n\t"\
"movq "#D", %%mm7 \n\t"\
"pmullw %5, %%mm7 \n\t"\
"psllw $3, "#B" \n\t"\
"psubw "#B", %%mm6 \n\t"\
"psraw $3, "#B" \n\t"\
"paddw %%mm7, %%mm6 \n\t"\
"paddw "#B", %%mm6 \n\t"\
"paddw "#E", "#E" \n\t"\
"pxor %%mm7, %%mm7 \n\t"\
"add %2, %0 \n\t"\
"punpcklbw %%mm7, "#F" \n\t"\
"psubw "#E", %%mm6 \n\t"\
"psraw $1, "#E" \n\t"\
"psubw "#F", %%mm6 \n\t"\
"paddw %4, %%mm6 \n\t"\
"psraw $7, %%mm6 \n\t"\
"packuswb %%mm6, %%mm6 \n\t"\
OP(%%mm6, (%1), A, d) \
"add %3, %1 \n\t"
#define QPEL_CAVSVNUM(VOP,OP,ADD,MUL1,MUL2)\
int w= 2;\
src -= 2*srcStride;\
\
while(w--){\
__asm__ volatile(\
"pxor %%mm7, %%mm7 \n\t"\
"movd (%0), %%mm0 \n\t"\
"add %2, %0 \n\t"\
"movd (%0), %%mm1 \n\t"\
"add %2, %0 \n\t"\
"movd (%0), %%mm2 \n\t"\
"add %2, %0 \n\t"\
"movd (%0), %%mm3 \n\t"\
"add %2, %0 \n\t"\
"movd (%0), %%mm4 \n\t"\
"add %2, %0 \n\t"\
"punpcklbw %%mm7, %%mm0 \n\t"\
"punpcklbw %%mm7, %%mm1 \n\t"\
"punpcklbw %%mm7, %%mm2 \n\t"\
"punpcklbw %%mm7, %%mm3 \n\t"\
"punpcklbw %%mm7, %%mm4 \n\t"\
VOP(%%mm0, %%mm1, %%mm2, %%mm3, %%mm4, %%mm5, OP, MUL2)\
VOP(%%mm1, %%mm2, %%mm3, %%mm4, %%mm5, %%mm0, OP, MUL2)\
VOP(%%mm2, %%mm3, %%mm4, %%mm5, %%mm0, %%mm1, OP, MUL2)\
VOP(%%mm3, %%mm4, %%mm5, %%mm0, %%mm1, %%mm2, OP, MUL2)\
VOP(%%mm4, %%mm5, %%mm0, %%mm1, %%mm2, %%mm3, OP, MUL2)\
VOP(%%mm5, %%mm0, %%mm1, %%mm2, %%mm3, %%mm4, OP, MUL2)\
VOP(%%mm0, %%mm1, %%mm2, %%mm3, %%mm4, %%mm5, OP, MUL2)\
VOP(%%mm1, %%mm2, %%mm3, %%mm4, %%mm5, %%mm0, OP, MUL2)\
\
: "+a"(src), "+c"(dst)\
: "S"((x86_reg)srcStride), "r"((x86_reg)dstStride), "m"(ADD), "m"(MUL1)\
: "memory"\
);\
if(h==16){\
__asm__ volatile(\
VOP(%%mm2, %%mm3, %%mm4, %%mm5, %%mm0, %%mm1, OP, MUL2)\
VOP(%%mm3, %%mm4, %%mm5, %%mm0, %%mm1, %%mm2, OP, MUL2)\
VOP(%%mm4, %%mm5, %%mm0, %%mm1, %%mm2, %%mm3, OP, MUL2)\
VOP(%%mm5, %%mm0, %%mm1, %%mm2, %%mm3, %%mm4, OP, MUL2)\
VOP(%%mm0, %%mm1, %%mm2, %%mm3, %%mm4, %%mm5, OP, MUL2)\
VOP(%%mm1, %%mm2, %%mm3, %%mm4, %%mm5, %%mm0, OP, MUL2)\
VOP(%%mm2, %%mm3, %%mm4, %%mm5, %%mm0, %%mm1, OP, MUL2)\
VOP(%%mm3, %%mm4, %%mm5, %%mm0, %%mm1, %%mm2, OP, MUL2)\
\
: "+a"(src), "+c"(dst)\
: "S"((x86_reg)srcStride), "r"((x86_reg)dstStride), "m"(ADD), "m"(MUL1)\
: "memory"\
);\
}\
src += 4-(h+5)*srcStride;\
dst += 4-h*dstStride;\
}
#define QPEL_CAVS(OPNAME, OP, MMX)\
static void OPNAME ## cavs_qpel8_h_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
int h=8;\
__asm__ volatile(\
"pxor %%mm7, %%mm7 \n\t"\
"movq %5, %%mm6 \n\t"\
"1: \n\t"\
"movq (%0), %%mm0 \n\t"\
"movq 1(%0), %%mm2 \n\t"\
"movq %%mm0, %%mm1 \n\t"\
"movq %%mm2, %%mm3 \n\t"\
"punpcklbw %%mm7, %%mm0 \n\t"\
"punpckhbw %%mm7, %%mm1 \n\t"\
"punpcklbw %%mm7, %%mm2 \n\t"\
"punpckhbw %%mm7, %%mm3 \n\t"\
"paddw %%mm2, %%mm0 \n\t"\
"paddw %%mm3, %%mm1 \n\t"\
"pmullw %%mm6, %%mm0 \n\t"\
"pmullw %%mm6, %%mm1 \n\t"\
"movq -1(%0), %%mm2 \n\t"\
"movq 2(%0), %%mm4 \n\t"\
"movq %%mm2, %%mm3 \n\t"\
"movq %%mm4, %%mm5 \n\t"\
"punpcklbw %%mm7, %%mm2 \n\t"\
"punpckhbw %%mm7, %%mm3 \n\t"\
"punpcklbw %%mm7, %%mm4 \n\t"\
"punpckhbw %%mm7, %%mm5 \n\t"\
"paddw %%mm4, %%mm2 \n\t"\
"paddw %%mm3, %%mm5 \n\t"\
"psubw %%mm2, %%mm0 \n\t"\
"psubw %%mm5, %%mm1 \n\t"\
"movq %6, %%mm5 \n\t"\
"paddw %%mm5, %%mm0 \n\t"\
"paddw %%mm5, %%mm1 \n\t"\
"psraw $3, %%mm0 \n\t"\
"psraw $3, %%mm1 \n\t"\
"packuswb %%mm1, %%mm0 \n\t"\
OP(%%mm0, (%1),%%mm5, q) \
"add %3, %0 \n\t"\
"add %4, %1 \n\t"\
"decl %2 \n\t"\
" jnz 1b \n\t"\
: "+a"(src), "+c"(dst), "+m"(h)\
: "d"((x86_reg)srcStride), "S"((x86_reg)dstStride), "m"(ff_pw_5), "m"(ff_pw_4)\
: "memory"\
);\
}\
\
static inline void OPNAME ## cavs_qpel8or16_v1_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride, int h){\
QPEL_CAVSVNUM(QPEL_CAVSV1,OP,ff_pw_64,ff_pw_96,ff_pw_42) \
}\
\
static inline void OPNAME ## cavs_qpel8or16_v2_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride, int h){\
QPEL_CAVSVNUM(QPEL_CAVSV2,OP,ff_pw_4,ff_pw_5,ff_pw_5) \
}\
\
static inline void OPNAME ## cavs_qpel8or16_v3_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride, int h){\
QPEL_CAVSVNUM(QPEL_CAVSV3,OP,ff_pw_64,ff_pw_96,ff_pw_42) \
}\
\
static void OPNAME ## cavs_qpel8_v1_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
OPNAME ## cavs_qpel8or16_v1_ ## MMX(dst , src , dstStride, srcStride, 8);\
}\
static void OPNAME ## cavs_qpel16_v1_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
OPNAME ## cavs_qpel8or16_v1_ ## MMX(dst , src , dstStride, srcStride, 16);\
OPNAME ## cavs_qpel8or16_v1_ ## MMX(dst+8, src+8, dstStride, srcStride, 16);\
}\
\
static void OPNAME ## cavs_qpel8_v2_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
OPNAME ## cavs_qpel8or16_v2_ ## MMX(dst , src , dstStride, srcStride, 8);\
}\
static void OPNAME ## cavs_qpel16_v2_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
OPNAME ## cavs_qpel8or16_v2_ ## MMX(dst , src , dstStride, srcStride, 16);\
OPNAME ## cavs_qpel8or16_v2_ ## MMX(dst+8, src+8, dstStride, srcStride, 16);\
}\
\
static void OPNAME ## cavs_qpel8_v3_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
OPNAME ## cavs_qpel8or16_v3_ ## MMX(dst , src , dstStride, srcStride, 8);\
}\
static void OPNAME ## cavs_qpel16_v3_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
OPNAME ## cavs_qpel8or16_v3_ ## MMX(dst , src , dstStride, srcStride, 16);\
OPNAME ## cavs_qpel8or16_v3_ ## MMX(dst+8, src+8, dstStride, srcStride, 16);\
}\
\
static void OPNAME ## cavs_qpel16_h_ ## MMX(uint8_t *dst, uint8_t *src, int dstStride, int srcStride){\
OPNAME ## cavs_qpel8_h_ ## MMX(dst , src , dstStride, srcStride);\
OPNAME ## cavs_qpel8_h_ ## MMX(dst+8, src+8, dstStride, srcStride);\
src += 8*srcStride;\
dst += 8*dstStride;\
OPNAME ## cavs_qpel8_h_ ## MMX(dst , src , dstStride, srcStride);\
OPNAME ## cavs_qpel8_h_ ## MMX(dst+8, src+8, dstStride, srcStride);\
}\
#define CAVS_MC(OPNAME, SIZE, MMX) \
static void ff_ ## OPNAME ## cavs_qpel ## SIZE ## _mc20_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
OPNAME ## cavs_qpel ## SIZE ## _h_ ## MMX(dst, src, stride, stride);\
}\
\
static void ff_ ## OPNAME ## cavs_qpel ## SIZE ## _mc01_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
OPNAME ## cavs_qpel ## SIZE ## _v1_ ## MMX(dst, src, stride, stride);\
}\
\
static void ff_ ## OPNAME ## cavs_qpel ## SIZE ## _mc02_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
OPNAME ## cavs_qpel ## SIZE ## _v2_ ## MMX(dst, src, stride, stride);\
}\
\
static void ff_ ## OPNAME ## cavs_qpel ## SIZE ## _mc03_ ## MMX(uint8_t *dst, uint8_t *src, int stride){\
OPNAME ## cavs_qpel ## SIZE ## _v3_ ## MMX(dst, src, stride, stride);\
}\
#define PUT_OP(a,b,temp, size) "mov" #size " " #a ", " #b " \n\t"
#define AVG_3DNOW_OP(a,b,temp, size) \
"mov" #size " " #b ", " #temp " \n\t"\
"pavgusb " #temp ", " #a " \n\t"\
"mov" #size " " #a ", " #b " \n\t"
#define AVG_MMX2_OP(a,b,temp, size) \
"mov" #size " " #b ", " #temp " \n\t"\
"pavgb " #temp ", " #a " \n\t"\
"mov" #size " " #a ", " #b " \n\t"
QPEL_CAVS(put_, PUT_OP, 3dnow)
QPEL_CAVS(avg_, AVG_3DNOW_OP, 3dnow)
QPEL_CAVS(put_, PUT_OP, mmx2)
QPEL_CAVS(avg_, AVG_MMX2_OP, mmx2)
CAVS_MC(put_, 8, 3dnow)
CAVS_MC(put_, 16,3dnow)
CAVS_MC(avg_, 8, 3dnow)
CAVS_MC(avg_, 16,3dnow)
CAVS_MC(put_, 8, mmx2)
CAVS_MC(put_, 16,mmx2)
CAVS_MC(avg_, 8, mmx2)
CAVS_MC(avg_, 16,mmx2)
static void ff_cavsdsp_init_mmx2(CAVSDSPContext* c, AVCodecContext *avctx) {
#define dspfunc(PFX, IDX, NUM) \
c->PFX ## _pixels_tab[IDX][ 0] = ff_ ## PFX ## NUM ## _mc00_mmx2; \
c->PFX ## _pixels_tab[IDX][ 2] = ff_ ## PFX ## NUM ## _mc20_mmx2; \
c->PFX ## _pixels_tab[IDX][ 4] = ff_ ## PFX ## NUM ## _mc01_mmx2; \
c->PFX ## _pixels_tab[IDX][ 8] = ff_ ## PFX ## NUM ## _mc02_mmx2; \
c->PFX ## _pixels_tab[IDX][12] = ff_ ## PFX ## NUM ## _mc03_mmx2; \
dspfunc(put_cavs_qpel, 0, 16);
dspfunc(put_cavs_qpel, 1, 8);
dspfunc(avg_cavs_qpel, 0, 16);
dspfunc(avg_cavs_qpel, 1, 8);
#undef dspfunc
c->cavs_idct8_add = cavs_idct8_add_mmx;
}
static void ff_cavsdsp_init_3dnow(CAVSDSPContext* c, AVCodecContext *avctx) {
#define dspfunc(PFX, IDX, NUM) \
c->PFX ## _pixels_tab[IDX][ 0] = ff_ ## PFX ## NUM ## _mc00_mmx2; \
c->PFX ## _pixels_tab[IDX][ 2] = ff_ ## PFX ## NUM ## _mc20_3dnow; \
c->PFX ## _pixels_tab[IDX][ 4] = ff_ ## PFX ## NUM ## _mc01_3dnow; \
c->PFX ## _pixels_tab[IDX][ 8] = ff_ ## PFX ## NUM ## _mc02_3dnow; \
c->PFX ## _pixels_tab[IDX][12] = ff_ ## PFX ## NUM ## _mc03_3dnow; \
dspfunc(put_cavs_qpel, 0, 16);
dspfunc(put_cavs_qpel, 1, 8);
dspfunc(avg_cavs_qpel, 0, 16);
dspfunc(avg_cavs_qpel, 1, 8);
#undef dspfunc
c->cavs_idct8_add = cavs_idct8_add_mmx;
}
void ff_cavsdsp_init_mmx(CAVSDSPContext *c, AVCodecContext *avctx)
{
int mm_flags = av_get_cpu_flags();
if (mm_flags & AV_CPU_FLAG_MMX2) ff_cavsdsp_init_mmx2 (c, avctx);
if (mm_flags & AV_CPU_FLAG_3DNOW) ff_cavsdsp_init_3dnow(c, avctx);
}
|
930022.c | /******************** (C) COPYRIGHT 2012 **************************************
* File Name : sensor_threshold.c
* Hackeroos : deh
* Date First Issued : 11/15/2012
* Board : STM32F103VxT6_pod_mm
* Description : Routines for determining photocell thresholds
*******************************************************************************/
/*
The purpose is to build a histogram of the ADC values while the hapless op spins
the shaft. From this we hope to divine the optimal threshold register settings
which will someday be saved for humanity in persistent storage.
Note: The EOC (End Of Conversion) flag gets reset when 'adcsensor_pod.c' gets an
adc watchdog interrupt as that routine reads the data register which automatically
resets the flag. Since losing a a few out of many doesn't matter we just live
with it.
******** Usage ******************
#define ADCHISTO_MAX 4000
#define NUMBERBINS 200
#define NUMBERDATAPTS 2000000
unsigned int bin[NUMBERBINS];
struct ADCHISTO strH = { NUBMERBINS, ADCHISTO_MAX, NUMBERDATAPTS, &bin[0] };
...
main()
...
... adc gets setup and is running, etc.
...
adc_histogram(&strH,(volatile u32 *)ADC1 );
*/
#include "sensor_threshold.h"
#include "libopenstm32/adc.h"
#include "libmiscstm32/printf.h"
#include "libusartstm32/usartallproto.h"
/*******************************************************************************
* void adc_histogram(struct ADCHISTO *pH, volatile u32 * pADC);
* @brief : Build histogram from ADC values
* @param : pH--pointer to struct with a bunch of things
* @param : ADC--ADC1, or ADC2
* @return : nothing to speak of
*******************************************************************************/
void adc_histogram(struct ADCHISTO *pH, u32 pADC)
{
unsigned int x = 0; // Count data points
int dr; // Data register retrieved
int i; // Index into array
int w = pH->nMax / pH->nBins; // Width of a bin
//printf("%d %d %u 0x%08x %d 0x%08x 0x%08x\n\r",pH->nBins,pH->nMax,pH->uiDp,(unsigned int)pH->p,w,(unsigned int)pADC,(unsigned int)ADC1);USART1_txint_send();
while ( x++ < pH->uiDp )
{
while ((ADC_SR(pADC) & ADC_SR_EOC) == 0); // Loop until End Of Conversion
dr = ADC_DR(pADC); // Data (which resets EOC flag)
i = (dr / w); // Data / Number adc counts per bin
if (i >= pH->nBins) i = (pH->nBins -1); // Stay within array boundary
*(pH->p + i) += 1; // Add a tick to this bin
}
return;
}
/*******************************************************************************
* void adc_histogram_print(struct ADCHISTO *pH);
* @brief : Printout the array
* @param : pH--pointer to struct with a bunch of things
* @return : nothing to speak of
*******************************************************************************/
void adc_histogram_print(struct ADCHISTO *pH)
{
int w = pH->nMax / pH->nBins; // Width of a bin
int i;
int val = 0;
for (i = 0; i < pH->nBins; i++)
{
printf("%4u%6u%10u\n\r",i,val,*(pH->p+i) ); USART1_txint_send();
val += w;
}
return;
}
|
623780.c | /*******************************************************************************
*
* Module Name: nsobject - Utilities for objects attached to namespace
* table entries
*
******************************************************************************/
/*
* Copyright (C) 2000 - 2016, Intel Corp.
* 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
* substantially 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.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* 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 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.
*/
#include <contrib/dev/acpica/include/acpi.h>
#include <contrib/dev/acpica/include/accommon.h>
#include <contrib/dev/acpica/include/acnamesp.h>
#define _COMPONENT ACPI_NAMESPACE
ACPI_MODULE_NAME ("nsobject")
/*******************************************************************************
*
* FUNCTION: AcpiNsAttachObject
*
* PARAMETERS: Node - Parent Node
* Object - Object to be attached
* Type - Type of object, or ACPI_TYPE_ANY if not
* known
*
* RETURN: Status
*
* DESCRIPTION: Record the given object as the value associated with the
* name whose ACPI_HANDLE is passed. If Object is NULL
* and Type is ACPI_TYPE_ANY, set the name as having no value.
* Note: Future may require that the Node->Flags field be passed
* as a parameter.
*
* MUTEX: Assumes namespace is locked
*
******************************************************************************/
ACPI_STATUS
AcpiNsAttachObject (
ACPI_NAMESPACE_NODE *Node,
ACPI_OPERAND_OBJECT *Object,
ACPI_OBJECT_TYPE Type)
{
ACPI_OPERAND_OBJECT *ObjDesc;
ACPI_OPERAND_OBJECT *LastObjDesc;
ACPI_OBJECT_TYPE ObjectType = ACPI_TYPE_ANY;
ACPI_FUNCTION_TRACE (NsAttachObject);
/*
* Parameter validation
*/
if (!Node)
{
/* Invalid handle */
ACPI_ERROR ((AE_INFO, "Null NamedObj handle"));
return_ACPI_STATUS (AE_BAD_PARAMETER);
}
if (!Object && (ACPI_TYPE_ANY != Type))
{
/* Null object */
ACPI_ERROR ((AE_INFO,
"Null object, but type not ACPI_TYPE_ANY"));
return_ACPI_STATUS (AE_BAD_PARAMETER);
}
if (ACPI_GET_DESCRIPTOR_TYPE (Node) != ACPI_DESC_TYPE_NAMED)
{
/* Not a name handle */
ACPI_ERROR ((AE_INFO, "Invalid handle %p [%s]",
Node, AcpiUtGetDescriptorName (Node)));
return_ACPI_STATUS (AE_BAD_PARAMETER);
}
/* Check if this object is already attached */
if (Node->Object == Object)
{
ACPI_DEBUG_PRINT ((ACPI_DB_EXEC,
"Obj %p already installed in NameObj %p\n",
Object, Node));
return_ACPI_STATUS (AE_OK);
}
/* If null object, we will just install it */
if (!Object)
{
ObjDesc = NULL;
ObjectType = ACPI_TYPE_ANY;
}
/*
* If the source object is a namespace Node with an attached object,
* we will use that (attached) object
*/
else if ((ACPI_GET_DESCRIPTOR_TYPE (Object) == ACPI_DESC_TYPE_NAMED) &&
((ACPI_NAMESPACE_NODE *) Object)->Object)
{
/*
* Value passed is a name handle and that name has a
* non-null value. Use that name's value and type.
*/
ObjDesc = ((ACPI_NAMESPACE_NODE *) Object)->Object;
ObjectType = ((ACPI_NAMESPACE_NODE *) Object)->Type;
}
/*
* Otherwise, we will use the parameter object, but we must type
* it first
*/
else
{
ObjDesc = (ACPI_OPERAND_OBJECT *) Object;
/* Use the given type */
ObjectType = Type;
}
ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, "Installing %p into Node %p [%4.4s]\n",
ObjDesc, Node, AcpiUtGetNodeName (Node)));
/* Detach an existing attached object if present */
if (Node->Object)
{
AcpiNsDetachObject (Node);
}
if (ObjDesc)
{
/*
* Must increment the new value's reference count
* (if it is an internal object)
*/
AcpiUtAddReference (ObjDesc);
/*
* Handle objects with multiple descriptors - walk
* to the end of the descriptor list
*/
LastObjDesc = ObjDesc;
while (LastObjDesc->Common.NextObject)
{
LastObjDesc = LastObjDesc->Common.NextObject;
}
/* Install the object at the front of the object list */
LastObjDesc->Common.NextObject = Node->Object;
}
Node->Type = (UINT8) ObjectType;
Node->Object = ObjDesc;
return_ACPI_STATUS (AE_OK);
}
/*******************************************************************************
*
* FUNCTION: AcpiNsDetachObject
*
* PARAMETERS: Node - A Namespace node whose object will be detached
*
* RETURN: None.
*
* DESCRIPTION: Detach/delete an object associated with a namespace node.
* if the object is an allocated object, it is freed.
* Otherwise, the field is simply cleared.
*
******************************************************************************/
void
AcpiNsDetachObject (
ACPI_NAMESPACE_NODE *Node)
{
ACPI_OPERAND_OBJECT *ObjDesc;
ACPI_FUNCTION_TRACE (NsDetachObject);
ObjDesc = Node->Object;
if (!ObjDesc ||
(ObjDesc->Common.Type == ACPI_TYPE_LOCAL_DATA))
{
return_VOID;
}
if (Node->Flags & ANOBJ_ALLOCATED_BUFFER)
{
/* Free the dynamic aml buffer */
if (ObjDesc->Common.Type == ACPI_TYPE_METHOD)
{
ACPI_FREE (ObjDesc->Method.AmlStart);
}
}
/* Clear the Node entry in all cases */
Node->Object = NULL;
if (ACPI_GET_DESCRIPTOR_TYPE (ObjDesc) == ACPI_DESC_TYPE_OPERAND)
{
/* Unlink object from front of possible object list */
Node->Object = ObjDesc->Common.NextObject;
/* Handle possible 2-descriptor object */
if (Node->Object &&
(Node->Object->Common.Type != ACPI_TYPE_LOCAL_DATA))
{
Node->Object = Node->Object->Common.NextObject;
}
/*
* Detach the object from any data objects (which are still held by
* the namespace node)
*/
if (ObjDesc->Common.NextObject &&
((ObjDesc->Common.NextObject)->Common.Type == ACPI_TYPE_LOCAL_DATA))
{
ObjDesc->Common.NextObject = NULL;
}
}
/* Reset the node type to untyped */
Node->Type = ACPI_TYPE_ANY;
ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, "Node %p [%4.4s] Object %p\n",
Node, AcpiUtGetNodeName (Node), ObjDesc));
/* Remove one reference on the object (and all subobjects) */
AcpiUtRemoveReference (ObjDesc);
return_VOID;
}
/*******************************************************************************
*
* FUNCTION: AcpiNsGetAttachedObject
*
* PARAMETERS: Node - Namespace node
*
* RETURN: Current value of the object field from the Node whose
* handle is passed
*
* DESCRIPTION: Obtain the object attached to a namespace node.
*
******************************************************************************/
ACPI_OPERAND_OBJECT *
AcpiNsGetAttachedObject (
ACPI_NAMESPACE_NODE *Node)
{
ACPI_FUNCTION_TRACE_PTR (NsGetAttachedObject, Node);
if (!Node)
{
ACPI_WARNING ((AE_INFO, "Null Node ptr"));
return_PTR (NULL);
}
if (!Node->Object ||
((ACPI_GET_DESCRIPTOR_TYPE (Node->Object) != ACPI_DESC_TYPE_OPERAND) &&
(ACPI_GET_DESCRIPTOR_TYPE (Node->Object) != ACPI_DESC_TYPE_NAMED)) ||
((Node->Object)->Common.Type == ACPI_TYPE_LOCAL_DATA))
{
return_PTR (NULL);
}
return_PTR (Node->Object);
}
/*******************************************************************************
*
* FUNCTION: AcpiNsGetSecondaryObject
*
* PARAMETERS: Node - Namespace node
*
* RETURN: Current value of the object field from the Node whose
* handle is passed.
*
* DESCRIPTION: Obtain a secondary object associated with a namespace node.
*
******************************************************************************/
ACPI_OPERAND_OBJECT *
AcpiNsGetSecondaryObject (
ACPI_OPERAND_OBJECT *ObjDesc)
{
ACPI_FUNCTION_TRACE_PTR (NsGetSecondaryObject, ObjDesc);
if ((!ObjDesc) ||
(ObjDesc->Common.Type== ACPI_TYPE_LOCAL_DATA) ||
(!ObjDesc->Common.NextObject) ||
((ObjDesc->Common.NextObject)->Common.Type == ACPI_TYPE_LOCAL_DATA))
{
return_PTR (NULL);
}
return_PTR (ObjDesc->Common.NextObject);
}
/*******************************************************************************
*
* FUNCTION: AcpiNsAttachData
*
* PARAMETERS: Node - Namespace node
* Handler - Handler to be associated with the data
* Data - Data to be attached
*
* RETURN: Status
*
* DESCRIPTION: Low-level attach data. Create and attach a Data object.
*
******************************************************************************/
ACPI_STATUS
AcpiNsAttachData (
ACPI_NAMESPACE_NODE *Node,
ACPI_OBJECT_HANDLER Handler,
void *Data)
{
ACPI_OPERAND_OBJECT *PrevObjDesc;
ACPI_OPERAND_OBJECT *ObjDesc;
ACPI_OPERAND_OBJECT *DataDesc;
/* We only allow one attachment per handler */
PrevObjDesc = NULL;
ObjDesc = Node->Object;
while (ObjDesc)
{
if ((ObjDesc->Common.Type == ACPI_TYPE_LOCAL_DATA) &&
(ObjDesc->Data.Handler == Handler))
{
return (AE_ALREADY_EXISTS);
}
PrevObjDesc = ObjDesc;
ObjDesc = ObjDesc->Common.NextObject;
}
/* Create an internal object for the data */
DataDesc = AcpiUtCreateInternalObject (ACPI_TYPE_LOCAL_DATA);
if (!DataDesc)
{
return (AE_NO_MEMORY);
}
DataDesc->Data.Handler = Handler;
DataDesc->Data.Pointer = Data;
/* Install the data object */
if (PrevObjDesc)
{
PrevObjDesc->Common.NextObject = DataDesc;
}
else
{
Node->Object = DataDesc;
}
return (AE_OK);
}
/*******************************************************************************
*
* FUNCTION: AcpiNsDetachData
*
* PARAMETERS: Node - Namespace node
* Handler - Handler associated with the data
*
* RETURN: Status
*
* DESCRIPTION: Low-level detach data. Delete the data node, but the caller
* is responsible for the actual data.
*
******************************************************************************/
ACPI_STATUS
AcpiNsDetachData (
ACPI_NAMESPACE_NODE *Node,
ACPI_OBJECT_HANDLER Handler)
{
ACPI_OPERAND_OBJECT *ObjDesc;
ACPI_OPERAND_OBJECT *PrevObjDesc;
PrevObjDesc = NULL;
ObjDesc = Node->Object;
while (ObjDesc)
{
if ((ObjDesc->Common.Type == ACPI_TYPE_LOCAL_DATA) &&
(ObjDesc->Data.Handler == Handler))
{
if (PrevObjDesc)
{
PrevObjDesc->Common.NextObject = ObjDesc->Common.NextObject;
}
else
{
Node->Object = ObjDesc->Common.NextObject;
}
AcpiUtRemoveReference (ObjDesc);
return (AE_OK);
}
PrevObjDesc = ObjDesc;
ObjDesc = ObjDesc->Common.NextObject;
}
return (AE_NOT_FOUND);
}
/*******************************************************************************
*
* FUNCTION: AcpiNsGetAttachedData
*
* PARAMETERS: Node - Namespace node
* Handler - Handler associated with the data
* Data - Where the data is returned
*
* RETURN: Status
*
* DESCRIPTION: Low level interface to obtain data previously associated with
* a namespace node.
*
******************************************************************************/
ACPI_STATUS
AcpiNsGetAttachedData (
ACPI_NAMESPACE_NODE *Node,
ACPI_OBJECT_HANDLER Handler,
void **Data)
{
ACPI_OPERAND_OBJECT *ObjDesc;
ObjDesc = Node->Object;
while (ObjDesc)
{
if ((ObjDesc->Common.Type == ACPI_TYPE_LOCAL_DATA) &&
(ObjDesc->Data.Handler == Handler))
{
*Data = ObjDesc->Data.Pointer;
return (AE_OK);
}
ObjDesc = ObjDesc->Common.NextObject;
}
return (AE_NOT_FOUND);
}
|
917764.c | /****************************************************************************
* libs/libc/unistd/lib_setreuid.c
*
* Copyright (C) 2019 Gregory Nutt. All rights reserved.
* Author: Michael Jung <[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 <unistd.h>
#include <errno.h>
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: setreuid
*
* Description:
* The setreuid() function sets the real user ID and/or the effective user
* ID of the calling task group to ruid and/or euid.
*
* Input Parameters:
* ruid - Real user identity to set. The special value (uid_t)-1
* indicates that the real user ID should not be changed.
* ruid - Effective user identity to set. The special value (uid_t)-1
* indicates that the effective user ID should not be changed.
*
* Returned Value:
* Zero if successful and -1 in case of failure, in which case errno is set
* appropriately.
*
****************************************************************************/
int setreuid(uid_t ruid, uid_t euid)
{
int ret = OK;
if (ruid != (uid_t)-1)
{
/* Set the real user ID. CAREFUL: This exploits non-standard behavior
* of setuid(): setuid() should set the real, effective, and saved
* user ID. Here we depend on it setting only the real user ID.
*/
ret = setuid(ruid);
}
if (ret >= 0 && euid != (uid_t)-1)
{
/* Set the effective user ID */
ret = seteuid(euid);
}
return ret;
}
|
444294.c | #ifdef _MINGW
#define __CRT__NO_INLINE
#define __declspec /* hacks */
#endif
#include <time.h>
#undef time
time_t time(time_t *tloc)
{
time_t res;
if(!tloc) *tloc=res;
return res;
}
|
145941.c | /*
* Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Sun Microsystems 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.
*/
/* Trace table. */
/*
* A trace is an optional thread serial number plus N frames.
*
* The thread serial number is added to the key only if the user asks for
* threads in traces, which will cause many more traces to be created.
* Without it all threads share the traces.
*
* This is a variable length Key, depending on the number of frames.
* The frames are FrameIndex values into the frame table.
*
* It is important that the thread serial number is used and not the
* TlsIndex, threads come and go, and TlsIndex values are re-used
* but the thread serial number is unique per thread.
*
* The cpu=times and cpu=samples dumps rely heavily on traces, the trace
* dump preceeds the cpu information and uses the trace information.
* Depending on the cpu= request, different sorts are applied to the
* traces that are dumped.
*
*/
#include "hprof.h"
typedef struct TraceKey {
SerialNumber thread_serial_num; /* Thread serial number */
short n_frames; /* Number of frames that follow. */
jvmtiPhase phase : 8; /* Makes some traces unique */
FrameIndex frames[1]; /* Variable length */
} TraceKey;
typedef struct TraceInfo {
SerialNumber serial_num; /* Trace serial number */
jint num_hits; /* Number of hits this trace has */
jlong total_cost; /* Total cost associated with trace */
jlong self_cost; /* Total cost without children cost */
jint status; /* Status of dump of trace */
} TraceInfo;
typedef struct IterateInfo {
TraceIndex* traces;
int count;
jlong grand_total_cost;
} IterateInfo;
/* Private internal functions. */
static TraceKey*
get_pkey(TraceIndex index)
{
void * pkey;
int key_len;
table_get_key(gdata->trace_table, index, &pkey, &key_len);
HPROF_ASSERT(pkey!=NULL);
HPROF_ASSERT(key_len>=(int)sizeof(TraceKey));
HPROF_ASSERT(((TraceKey*)pkey)->n_frames<=1?key_len==(int)sizeof(TraceKey) :
key_len==(int)sizeof(TraceKey)+
(int)sizeof(FrameIndex)*(((TraceKey*)pkey)->n_frames-1));
return (TraceKey*)pkey;
}
static TraceInfo *
get_info(TraceIndex index)
{
TraceInfo * info;
info = (TraceInfo*)table_get_info(gdata->trace_table, index);
return info;
}
static TraceIndex
find_or_create(SerialNumber thread_serial_num, jint n_frames,
FrameIndex *frames, jvmtiPhase phase, TraceKey *trace_key_buffer)
{
TraceInfo * info;
TraceKey * pkey;
int key_len;
TraceIndex index;
jboolean new_one;
static TraceKey empty_key;
HPROF_ASSERT(frames!=NULL);
HPROF_ASSERT(trace_key_buffer!=NULL);
key_len = (int)sizeof(TraceKey);
if ( n_frames > 1 ) {
key_len += (int)((n_frames-1)*(int)sizeof(FrameIndex));
}
pkey = trace_key_buffer;
*pkey = empty_key;
pkey->thread_serial_num = (gdata->thread_in_traces ? thread_serial_num : 0);
pkey->n_frames = (short)n_frames;
pkey->phase = phase;
if ( n_frames > 0 ) {
(void)memcpy(pkey->frames, frames, (n_frames*(int)sizeof(FrameIndex)));
}
new_one = JNI_FALSE;
index = table_find_or_create_entry(gdata->trace_table,
pkey, key_len, &new_one, NULL);
if ( new_one ) {
info = get_info(index);
info->serial_num = gdata->trace_serial_number_counter++;
}
return index;
}
static void
list_item(TableIndex index, void *key_ptr, int key_len, void *info_ptr, void *arg)
{
TraceInfo *info;
TraceKey *key;
int i;
HPROF_ASSERT(key_ptr!=NULL);
HPROF_ASSERT(key_len>0);
HPROF_ASSERT(info_ptr!=NULL);
key = (TraceKey*)key_ptr;
info = (TraceInfo *)info_ptr;
debug_message( "Trace 0x%08x: SN=%u, threadSN=%u, n_frames=%d, frames=(",
index,
info->serial_num,
key->thread_serial_num,
key->n_frames);
for ( i = 0 ; i < key->n_frames ; i++ ) {
debug_message( "0x%08x, ", key->frames[i]);
}
debug_message( "), traceSN=%u, num_hits=%d, self_cost=(%d,%d), "
"total_cost=(%d,%d), status=0x%08x\n",
info->serial_num,
info->num_hits,
jlong_high(info->self_cost),
jlong_low(info->self_cost),
jlong_high(info->total_cost),
jlong_low(info->total_cost),
info->status);
}
static void
clear_cost(TableIndex i, void *key_ptr, int key_len, void *info_ptr, void *arg)
{
TraceInfo *info;
HPROF_ASSERT(key_ptr!=NULL);
HPROF_ASSERT(key_len>0);
HPROF_ASSERT(info_ptr!=NULL);
info = (TraceInfo *)info_ptr;
info->num_hits = 0;
info->total_cost = 0;
info->self_cost = 0;
}
/* Get the names for a frame in order to dump it. */
static void
get_frame_details(JNIEnv *env, FrameIndex frame_index,
SerialNumber *frame_serial_num, char **pcsig, ClassIndex *pcnum,
char **pmname, char **pmsig, char **psname, jint *plineno)
{
jmethodID method;
jlocation location;
jint lineno;
HPROF_ASSERT(frame_index!=0);
*pmname = NULL;
*pmsig = NULL;
*pcsig = NULL;
if ( psname != NULL ) {
*psname = NULL;
}
if ( plineno != NULL ) {
*plineno = -1;
}
if ( pcnum != NULL ) {
*pcnum = 0;
}
frame_get_location(frame_index, frame_serial_num, &method, &location, &lineno);
if ( plineno != NULL ) {
*plineno = lineno;
}
WITH_LOCAL_REFS(env, 1) {
jclass klass;
getMethodClass(method, &klass);
getClassSignature(klass, pcsig, NULL);
if ( pcnum != NULL ) {
LoaderIndex loader_index;
jobject loader;
loader = getClassLoader(klass);
loader_index = loader_find_or_create(env, loader);
*pcnum = class_find_or_create(*pcsig, loader_index);
(void)class_new_classref(env, *pcnum, klass);
}
if ( psname != NULL ) {
getSourceFileName(klass, psname);
}
} END_WITH_LOCAL_REFS;
getMethodName(method, pmname, pmsig);
}
/* Write out a stack trace. */
static void
output_trace(TableIndex index, void *key_ptr, int key_len, void *info_ptr, void *arg)
{
TraceKey *key;
TraceInfo *info;
SerialNumber serial_num;
SerialNumber thread_serial_num;
jint n_frames;
JNIEnv *env;
int i;
char *phase_str;
struct FrameNames {
SerialNumber serial_num;
char * sname;
char * csig;
char * mname;
int lineno;
} *finfo;
info = (TraceInfo*)info_ptr;
if ( info->status != 0 ) {
return;
}
env = (JNIEnv*)arg;
key = (TraceKey*)key_ptr;
thread_serial_num = key->thread_serial_num;
serial_num = info->serial_num;
info->status = 1;
finfo = NULL;
n_frames = (jint)key->n_frames;
if ( n_frames > 0 ) {
finfo = (struct FrameNames *)HPROF_MALLOC(n_frames*(int)sizeof(struct FrameNames));
/* Write frames, but save information for trace later */
for (i = 0; i < n_frames; i++) {
FrameIndex frame_index;
char *msig;
ClassIndex cnum;
frame_index = key->frames[i];
get_frame_details(env, frame_index, &finfo[i].serial_num,
&finfo[i].csig, &cnum,
&finfo[i].mname, &msig, &finfo[i].sname, &finfo[i].lineno);
if (frame_get_status(frame_index) == 0) {
io_write_frame(frame_index, finfo[i].serial_num,
finfo[i].mname, msig,
finfo[i].sname, class_get_serial_number(cnum),
finfo[i].lineno);
frame_set_status(frame_index, 1);
}
jvmtiDeallocate(msig);
}
}
/* Find phase string */
if ( key->phase == JVMTI_PHASE_LIVE ) {
phase_str = NULL; /* Normal trace, no phase annotation */
} else {
phase_str = phaseString(key->phase);
}
io_write_trace_header(serial_num, thread_serial_num, n_frames, phase_str);
for (i = 0; i < n_frames; i++) {
io_write_trace_elem(serial_num, key->frames[i], finfo[i].serial_num,
finfo[i].csig,
finfo[i].mname, finfo[i].sname, finfo[i].lineno);
jvmtiDeallocate(finfo[i].csig);
jvmtiDeallocate(finfo[i].mname);
jvmtiDeallocate(finfo[i].sname);
}
io_write_trace_footer(serial_num, thread_serial_num, n_frames);
if ( finfo != NULL ) {
HPROF_FREE(finfo);
}
}
/* Output a specific list of traces. */
static void
output_list(JNIEnv *env, TraceIndex *list, jint count)
{
rawMonitorEnter(gdata->data_access_lock); {
int i;
for ( i = 0; i < count ; i++ ) {
TraceIndex index;
TraceInfo *info;
void * pkey;
int key_len;
index = list[i];
table_get_key(gdata->trace_table, index, &pkey, &key_len);
info = get_info(index);
output_trace(index, pkey, key_len, info, (void*)env);
}
} rawMonitorExit(gdata->data_access_lock);
}
static void
collect_iterator(TableIndex index, void *key_ptr, int key_len, void *info_ptr, void *arg)
{
TraceInfo *info;
IterateInfo *iterate;
HPROF_ASSERT(key_ptr!=NULL);
HPROF_ASSERT(key_len>0);
HPROF_ASSERT(arg!=NULL);
HPROF_ASSERT(info_ptr!=NULL);
iterate = (IterateInfo *)arg;
info = (TraceInfo *)info_ptr;
iterate->traces[iterate->count++] = index;
iterate->grand_total_cost += info->self_cost;
}
static int
qsort_compare_cost(const void *p_trace1, const void *p_trace2)
{
TraceIndex trace1;
TraceIndex trace2;
TraceInfo * info1;
TraceInfo * info2;
HPROF_ASSERT(p_trace1!=NULL);
HPROF_ASSERT(p_trace2!=NULL);
trace1 = *(TraceIndex *)p_trace1;
trace2 = *(TraceIndex *)p_trace2;
info1 = get_info(trace1);
info2 = get_info(trace2);
/*LINTED*/
return (int)(info2->self_cost - info1->self_cost);
}
static int
qsort_compare_num_hits(const void *p_trace1, const void *p_trace2)
{
TraceIndex trace1;
TraceIndex trace2;
TraceInfo * info1;
TraceInfo * info2;
HPROF_ASSERT(p_trace1!=NULL);
HPROF_ASSERT(p_trace2!=NULL);
trace1 = *(TraceIndex *)p_trace1;
trace2 = *(TraceIndex *)p_trace2;
info1 = get_info(trace1);
info2 = get_info(trace2);
return info2->num_hits - info1->num_hits;
}
/* External interfaces. */
void
trace_init(void)
{
gdata->trace_table = table_initialize("Trace",
256, 256, 511, (int)sizeof(TraceInfo));
}
void
trace_list(void)
{
debug_message(
"--------------------- Trace Table ------------------------\n");
table_walk_items(gdata->trace_table, &list_item, NULL);
debug_message(
"----------------------------------------------------------\n");
}
void
trace_cleanup(void)
{
table_cleanup(gdata->trace_table, NULL, NULL);
gdata->trace_table = NULL;
}
SerialNumber
trace_get_serial_number(TraceIndex index)
{
TraceInfo *info;
if ( index == 0 ) {
return 0;
}
info = get_info(index);
return info->serial_num;
}
void
trace_increment_cost(TraceIndex index, jint num_hits, jlong self_cost, jlong total_cost)
{
TraceInfo *info;
table_lock_enter(gdata->trace_table); {
info = get_info(index);
info->num_hits += num_hits;
info->self_cost += self_cost;
info->total_cost += total_cost;
} table_lock_exit(gdata->trace_table);
}
TraceIndex
trace_find_or_create(SerialNumber thread_serial_num, jint n_frames, FrameIndex *frames, jvmtiFrameInfo *jframes_buffer)
{
return find_or_create(thread_serial_num, n_frames, frames, getPhase(),
(TraceKey*)jframes_buffer);
}
/* We may need to ask for more frames than the user asked for */
static int
get_real_depth(int depth, jboolean skip_init)
{
int extra_frames;
extra_frames = 0;
/* This is only needed if we are doing BCI */
if ( gdata->bci && depth > 0 ) {
/* Account for Java and native Tracker methods */
extra_frames = 2;
if ( skip_init ) {
/* Also allow for ignoring the java.lang.Object.<init> method */
extra_frames += 1;
}
}
return depth + extra_frames;
}
/* Fill in FrameIndex array from jvmtiFrameInfo array, return n_frames */
static int
fill_frame_buffer(int depth, int real_depth,
int frame_count, jboolean skip_init,
jvmtiFrameInfo *jframes_buffer, FrameIndex *frames_buffer)
{
int n_frames;
jint topframe;
/* If real_depth is 0, just return 0 */
if ( real_depth == 0 ) {
return 0;
}
/* Assume top frame index is 0 for now */
topframe = 0;
/* Possible top frames belong to the hprof Tracker class, remove them */
if ( gdata->bci ) {
while ( ( ( frame_count - topframe ) > 0 ) &&
( topframe < (real_depth-depth) ) &&
( tracker_method(jframes_buffer[topframe].method) ||
( skip_init
&& jframes_buffer[topframe].method==gdata->object_init_method ) )
) {
topframe++;
}
}
/* Adjust count to match depth request */
if ( ( frame_count - topframe ) > depth ) {
frame_count = depth + topframe;
}
/* The actual frame count we will process */
n_frames = frame_count - topframe;
if ( n_frames > 0 ) {
int i;
for (i = 0; i < n_frames; i++) {
jmethodID method;
jlocation location;
method = jframes_buffer[i+topframe].method;
location = jframes_buffer[i+topframe].location;
frames_buffer[i] = frame_find_or_create(method, location);
}
}
return n_frames;
}
/* Get the trace for the supplied thread */
TraceIndex
trace_get_current(jthread thread, SerialNumber thread_serial_num,
int depth, jboolean skip_init,
FrameIndex *frames_buffer,
jvmtiFrameInfo *jframes_buffer)
{
TraceIndex index;
jint frame_count;
int real_depth;
int n_frames;
HPROF_ASSERT(thread!=NULL);
HPROF_ASSERT(frames_buffer!=NULL);
HPROF_ASSERT(jframes_buffer!=NULL);
/* We may need to ask for more frames than the user asked for */
real_depth = get_real_depth(depth, skip_init);
/* Get the stack trace for this one thread */
frame_count = 0;
if ( real_depth > 0 ) {
getStackTrace(thread, jframes_buffer, real_depth, &frame_count);
}
/* Create FrameIndex's */
n_frames = fill_frame_buffer(depth, real_depth, frame_count, skip_init,
jframes_buffer, frames_buffer);
/* Lookup or create new TraceIndex */
index = find_or_create(thread_serial_num, n_frames, frames_buffer,
getPhase(), (TraceKey*)jframes_buffer);
return index;
}
/* Get traces for all threads in list (traces[i]==0 if thread not running) */
void
trace_get_all_current(jint thread_count, jthread *threads,
SerialNumber *thread_serial_nums,
int depth, jboolean skip_init,
TraceIndex *traces, jboolean always_care)
{
jvmtiStackInfo *stack_info;
int nbytes;
int real_depth;
int i;
FrameIndex *frames_buffer;
TraceKey *trace_key_buffer;
jvmtiPhase phase;
HPROF_ASSERT(threads!=NULL);
HPROF_ASSERT(thread_serial_nums!=NULL);
HPROF_ASSERT(traces!=NULL);
HPROF_ASSERT(thread_count > 0);
/* Find out what the phase is for all these traces */
phase = getPhase();
/* We may need to ask for more frames than the user asked for */
real_depth = get_real_depth(depth, skip_init);
/* Get the stack traces for all the threads */
getThreadListStackTraces(thread_count, threads, real_depth, &stack_info);
/* Allocate a frames_buffer and trace key buffer */
nbytes = (int)sizeof(FrameIndex)*real_depth;
frames_buffer = (FrameIndex*)HPROF_MALLOC(nbytes);
nbytes += (int)sizeof(TraceKey);
trace_key_buffer = (TraceKey*)HPROF_MALLOC(nbytes);
/* Loop over the stack traces we have for these 'thread_count' threads */
for ( i = 0 ; i < thread_count ; i++ ) {
int n_frames;
/* Assume 0 at first (no trace) */
traces[i] = 0;
/* If thread has frames, is runnable, and isn't suspended, we care */
if ( always_care ||
( stack_info[i].frame_count > 0
&& (stack_info[i].state & JVMTI_THREAD_STATE_RUNNABLE)!=0
&& (stack_info[i].state & JVMTI_THREAD_STATE_SUSPENDED)==0
&& (stack_info[i].state & JVMTI_THREAD_STATE_INTERRUPTED)==0 )
) {
/* Create FrameIndex's */
n_frames = fill_frame_buffer(depth, real_depth,
stack_info[i].frame_count,
skip_init,
stack_info[i].frame_buffer,
frames_buffer);
/* Lookup or create new TraceIndex */
traces[i] = find_or_create(thread_serial_nums[i],
n_frames, frames_buffer, phase, trace_key_buffer);
}
}
/* Make sure we free the space */
HPROF_FREE(frames_buffer);
HPROF_FREE(trace_key_buffer);
jvmtiDeallocate(stack_info);
}
/* Increment the trace costs for all the threads (for cpu=samples) */
void
trace_increment_all_sample_costs(jint thread_count, jthread *threads,
SerialNumber *thread_serial_nums,
int depth, jboolean skip_init)
{
TraceIndex *traces;
int nbytes;
HPROF_ASSERT(threads!=NULL);
HPROF_ASSERT(thread_serial_nums!=NULL);
HPROF_ASSERT(thread_count > 0);
HPROF_ASSERT(depth >= 0);
if ( depth == 0 ) {
return;
}
/* Allocate a traces array */
nbytes = (int)sizeof(TraceIndex)*thread_count;
traces = (TraceIndex*)HPROF_MALLOC(nbytes);
/* Get all the current traces for these threads */
trace_get_all_current(thread_count, threads, thread_serial_nums,
depth, skip_init, traces, JNI_FALSE);
/* Increment the cpu=samples cost on these traces */
table_lock_enter(gdata->trace_table); {
int i;
for ( i = 0 ; i < thread_count ; i++ ) {
/* Each trace gets a hit and an increment of it's total cost */
if ( traces[i] != 0 ) {
TraceInfo *info;
info = get_info(traces[i]);
info->num_hits += 1;
info->self_cost += (jlong)1;
info->total_cost += (jlong)1;
}
}
} table_lock_exit(gdata->trace_table);
/* Free up the memory allocated */
HPROF_FREE(traces);
}
void
trace_output_unmarked(JNIEnv *env)
{
rawMonitorEnter(gdata->data_access_lock); {
table_walk_items(gdata->trace_table, &output_trace, (void*)env);
} rawMonitorExit(gdata->data_access_lock);
}
/* output info on the cost associated with traces */
void
trace_output_cost(JNIEnv *env, double cutoff)
{
IterateInfo iterate;
int i, trace_table_size, n_items;
double accum;
int n_entries;
rawMonitorEnter(gdata->data_access_lock); {
n_entries = table_element_count(gdata->trace_table);
iterate.traces = HPROF_MALLOC(n_entries*(int)sizeof(TraceIndex)+1);
iterate.count = 0;
iterate.grand_total_cost = 0;
table_walk_items(gdata->trace_table, &collect_iterator, &iterate);
trace_table_size = iterate.count;
/* sort all the traces according to the cost */
qsort(iterate.traces, trace_table_size, sizeof(TraceIndex),
&qsort_compare_cost);
n_items = 0;
for (i = 0; i < trace_table_size; i++) {
TraceInfo *info;
TraceIndex trace_index;
double percent;
trace_index = iterate.traces[i];
info = get_info(trace_index);
/* As soon as a trace with zero hits is seen, we need no others */
if (info->num_hits == 0 ) {
break;
}
percent = (double)info->self_cost / (double)iterate.grand_total_cost;
if (percent < cutoff) {
break;
}
n_items++;
}
/* Now write all trace we might refer to. */
output_list(env, iterate.traces, n_items);
io_write_cpu_samples_header(iterate.grand_total_cost, n_items);
accum = 0;
for (i = 0; i < n_items; i++) {
SerialNumber frame_serial_num;
TraceInfo *info;
TraceKey *key;
TraceIndex trace_index;
double percent;
char *csig;
char *mname;
char *msig;
trace_index = iterate.traces[i];
info = get_info(trace_index);
key = get_pkey(trace_index);
percent = ((double)info->self_cost / (double)iterate.grand_total_cost) * 100.0;
accum += percent;
csig = NULL;
mname = NULL;
msig = NULL;
if (key->n_frames > 0) {
get_frame_details(env, key->frames[0], &frame_serial_num,
&csig, NULL, &mname, &msig, NULL, NULL);
}
io_write_cpu_samples_elem(i+1, percent, accum, info->num_hits,
(jint)info->self_cost, info->serial_num,
key->n_frames, csig, mname);
jvmtiDeallocate(csig);
jvmtiDeallocate(mname);
jvmtiDeallocate(msig);
}
io_write_cpu_samples_footer();
HPROF_FREE(iterate.traces);
} rawMonitorExit(gdata->data_access_lock);
}
/* output the trace cost in old prof format */
void
trace_output_cost_in_prof_format(JNIEnv *env)
{
IterateInfo iterate;
int i, trace_table_size;
int n_entries;
rawMonitorEnter(gdata->data_access_lock); {
n_entries = table_element_count(gdata->trace_table);
iterate.traces = HPROF_MALLOC(n_entries*(int)sizeof(TraceIndex)+1);
iterate.count = 0;
iterate.grand_total_cost = 0;
table_walk_items(gdata->trace_table, &collect_iterator, &iterate);
trace_table_size = iterate.count;
/* sort all the traces according to the number of hits */
qsort(iterate.traces, trace_table_size, sizeof(TraceIndex),
&qsort_compare_num_hits);
io_write_oldprof_header();
for (i = 0; i < trace_table_size; i++) {
SerialNumber frame_serial_num;
TraceInfo *info;
TraceKey *key;
TraceIndex trace_index;
int num_frames;
int num_hits;
char *csig_callee;
char *mname_callee;
char *msig_callee;
char *csig_caller;
char *mname_caller;
char *msig_caller;
trace_index = iterate.traces[i];
key = get_pkey(trace_index);
info = get_info(trace_index);
num_hits = info->num_hits;
if (num_hits == 0) {
break;
}
csig_callee = NULL;
mname_callee = NULL;
msig_callee = NULL;
csig_caller = NULL;
mname_caller = NULL;
msig_caller = NULL;
num_frames = (int)key->n_frames;
if (num_frames >= 1) {
get_frame_details(env, key->frames[0], &frame_serial_num,
&csig_callee, NULL,
&mname_callee, &msig_callee, NULL, NULL);
}
if (num_frames > 1) {
get_frame_details(env, key->frames[1], &frame_serial_num,
&csig_caller, NULL,
&mname_caller, &msig_caller, NULL, NULL);
}
io_write_oldprof_elem(info->num_hits, num_frames,
csig_callee, mname_callee, msig_callee,
csig_caller, mname_caller, msig_caller,
(int)info->total_cost);
jvmtiDeallocate(csig_callee);
jvmtiDeallocate(mname_callee);
jvmtiDeallocate(msig_callee);
jvmtiDeallocate(csig_caller);
jvmtiDeallocate(mname_caller);
jvmtiDeallocate(msig_caller);
}
io_write_oldprof_footer();
HPROF_FREE(iterate.traces);
} rawMonitorExit(gdata->data_access_lock);
}
void
trace_clear_cost(void)
{
table_walk_items(gdata->trace_table, &clear_cost, NULL);
}
|
734531.c | #include "xc.h"
#include "stdint.h"
int main(void) {
TRISE = 0x1FFF; //Set RE13 through RE15 as outputs, the rest of the port as inputs
while (1)
{
if(PORTEbits.RE7) //Check if RE7 (S1) is pressed
LATEbits.LATE14=1; //if it is, turn on green LED
else
LATEbits.LATE14=0; //If it is not, turn off green LED
}
}
|
713277.c | int func1(int a);
int func1(double a){
}
int func2(double a);
int func2(int a){
} |
827293.c | #include "serialize_sparse_matrix.h"
#ifdef _WIN32
#include "hiredis-win32/hiredis.h"
#else
#include "hiredis/hiredis.h"
#endif
#include <stdlib.h>
int save_sparse_matrix (sparse_matrix_t* matrix, redisContext *c)
{
redisReply *reply;
size_t i;
reply = redisCommand (c, "SET %s %d", "column_nb", matrix->column_nb);
freeReplyObject (reply);
reply = redisCommand (c, "SET %s %d", "row_nb", matrix->row_nb);
freeReplyObject (reply);
reply = redisCommand (c, "SET %s %d", "nonzero_entries_nb", matrix->nonzero_entries_nb);
freeReplyObject (reply);
reply = redisCommand (c, "SET %s %d", "row_capacity", matrix->row_capacity);
freeReplyObject (reply);
reply = redisCommand (c, "SET %s %d", "nonzero_entries_capacity", matrix->nonzero_entries_capacity);
freeReplyObject (reply);
reply = redisCommand (c, "DEL values");
freeReplyObject (reply);
reply = redisCommand (c, "DEL column_index");
freeReplyObject (reply);
for ( i = 0 ; i < matrix->nonzero_entries_nb; i++)
{
reply = redisCommand (c, "RPUSH values %f", matrix->values[i]);
freeReplyObject (reply);
reply = redisCommand (c, "RPUSH column_index %d", matrix->column_index[i]);
freeReplyObject (reply);
}
reply = redisCommand (c, "DEL row_index");
freeReplyObject (reply);
for (i = 0; i < matrix->row_nb + 1 ; i++)
{
reply = redisCommand (c, "RPUSH row_index %d", matrix->row_index[i]);
freeReplyObject (reply);
}
return 0;
}
sparse_matrix_t* load_sparse_matrix (redisContext *c)
{
redisReply *reply;
size_t i;
sparse_matrix_t* matrix;
matrix = malloc (sizeof (sparse_matrix_t) );
reply = redisCommand (c, "GET column_nb");
matrix->column_nb = atoi (reply->str);
freeReplyObject (reply);
reply = redisCommand (c, "GET row_nb");
matrix->row_nb = atoi (reply->str);
freeReplyObject (reply);
reply = redisCommand (c, "GET nonzero_entries_nb");
matrix->nonzero_entries_nb = atoi (reply->str);
freeReplyObject (reply);
reply = redisCommand (c, "GET row_capacity");
matrix->row_capacity = atoi (reply->str);
freeReplyObject (reply);
reply = redisCommand (c, "GET nonzero_entries_capacity");
matrix->nonzero_entries_capacity = atoi (reply->str);
freeReplyObject (reply);
reply = redisCommand (c, "GET nonzero_entries_capacity");
matrix->nonzero_entries_capacity = atoi (reply->str);
freeReplyObject (reply);
matrix->values = malloc (matrix->nonzero_entries_capacity * sizeof (float) );
matrix->column_index = malloc (matrix->nonzero_entries_capacity * sizeof (size_t) );
reply = redisCommand (c, "LRANGE values 0 -1");
if (reply->type == REDIS_REPLY_ARRAY && reply->elements == matrix->nonzero_entries_nb)
{
for (i = 0; i < reply->elements; i++)
{
matrix->values[i] = atof (reply->element[i]->str);
}
}
reply = redisCommand (c, "LRANGE column_index 0 -1");
if (reply->type == REDIS_REPLY_ARRAY && reply->elements == matrix->nonzero_entries_nb)
{
for (i = 0; i < reply->elements; i++)
{
matrix->column_index[i] = atoi (reply->element[i]->str);
}
}
freeReplyObject (reply);
matrix->row_index = malloc (matrix->row_capacity * sizeof (size_t) );
reply = redisCommand (c, "LRANGE row_index 0 -1");
if (reply->type == REDIS_REPLY_ARRAY && reply->elements == matrix->row_nb + 1)
{
for (i = 0; i < matrix->row_nb + 1; i++)
{
matrix->row_index[i] = atoi (reply->element[i]->str);
}
}
return matrix;
}
int save_coo_matrix (coo_matrix_t* coo, redisContext *c)
{
redisReply *reply;
size_t i;
reply = redisCommand (c, "SET %s %d", "current_size", coo->current_size);
freeReplyObject (reply);
reply = redisCommand (c, "SET %s %d", "size", coo->size);
freeReplyObject (reply);
reply = redisCommand (c, "DEL coo_entries_column_j");
reply = redisCommand (c, "DEL coo_entries_row_i");
reply = redisCommand (c, "DEL coo_entries_value");
freeReplyObject (reply);
for (i = 0; i < coo->size; i++)
{
reply = redisCommand (c, "RPUSH coo_entries_column_j %d", coo->entries[i].column_j);
reply = redisCommand (c, "RPUSH coo_entries_row_i %d", coo->entries[i].row_i);
reply = redisCommand (c, "RPUSH coo_entries_value %f", coo->entries[i].value);
freeReplyObject (reply);
}
return 0;
}
coo_matrix_t* load_coo_matrix (redisContext *c)
{
redisReply *reply;
size_t i;
coo_matrix_t* coo;
coo = malloc (sizeof (coo_matrix_t) );
reply = redisCommand (c, "GET current_size");
coo->current_size = atoi (reply->str);
freeReplyObject (reply);
reply = redisCommand (c, "GET size");
coo->size = atoi (reply->str);
coo->entries = malloc (coo->size * sizeof (coo_entry_t) );
reply = redisCommand (c, "lrange coo_entries_column_j 0 -1");
if (reply->type == REDIS_REPLY_ARRAY && reply->elements == coo->size)
{
for (i = 0; i < reply->elements; i++)
{
coo->entries[i].column_j = atoi (reply->element[i]->str);
}
}
reply = redisCommand (c, "lrange coo_entries_row_i 0 -1");
if (reply->type == REDIS_REPLY_ARRAY && reply->elements == coo->size)
{
for (i = 0; i < reply->elements; i++)
{
coo->entries[i].row_i = atoi (reply->element[i]->str);
}
}
reply = redisCommand (c, "lrange coo_entries_value 0 -1");
if (reply->type == REDIS_REPLY_ARRAY && reply->elements == coo->size)
{
for (i = 0; i < reply->elements ; i++)
{
coo->entries[i].value = atof (reply->element[i]->str);
}
}
return coo;
}
|
24055.c |
#include "../../NAApp.h"
#if (NA_COMPILE_GUI == 1)
NA_API void na_DeallocUIImage(NAUIImage* uiImage);
NA_RUNTIME_TYPE(NAUIImage, na_DeallocUIImage, NA_TRUE);
// Will retain the babyImage.
NA_HIAPI void na_SetUIImageBabyImage(NAUIImage* uiImage, const NABabyImage* babyImage, NAUIImageResolution resolution, NAUIImageKind kind, NAUIImageSkin skin);
NA_DEF void naFillDefaultTextColorWithSkin(NABabyColor color, NAUIImageSkin skin){
uint8 skinColor[4];
switch(skin){
case NA_UIIMAGE_SKIN_LIGHT:
skinColor[0] = 16;
skinColor[1] = 16;
skinColor[2] = 16;
skinColor[3] = 255;
break;
case NA_UIIMAGE_SKIN_DARK:
skinColor[0] = 240;
skinColor[1] = 240;
skinColor[2] = 240;
skinColor[3] = 255;
break;
default:
#if NA_DEBUG
naError("Cannot provide color for plain skin");
#endif
break;
}
naFillBabyColorWithu8(color, skinColor, NA_COLOR_BUFFER_RGBA);
}
NA_DEF void naFillDefaultLinkColorWithSkin(NABabyColor color, NAUIImageSkin skin){
uint8 skinColor[4];
switch(skin){
case NA_UIIMAGE_SKIN_LIGHT:
skinColor[0] = 16;
skinColor[1] = 128;
skinColor[2] = 240;
skinColor[3] = 255;
break;
case NA_UIIMAGE_SKIN_DARK:
skinColor[0] = 64;
skinColor[1] = 196;
skinColor[2] = 240;
skinColor[3] = 255;
break;
default:
#if NA_DEBUG
naError("Cannot provide color for plain skin");
#endif
break;
}
naFillBabyColorWithu8(color, skinColor, NA_COLOR_BUFFER_RGBA);
}
NA_HIDEF NAInt na_GetUIImageSubImageIndex(NAUIImageResolution resolution, NAUIImageKind kind, NAUIImageSkin skin){
return ((NAInt)resolution * (NAInt)NA_UIIMAGE_KIND_COUNT + (NAInt)kind) * (NAInt)NA_UIIMAGE_SKIN_COUNT + (NAInt)skin;
}
NA_HDEF const NABabyImage* na_GetUIImageBabyImage(const NAUIImage* uiImage, NAUIImageResolution resolution, NAUIImageKind kind, NAUIImageSkin skin){
NAInt subIndex = na_GetUIImageSubImageIndex(resolution, kind, skin);
const NABabyImage* retimg = uiImage->babyImages[subIndex];
if(!retimg && skin != NA_UIIMAGE_SKIN_PLAIN){
NAInt plainIndex = na_GetUIImageSubImageIndex(resolution, kind, NA_UIIMAGE_SKIN_PLAIN);
const NABabyImage* plainimg = uiImage->babyImages[plainIndex];
if(plainimg){
NABabyColor skinColor;
NABabyImage* skinnedImage;
naFillDefaultTextColorWithSkin(skinColor, skin);
skinnedImage = naCreateBabyImageWithTint(plainimg, skinColor, uiImage->tintMode, 1.f);
// todo: not so beautiful const cast to NAUIImage*.
na_SetUIImageBabyImage((NAUIImage*)uiImage, skinnedImage, resolution, kind, skin);
naReleaseBabyImage(skinnedImage);
retimg = uiImage->babyImages[subIndex];
}
}
return retimg;
}
NA_HDEF void* na_GetUIImageNativeImage(const NAUIImage* uiImage, NAUIImageResolution resolution, NAUIImageKind kind, NAUIImageSkin skin){
NAInt subIndex;
// Let the following function do the hard work.
na_GetUIImageBabyImage(uiImage, resolution, kind, skin);
// Now, we are sure that, if ever possible, nativeImages will contain the desired image.
subIndex = na_GetUIImageSubImageIndex(resolution, kind, skin);
return uiImage->nativeImages[subIndex];
}
NA_HIDEF void na_SetUIImageBabyImage(NAUIImage* uiImage, const NABabyImage* babyImage, NAUIImageResolution resolution, NAUIImageKind kind, NAUIImageSkin skin){
NAInt subIndex = na_GetUIImageSubImageIndex(resolution, kind, skin);
uiImage->babyImages[subIndex] = naRetainBabyImage(babyImage);
uiImage->nativeImages[subIndex] = naAllocNativeImageWithBabyImage(babyImage);
}
NA_DEF NAUIImage* naNewUIImage(const NABabyImage* main, const NABabyImage* alt, NAUIImageResolution resolution, NABlendMode tintMode){
NAUIImage* uiImage;
NABabyImage* main1x;
#if NA_DEBUG
#if NA_OS == NA_OS_WINDOWS
if(sizeof(WORD) > 4)
naError("Bitamps require WORD alignment. But WORD is kind-a big on this system. Expect bad images.");
#endif
if(!main)
naError("There must be a main image");
if(alt && !naEqualSizei(naGetBabyImageSize(main), naGetBabyImageSize(alt)))
naError("Both images must have the same size.");
#endif
uiImage = naNew(NAUIImage);
uiImage->size1x = naGetBabyImageSize(main);
uiImage->tintMode = tintMode;
naZeron(uiImage->babyImages, NA_UIIMAGE_SUBIMAGES_COUNT * sizeof(NABabyImage*));
#if NA_OS == NA_OS_WINDOWS
naZeron(uiImage->nativeImages, NA_UIIMAGE_SUBIMAGES_COUNT * sizeof(HBITMAP));
#else
naZeron(uiImage->nativeImages, NA_UIIMAGE_SUBIMAGES_COUNT * sizeof(void*));
#endif
switch(resolution){
case NA_UIIMAGE_RESOLUTION_1x:
na_SetUIImageBabyImage(uiImage, main, NA_UIIMAGE_RESOLUTION_1x, NA_UIIMAGE_KIND_MAIN, NA_UIIMAGE_SKIN_PLAIN);
if(alt){
na_SetUIImageBabyImage(uiImage, alt, NA_UIIMAGE_RESOLUTION_1x, NA_UIIMAGE_KIND_ALT, NA_UIIMAGE_SKIN_PLAIN);
}
break;
case NA_UIIMAGE_RESOLUTION_2x:
#if NA_DEBUG
if(uiImage->size1x.width % 2 || uiImage->size1x.height % 2)
naError("Image size is not divisable by 2");
#endif
uiImage->size1x.width /= 2;
uiImage->size1x.height /= 2;
na_SetUIImageBabyImage(uiImage, main, NA_UIIMAGE_RESOLUTION_2x, NA_UIIMAGE_KIND_MAIN, NA_UIIMAGE_SKIN_PLAIN);
main1x = naCreateBabyImageWithHalfSize(main);
na_SetUIImageBabyImage(uiImage, main1x, NA_UIIMAGE_RESOLUTION_1x, NA_UIIMAGE_KIND_MAIN, NA_UIIMAGE_SKIN_PLAIN);
naReleaseBabyImage(main1x);
if(alt){
NABabyImage* alt1x;
na_SetUIImageBabyImage(uiImage, alt, NA_UIIMAGE_RESOLUTION_2x, NA_UIIMAGE_KIND_ALT, NA_UIIMAGE_SKIN_PLAIN);
alt1x = naCreateBabyImageWithHalfSize(alt);
na_SetUIImageBabyImage(uiImage, alt1x, NA_UIIMAGE_RESOLUTION_1x, NA_UIIMAGE_KIND_ALT, NA_UIIMAGE_SKIN_PLAIN);
naReleaseBabyImage(alt1x);
}
break;
default:
#if NA_DEBUG
naError("Unknown resolution");
#endif
break;
}
return uiImage;
}
NA_API void na_DeallocUIImage(NAUIImage* uiImage){
NAInt i;
for(i = 0; i < NA_UIIMAGE_SUBIMAGES_COUNT; i++){
if(uiImage->nativeImages[i]){naDeallocNativeImage(uiImage->nativeImages[i]);}
if(uiImage->babyImages[i]){naReleaseBabyImage(uiImage->babyImages[i]);}
}
}
#endif // (NA_COMPILE_GUI == 1)
// This is free and unencumbered software released into the public domain.
// Anyone is free to copy, modify, publish, use, compile, sell, or
// distribute this software, either in source code form or as a compiled
// binary, for any purpose, commercial or non-commercial, and by any
// means.
// In jurisdictions that recognize copyright laws, the author or authors
// of this software dedicate any and all copyright interest in the
// software to the public domain. We make this dedication for the benefit
// of the public at large and to the detriment of our heirs and
// successors. We intend this dedication to be an overt act of
// relinquishment in perpetuity of all present and future rights to this
// software under copyright law.
// 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 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.
// For more information, please refer to <http://unlicense.org/>
|
553025.c | /*
* FreeRTOS V202011.00
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* 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.
*
* http://www.FreeRTOS.org
* http://aws.amazon.com/freertos
*
* 1 tab == 4 spaces!
*/
/*
* Instead of the normal single demo application, the PIC18F demo is split
* into several smaller programs of which this is the first. This enables the
* demo's to be executed on the RAM limited 40 pin devices. The 64 and 80 pin
* devices require a more costly development platform and are not so readily
* available.
*
* The RTOSDemo1 project is configured for a PIC18F452 device. Main1.c starts 5
* tasks (including the idle task).
*
* The first task runs at the idle priority. It repeatedly performs a 32bit
* calculation and checks it's result against the expected value. This checks
* that the temporary storage utilised by the compiler to hold intermediate
* results does not get corrupted when the task gets switched in and out. See
* demo/common/minimal/integer.c for more information.
*
* The second and third tasks pass an incrementing value between each other on
* a message queue. See demo/common/minimal/PollQ.c for more information.
*
* Main1.c also creates a check task. This periodically checks that all the
* other tasks are still running and have not experienced any unexpected
* results. If all the other tasks are executing correctly an LED is flashed
* once every mainCHECK_PERIOD milliseconds. If any of the tasks have not
* executed, or report and error, the frequency of the LED flash will increase
* to mainERROR_FLASH_RATE.
*
* On entry to main an 'X' is transmitted. Monitoring the serial port using a
* dumb terminal allows for verification that the device is not continuously
* being reset (no more than one 'X' should be transmitted).
*
* http://www.FreeRTOS.org contains important information on the use of the
* PIC18F port.
*/
/*
Changes from V2.0.0
+ Delay periods are now specified using variables and constants of
TickType_t rather than unsigned long.
*/
/* Scheduler include files. */
#include "FreeRTOS.h"
#include "task.h"
/* Demo app include files. */
#include "PollQ.h"
#include "integer.h"
#include "partest.h"
#include "serial.h"
/* The period between executions of the check task before and after an error
has been discovered. If an error has been discovered the check task runs
more frequently - increasing the LED flash rate. */
#define mainNO_ERROR_CHECK_PERIOD ( ( TickType_t ) 1000 / portTICK_PERIOD_MS )
#define mainERROR_CHECK_PERIOD ( ( TickType_t ) 100 / portTICK_PERIOD_MS )
/* Priority definitions for some of the tasks. Other tasks just use the idle
priority. */
#define mainQUEUE_POLL_PRIORITY ( tskIDLE_PRIORITY + 2 )
#define mainCHECK_TASK_PRIORITY ( tskIDLE_PRIORITY + 3 )
/* The LED that is flashed by the check task. */
#define mainCHECK_TASK_LED ( 0 )
/* Constants required for the communications. Only one character is ever
transmitted. */
#define mainCOMMS_QUEUE_LENGTH ( 5 )
#define mainNO_BLOCK ( ( TickType_t ) 0 )
#define mainBAUD_RATE ( ( unsigned long ) 9600 )
/*
* The task function for the "Check" task.
*/
static void vErrorChecks( void *pvParameters );
/*
* Checks the unique counts of other tasks to ensure they are still operational.
* Returns pdTRUE if an error is detected, otherwise pdFALSE.
*/
static portBASE_TYPE prvCheckOtherTasksAreStillRunning( void );
/*-----------------------------------------------------------*/
/* Creates the tasks, then starts the scheduler. */
void main( void )
{
/* Initialise the required hardware. */
vParTestInitialise();
vPortInitialiseBlocks();
/* Send a character so we have some visible feedback of a reset. */
xSerialPortInitMinimal( mainBAUD_RATE, mainCOMMS_QUEUE_LENGTH );
xSerialPutChar( NULL, 'X', mainNO_BLOCK );
/* Start the standard demo tasks found in the demo\common directory. */
vStartIntegerMathTasks( tskIDLE_PRIORITY );
vStartPolledQueueTasks( mainQUEUE_POLL_PRIORITY );
/* Start the check task defined in this file. */
xTaskCreate( vErrorChecks, "Check", configMINIMAL_STACK_SIZE, NULL, mainCHECK_TASK_PRIORITY, NULL );
/* Start the scheduler. Will never return here. */
vTaskStartScheduler();
}
/*-----------------------------------------------------------*/
static void vErrorChecks( void *pvParameters )
{
TickType_t xDelayTime = mainNO_ERROR_CHECK_PERIOD;
portBASE_TYPE xErrorOccurred;
/* Cycle for ever, delaying then checking all the other tasks are still
operating without error. */
for( ;; )
{
/* Wait until it is time to check the other tasks. */
vTaskDelay( xDelayTime );
/* Check all the other tasks are running, and running without ever
having an error. */
xErrorOccurred = prvCheckOtherTasksAreStillRunning();
/* If an error was detected increase the frequency of the LED flash. */
if( xErrorOccurred == pdTRUE )
{
xDelayTime = mainERROR_CHECK_PERIOD;
}
/* Flash the LED for visual feedback. */
vParTestToggleLED( mainCHECK_TASK_LED );
}
}
/*-----------------------------------------------------------*/
static portBASE_TYPE prvCheckOtherTasksAreStillRunning( void )
{
portBASE_TYPE xErrorHasOccurred = pdFALSE;
if( xAreIntegerMathsTaskStillRunning() != pdTRUE )
{
xErrorHasOccurred = pdTRUE;
}
if( xArePollingQueuesStillRunning() != pdTRUE )
{
xErrorHasOccurred = pdTRUE;
}
return xErrorHasOccurred;
}
/*-----------------------------------------------------------*/
|
574763.c | /*
compat: Some compatibility functions (basic memory and string stuff)
The mpg123 code is determined to keep it's legacy. A legacy of old, old UNIX.
So anything possibly somewhat advanced should be considered to be put here, with proper #ifdef;-)
copyright 2007-2016 by the mpg123 project - free software under the terms of the LGPL 2.1
see COPYING and AUTHORS files in distribution or http://mpg123.org
initially written by Thomas Orgis, Windows Unicode stuff by JonY.
*/
#include "compat.h"
#include "debug.h"
/* A safe realloc also for very old systems where realloc(NULL, size) returns NULL. */
void *safe_realloc(void *ptr, size_t size)
{
if(ptr == NULL) return malloc(size);
else return realloc(ptr, size);
}
#ifndef HAVE_STRERROR
const char *strerror(int errnum)
{
extern int sys_nerr;
extern char *sys_errlist[];
return (errnum < sys_nerr) ? sys_errlist[errnum] : "";
}
#endif
char* compat_strdup(const char *src)
{
char *dest = NULL;
if(src)
{
size_t len;
len = strlen(src)+1;
if((dest = malloc(len)))
memcpy(dest, src, len);
}
return dest;
}
|
115509.c | /* Test mpz_sizeinbase.
Copyright 2001, 2002 Free Software Foundation, Inc.
This file is part of the GNU MP Library.
The GNU MP 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.
The GNU MP 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 the GNU MP Library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA. */
#include <stdio.h>
#include <stdlib.h>
#include "mpir.h"
#include "gmp-impl.h"
#include "tests.h"
#if 0
/* Disabled due to the bogosity of trying to fake an _mp_d pointer to
below an object. Has been seen to fail on a hppa system and on ia64. */
/* Create a fake mpz consisting of just a single 1 bit, with totbits being
the total number of bits, inclusive of that 1 bit. */
void
mpz_fake_bits (mpz_ptr z, unsigned long totbits)
{
static mp_limb_t n;
unsigned long zero_bits, zero_limbs;
zero_bits = totbits - 1;
zero_limbs = zero_bits / GMP_NUMB_BITS;
zero_bits %= GMP_NUMB_BITS;
SIZ(z) = zero_limbs + 1;
PTR(z) = (&n) - (SIZ(z) - 1);
n = CNST_LIMB(1) << zero_bits;
ASSERT_ALWAYS (mpz_sizeinbase (z, 2) == totbits);
}
/* This was seen to fail on a GNU/Linux powerpc32 with gcc 2.95.2,
apparently due to a doubtful value of mp_bases[10].chars_per_bit_exactly
(0X1.34413509F79FDP-2 whereas 0X1.34413509F79FFP-2 is believed correct).
Presumably this is a glibc problem when gcc converts the decimal string
in mp_bases.c, or maybe it's only a function of the rounding mode during
compilation. */
void
check_sample (void)
{
unsigned long totbits = 198096465;
int base = 10;
size_t want = 59632979;
size_t got;
mpz_t z;
mpz_fake_bits (z, totbits);
got = mpz_sizeinbase (z, base);
if (got != want)
{
printf ("mpz_sizeinbase\n");
printf (" base %d\n", base);
printf (" totbits %lu\n", totbits);
printf (" got %u\n", got);
printf (" want %u\n", want);
abort ();
}
}
#endif
int
main (void)
{
tests_start ();
/* check_sample (); */
tests_end ();
exit (0);
}
|
889959.c | /* Copyright (C) 2011-2017 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Chris Metcalf <[email protected]>, 2011.
The GNU C 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.
The GNU C 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 the GNU C Library. If not, see
<http://www.gnu.org/licenses/>. */
#include <errno.h>
#include <stddef.h>
#include <unistd.h>
#include <fcntl.h>
/* Remove the directory PATH. */
int
__rmdir (const char *path)
{
return INLINE_SYSCALL (unlinkat, 3, AT_FDCWD, path, AT_REMOVEDIR);
}
weak_alias (__rmdir, rmdir)
|
594225.c | /*
* Copyright 2018 Google LLC
*
* 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
*
* https://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.
*/
#define _POSIX_C_SOURCE 200809L
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <setjmp.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "harness.h"
#include "../util.h"
struct test_env {
const char *current_testcase;
jmp_buf escape_env;
int tmpdir_fd;
const char *tmpdir_name;
int testdir_fd;
char *testdir_name;
};
bool test_main(test_env *env);
static void testdir_setup(test_env *env);
static int testdir_getdir(test_env *env, const char *path);
static void testdir_closedir(test_env *env, int dir_fd);
static bool testdir_rmtree(int parent_fd, int dir_fd, const char *dir_name);
void test_write_file(test_env *env, const char *path, const char *contents) {
if (*path == '/')
test_fail(env, "test_write_file path is absolute: %s", path);
const char *file = strrchr(path, '/');
file = file ? file + 1 : path;
testdir_setup(env);
int dir_fd = testdir_getdir(env, path);
int fd = openat(dir_fd, file, O_WRONLY | O_CREAT | O_TRUNC, 0600);
if (fd == -1)
test_fail(env, "in %s: %s: unable to open for writing: %s", path, file, strerror(errno));
testdir_closedir(env, dir_fd);
if (write_all(fd, contents, strlen(contents)) == -1)
test_fail(env, "in %s: %s: failed write: %s", path, file, strerror(errno));
close(fd);
}
void test_add_link(test_env *env, const char *path, const char *target) {
if (*path == '/')
test_fail(env, "test_write_file path is absolute: %s", path);
const char *file = strrchr(path, '/');
file = file ? file + 1 : path;
testdir_setup(env);
int dir_fd = testdir_getdir(env, path);
if (symlinkat(target, dir_fd, file) == -1)
test_fail(env, "in %s: %s: unable to create a symlink to %s: %s", path, file, target, strerror(errno));
testdir_closedir(env, dir_fd);
}
void test_fail(test_env *env, const char *err, ...) {
va_list ap;
printf("FAILED: ");
va_start(ap, err);
vprintf(err, ap);
va_end(ap);
printf("\n");
longjmp(env->escape_env, 1);
}
bool test_start(test_env *env, const char *name) {
printf("test: %s\n", name);
env->current_testcase = name;
env->testdir_fd = -1;
env->testdir_name = 0;
return true;
}
jmp_buf *test_escape(test_env *env) {
return &env->escape_env;
}
bool test_cleanup(test_env *env) {
int success = true;
if (env->testdir_name) {
success = success && testdir_rmtree(env->tmpdir_fd, env->testdir_fd, env->testdir_name);
free(env->testdir_name);
}
if (!success)
printf("FAILED: test cleanup failed\n");
env->current_testcase = 0;
return success;
}
int main(void) {
test_env env;
env.current_testcase = 0;
env.tmpdir_fd = -1;
bool success = test_main(&env);
if (env.tmpdir_fd != -1)
close(env.tmpdir_fd);
return success ? EXIT_SUCCESS : EXIT_FAILURE;
}
static void testdir_setup(test_env *env) {
char buf[64];
if (env->testdir_name)
return; // already done
if (env->tmpdir_fd == -1) {
env->tmpdir_name = getenv("TMPDIR");
if (!env->tmpdir_name)
env->tmpdir_name = "/tmp";
env->tmpdir_fd = open(env->tmpdir_name, O_RDONLY | O_DIRECTORY);
if (env->tmpdir_fd == -1)
test_fail(env, "failed to open temporary file directory: %s: %s", env->tmpdir_name, strerror(errno));
}
for (unsigned attempt = 0; attempt < 100; attempt++) {
unsigned base = 0;
for (const char *p = env->current_testcase; p && *p; p++)
base = (base << 5) + base + (unsigned char) *p;
snprintf(buf, sizeof buf, "nano_exporter_test_%x", base + attempt);
if (mkdirat(env->tmpdir_fd, buf, 0700) == 0) {
env->testdir_fd = openat(env->tmpdir_fd, buf, O_RDONLY | O_DIRECTORY);
if (env->testdir_fd == -1)
test_fail(env, "failed to open test work directory in %s: %s: %s", env->tmpdir_name, buf, strerror(errno));
env->testdir_name = must_strdup(buf);
if (fchdir(env->testdir_fd) == -1)
test_fail(env, "unable to change to test work directory in %s: %s: %s", env->tmpdir_name, buf, strerror(errno));
return;
}
}
test_fail(env, "failed to create test work directory in %s: %s: %s", env->tmpdir_name, buf, strerror(errno));
}
static int testdir_getdir(test_env *env, const char *orig_path) {
char buf[NAME_MAX + 1];
struct stat st;
int parent_fd = env->testdir_fd;
const char *path = orig_path;
char *slash;
while ((slash = strchr(path, '/'))) {
if (slash - path > (ptrdiff_t) sizeof buf - 1)
test_fail(env, "path name component too long: %s", path);
snprintf(buf, sizeof buf, "%.*s", (int)(slash - path), path);
if (fstatat(parent_fd, buf, &st, AT_SYMLINK_NOFOLLOW) == 0) {
if (!S_ISDIR(st.st_mode))
test_fail(env, "in %s: %s: exists and not a directory", orig_path, buf);
// already a directory, just try to open it
} else if (errno != ENOENT) {
test_fail(env, "in %s: %s: failed to stat: %s", orig_path, buf, strerror(errno));
} else {
// doesn't exist: make a new directory
if (mkdirat(parent_fd, buf, 0700) == -1)
test_fail(env, "in %s: %s: failed to mkdir: %s", orig_path, buf, strerror(errno));
}
int fd = openat(parent_fd, buf, O_RDONLY | O_DIRECTORY);
if (fd == -1)
test_fail(env, "in %s: %s: failed to open: %s", orig_path, buf, strerror(errno));
if (parent_fd != env->testdir_fd)
close(parent_fd);
parent_fd = fd;
path = slash + 1;
}
return parent_fd;
}
static void testdir_closedir(test_env *env, int dir_fd) {
if (dir_fd != env->testdir_fd)
close(dir_fd);
}
static bool testdir_rmtree(int parent_fd, int dir_fd, const char *dir_name) {
DIR *d = fdopendir(dir_fd);
if (!d) {
close(dir_fd);
return false;
}
bool success = true;
struct dirent *dent;
while ((dent = readdir(d))) {
if (strcmp(dent->d_name, ".") == 0 || strcmp(dent->d_name, "..") == 0)
continue;
struct stat st;
if (fstatat(dir_fd, dent->d_name, &st, AT_SYMLINK_NOFOLLOW) == -1) {
success = false;
continue;
}
if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
if (unlinkat(dir_fd, dent->d_name, 0) == -1)
success = false;
} else if (S_ISDIR(st.st_mode)) {
int fd = openat(dir_fd, dent->d_name, O_RDONLY | O_DIRECTORY);
if (fd == -1 || !testdir_rmtree(dir_fd, fd, dent->d_name))
success = false;
} else {
printf("unexpected item in bagging area: %s: not file, link or directory\n", dent->d_name);
success = false;
}
}
closedir(d);
if (success)
success = unlinkat(parent_fd, dir_name, AT_REMOVEDIR) == 0;
return success;
}
|
114681.c | #include "../include/driver_framebuffer.h"
const uint8_t Exo2_Bold_36pt7bBitmaps[] = {
0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFD, 0xE7, 0x80, 0x01, 0xEF, 0xFF, 0xFF, 0xF7, 0x80, 0xF1, 0xFE,
0x3F, 0xC7, 0xF8, 0xFF, 0x1F, 0xE3, 0xFC, 0x7F, 0x8F, 0xF1, 0xE0, 0x00,
0xF8, 0x3E, 0x00, 0x3E, 0x0F, 0x80, 0x0F, 0x03, 0xC0, 0x03, 0xC0, 0xF0,
0x01, 0xF0, 0x7C, 0x00, 0x7C, 0x1F, 0x01, 0xFF, 0xFF, 0xFC, 0xFF, 0xFF,
0xFF, 0x3F, 0xFF, 0xFF, 0xCF, 0xFF, 0xFF, 0xF0, 0x3E, 0x0F, 0x80, 0x0F,
0x83, 0xE0, 0x03, 0xE0, 0xF8, 0x00, 0xF0, 0x3C, 0x00, 0x3C, 0x0F, 0x01,
0xFF, 0xFF, 0xFC, 0x7F, 0xFF, 0xFF, 0x1F, 0xFF, 0xFF, 0xCF, 0xFF, 0xFF,
0xF0, 0x1E, 0x07, 0x80, 0x07, 0x81, 0xE0, 0x03, 0xE0, 0x78, 0x00, 0xF8,
0x3E, 0x00, 0x3E, 0x0F, 0x80, 0x0F, 0x03, 0xE0, 0x03, 0xC0, 0xF0, 0x00,
0xF0, 0x3C, 0x00, 0x00, 0x7C, 0x00, 0x07, 0xC0, 0x00, 0x7C, 0x00, 0x07,
0xC0, 0x00, 0x7C, 0x01, 0xFF, 0xFC, 0x7F, 0xFF, 0xE7, 0xFF, 0xFE, 0xFF,
0xFF, 0xCF, 0xFC, 0x00, 0xFC, 0x00, 0x0F, 0xC0, 0x00, 0xFC, 0x00, 0x0F,
0xC0, 0x00, 0xFF, 0x00, 0x0F, 0xFC, 0x00, 0x7F, 0xF8, 0x03, 0xFF, 0xF0,
0x1F, 0xFF, 0x80, 0x7F, 0xFC, 0x00, 0xFF, 0xE0, 0x01, 0xFE, 0x00, 0x07,
0xE0, 0x00, 0x7F, 0x00, 0x03, 0xF0, 0x00, 0x7F, 0x00, 0x07, 0xEF, 0xFF,
0xFE, 0xFF, 0xFF, 0xEF, 0xFF, 0xFC, 0xFF, 0xFF, 0x81, 0xFF, 0xE0, 0x03,
0xC0, 0x00, 0x3C, 0x00, 0x03, 0xC0, 0x00, 0x3C, 0x00, 0x01, 0x00, 0x00,
0x00, 0x07, 0xFC, 0x00, 0x78, 0x03, 0xFF, 0x80, 0x1C, 0x01, 0xFF, 0xE0,
0x0F, 0x00, 0x78, 0x7C, 0x07, 0x80, 0x1E, 0x1F, 0x01, 0xC0, 0x0F, 0x83,
0xC0, 0xF0, 0x03, 0xE0, 0xF0, 0x78, 0x00, 0xF8, 0x3C, 0x1E, 0x00, 0x3E,
0x0F, 0x0F, 0x00, 0x0F, 0x83, 0xC3, 0x80, 0x01, 0xE1, 0xF1, 0xE0, 0x00,
0x7C, 0x7C, 0xF0, 0xFC, 0x1F, 0xFE, 0x3C, 0xFF, 0xC3, 0xFF, 0x1E, 0x7F,
0xF8, 0x3F, 0x87, 0x1E, 0x1E, 0x00, 0x03, 0xCF, 0x87, 0xC0, 0x01, 0xE3,
0xE1, 0xF0, 0x00, 0x78, 0xF8, 0x7C, 0x00, 0x3C, 0x3E, 0x1F, 0x00, 0x0E,
0x0F, 0x87, 0xC0, 0x07, 0x83, 0xE1, 0xF0, 0x03, 0xC0, 0xF8, 0x7C, 0x00,
0xE0, 0x1E, 0x1F, 0x00, 0x78, 0x07, 0x87, 0x80, 0x3C, 0x01, 0xFF, 0xE0,
0x0F, 0x00, 0x3F, 0xF0, 0x07, 0x80, 0x03, 0xF8, 0x00, 0x10, 0x00, 0x01,
0xFF, 0xF8, 0x00, 0xFF, 0xFF, 0x00, 0x1F, 0xFF, 0xE0, 0x07, 0xFF, 0xF8,
0x00, 0xFE, 0x00, 0x00, 0x1F, 0x80, 0x00, 0x03, 0xF0, 0x03, 0xE0, 0x7E,
0x00, 0x7C, 0x0F, 0xC0, 0x0F, 0x81, 0xFC, 0x01, 0xF0, 0x1F, 0xFF, 0xFF,
0xE1, 0xFF, 0xFF, 0xFC, 0x1F, 0xFF, 0xFF, 0x8F, 0xFF, 0xFF, 0xF3, 0xFE,
0x03, 0xE0, 0x7E, 0x00, 0x7C, 0x1F, 0xC0, 0x0F, 0x83, 0xF8, 0x01, 0xF0,
0x7E, 0x00, 0x3E, 0x0F, 0xE0, 0x07, 0xC1, 0xFC, 0x00, 0xF8, 0x3F, 0x80,
0x7F, 0x07, 0xFC, 0x7F, 0xF8, 0x7F, 0xFF, 0xFF, 0xEF, 0xFF, 0xFF, 0xFC,
0xFF, 0xF8, 0xFF, 0x87, 0xFC, 0x0F, 0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0,
0x00, 0x10, 0x0E, 0x01, 0xF0, 0x7E, 0x0F, 0xC1, 0xF8, 0x1F, 0x03, 0xE0,
0x3E, 0x07, 0xE0, 0x7C, 0x0F, 0xC0, 0xFC, 0x0F, 0xC0, 0xFC, 0x0F, 0x80,
0xF8, 0x0F, 0x80, 0xF8, 0x0F, 0x80, 0xF8, 0x0F, 0x80, 0xF8, 0x0F, 0x80,
0xFC, 0x0F, 0xC0, 0xFC, 0x0F, 0xC0, 0x7C, 0x07, 0xE0, 0x3E, 0x03, 0xE0,
0x1F, 0x01, 0xF8, 0x0F, 0xC0, 0x7E, 0x01, 0xF0, 0x0E, 0x00, 0x10, 0x80,
0x0E, 0x00, 0xF8, 0x07, 0xC0, 0x3E, 0x01, 0xF0, 0x0F, 0x80, 0xFC, 0x07,
0xC0, 0x7C, 0x07, 0xE0, 0x3E, 0x03, 0xE0, 0x3F, 0x03, 0xF0, 0x3F, 0x03,
0xF0, 0x3F, 0x03, 0xF0, 0x3F, 0x03, 0xF0, 0x3F, 0x03, 0xF0, 0x3F, 0x03,
0xF0, 0x3F, 0x03, 0xE0, 0x3E, 0x07, 0xE0, 0x7C, 0x07, 0xC0, 0xFC, 0x0F,
0x81, 0xF0, 0x3E, 0x07, 0xC0, 0xF8, 0x0E, 0x00, 0x80, 0x00, 0x07, 0x80,
0x07, 0x00, 0x0E, 0x04, 0x18, 0x2F, 0x33, 0xDF, 0x6F, 0x9E, 0xDE, 0x83,
0xC0, 0x0F, 0xC0, 0x3F, 0xC0, 0x73, 0x81, 0xC3, 0x81, 0x86, 0x01, 0x08,
0x00, 0x01, 0xE0, 0x00, 0x78, 0x00, 0x1E, 0x00, 0x07, 0x80, 0x01, 0xE0,
0x00, 0x78, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0,
0x1E, 0x00, 0x07, 0x80, 0x01, 0xE0, 0x00, 0x78, 0x00, 0x1E, 0x00, 0x07,
0x80, 0x01, 0xE0, 0x00, 0xFB, 0xFF, 0xFF, 0xFF, 0xF3, 0x8E, 0x39, 0xE7,
0x04, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFB, 0xFF, 0xFF, 0xFF, 0xE0,
0x00, 0x01, 0xF0, 0x00, 0x1E, 0x00, 0x03, 0xE0, 0x00, 0x3C, 0x00, 0x07,
0xC0, 0x00, 0x78, 0x00, 0x0F, 0x80, 0x00, 0xF0, 0x00, 0x1F, 0x00, 0x01,
0xE0, 0x00, 0x3E, 0x00, 0x07, 0xC0, 0x00, 0x7C, 0x00, 0x0F, 0x80, 0x00,
0xF8, 0x00, 0x1F, 0x00, 0x01, 0xF0, 0x00, 0x3E, 0x00, 0x03, 0xE0, 0x00,
0x7C, 0x00, 0x07, 0x80, 0x00, 0xF8, 0x00, 0x0F, 0x00, 0x01, 0xF0, 0x00,
0x1E, 0x00, 0x03, 0xE0, 0x00, 0x3C, 0x00, 0x07, 0xC0, 0x00, 0x78, 0x00,
0x0F, 0x80, 0x00, 0x00, 0x20, 0x00, 0x3F, 0xF8, 0x07, 0xFF, 0xF0, 0x7F,
0xFF, 0xC3, 0xFF, 0xFE, 0x3F, 0x83, 0xF9, 0xF8, 0x0F, 0xCF, 0xC0, 0x7F,
0xFC, 0x01, 0xFF, 0xE0, 0x0F, 0xFF, 0x00, 0x7F, 0xF8, 0x03, 0xFF, 0xC0,
0x1F, 0xFE, 0x00, 0xFF, 0xF0, 0x07, 0xFF, 0x80, 0x3F, 0xFC, 0x01, 0xFF,
0xE0, 0x0F, 0xFF, 0x00, 0x7F, 0xF8, 0x03, 0xFF, 0xC0, 0x1F, 0xBF, 0x01,
0xFD, 0xF8, 0x0F, 0xCF, 0xE0, 0xFE, 0x3F, 0xFF, 0xE1, 0xFF, 0xFF, 0x07,
0xFF, 0xF0, 0x0F, 0xFE, 0x00, 0x02, 0x00, 0x00, 0x03, 0xF8, 0x7F, 0xDF,
0xFF, 0xFF, 0xF7, 0xFF, 0xBE, 0x7D, 0x07, 0xE0, 0x3F, 0x01, 0xF8, 0x0F,
0xC0, 0x7E, 0x03, 0xF0, 0x1F, 0x80, 0xFC, 0x07, 0xE0, 0x3F, 0x01, 0xF8,
0x0F, 0xC0, 0x7E, 0x03, 0xF0, 0x1F, 0x80, 0xFC, 0x07, 0xE0, 0x3F, 0x01,
0xF8, 0x0F, 0xC0, 0x7E, 0x00, 0x40, 0x1F, 0xFF, 0xE3, 0xFF, 0xFE, 0x7F,
0xFF, 0xEF, 0xFF, 0xFD, 0xFF, 0xFF, 0x80, 0x03, 0xF8, 0x00, 0x7F, 0x00,
0x0F, 0xC0, 0x01, 0xF8, 0x00, 0x7F, 0x00, 0x1F, 0xE0, 0x03, 0xF8, 0x00,
0xFE, 0x00, 0x3F, 0x80, 0x0F, 0xE0, 0x03, 0xFC, 0x00, 0xFF, 0x00, 0x3F,
0xC0, 0x0F, 0xF0, 0x03, 0xFC, 0x00, 0xFF, 0x00, 0x3F, 0xC0, 0x07, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x00,
0x80, 0x1F, 0xFF, 0xC3, 0xFF, 0xFE, 0x7F, 0xFF, 0xCF, 0xFF, 0xFC, 0x00,
0x3F, 0x80, 0x03, 0xF0, 0x00, 0x7E, 0x00, 0x0F, 0xC0, 0x01, 0xF8, 0x00,
0x7E, 0x00, 0x3F, 0xC1, 0xFF, 0xF0, 0x3F, 0xF8, 0x07, 0xFF, 0xC0, 0xFF,
0xFC, 0x00, 0x1F, 0xC0, 0x01, 0xF8, 0x00, 0x3F, 0x00, 0x03, 0xF0, 0x00,
0x7E, 0x00, 0x1F, 0xC0, 0x03, 0xF0, 0x0F, 0xFE, 0xFF, 0xFF, 0xDF, 0xFF,
0xF3, 0xFF, 0xFE, 0x7F, 0xFF, 0x00, 0x04, 0x00, 0x01, 0xF8, 0x00, 0x03,
0xF0, 0x00, 0x0F, 0xC0, 0x00, 0x1F, 0x80, 0x00, 0x7E, 0x00, 0x00, 0xFC,
0x3E, 0x01, 0xF0, 0x7C, 0x07, 0xE0, 0xF8, 0x0F, 0xC3, 0xF0, 0x3F, 0x07,
0xE0, 0x7E, 0x0F, 0xC1, 0xF8, 0x1F, 0x83, 0xF0, 0x3F, 0x07, 0xC0, 0x7E,
0x1F, 0x80, 0xFC, 0x3F, 0x01, 0xF8, 0xFE, 0x03, 0xF1, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF7, 0xFF, 0xFF, 0xE0, 0x00, 0x7E, 0x00,
0x00, 0xFC, 0x00, 0x01, 0xF8, 0x00, 0x03, 0xF0, 0x00, 0x07, 0xE0, 0x00,
0x0F, 0xC0, 0x7F, 0xFF, 0xDF, 0xFF, 0xE7, 0xFF, 0xF9, 0xFF, 0xFE, 0x7C,
0x00, 0x1F, 0x00, 0x07, 0xC0, 0x01, 0xF0, 0x00, 0x7C, 0x00, 0x1F, 0x80,
0x07, 0xFF, 0x81, 0xFF, 0xF8, 0x7F, 0xFF, 0x0F, 0xFF, 0xE0, 0x07, 0xFC,
0x00, 0x3F, 0x00, 0x0F, 0xC0, 0x03, 0xF0, 0x00, 0xFC, 0x00, 0x3F, 0x00,
0x0F, 0xC0, 0x07, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0x3F, 0xFF,
0x83, 0xFF, 0x80, 0x00, 0x10, 0x00, 0x7F, 0xFC, 0x1F, 0xFF, 0xC3, 0xFF,
0xFC, 0x3F, 0xFF, 0xC7, 0xF0, 0x00, 0x7E, 0x00, 0x07, 0xE0, 0x00, 0xFC,
0x00, 0x0F, 0xC0, 0x00, 0xFC, 0xFF, 0x8F, 0xFF, 0xFC, 0xFF, 0xFF, 0xEF,
0xFF, 0xFE, 0xFF, 0x07, 0xFF, 0xC0, 0x3F, 0xFC, 0x03, 0xFF, 0xC0, 0x3F,
0xFC, 0x03, 0xFF, 0xC0, 0x3F, 0xFC, 0x03, 0xF7, 0xC0, 0x3F, 0x7E, 0x07,
0xE7, 0xF8, 0xFE, 0x3F, 0xFF, 0xE3, 0xFF, 0xFC, 0x1F, 0xFF, 0x80, 0x3F,
0xE0, 0xFF, 0xFF, 0xDF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x00,
0x7E, 0x00, 0x1F, 0x80, 0x03, 0xF0, 0x00, 0x7E, 0x00, 0x1F, 0x80, 0x03,
0xF0, 0x00, 0xFE, 0x00, 0x1F, 0x80, 0x03, 0xF0, 0x00, 0xFC, 0x00, 0x1F,
0x80, 0x03, 0xF0, 0x00, 0xFC, 0x00, 0x1F, 0x80, 0x03, 0xF0, 0x00, 0xFC,
0x00, 0x1F, 0x80, 0x03, 0xF0, 0x00, 0xFC, 0x00, 0x1F, 0x80, 0x03, 0xF0,
0x00, 0xFC, 0x00, 0x1F, 0x80, 0x00, 0x00, 0x20, 0x00, 0x7F, 0xFC, 0x0F,
0xFF, 0xF8, 0x7F, 0xFF, 0xC7, 0xFF, 0xFF, 0x3F, 0x01, 0xF9, 0xF0, 0x0F,
0xCF, 0x80, 0x7E, 0x7C, 0x03, 0xF3, 0xE0, 0x1F, 0x9F, 0x80, 0xF8, 0x7F,
0xFF, 0xC1, 0xFF, 0xFC, 0x07, 0xFF, 0xC0, 0xFF, 0xFF, 0x8F, 0xFB, 0xFE,
0x7E, 0x03, 0xF7, 0xE0, 0x0F, 0xBF, 0x00, 0x7D, 0xF8, 0x03, 0xFF, 0xC0,
0x1F, 0xFE, 0x00, 0xFF, 0xF0, 0x0F, 0xFF, 0xFB, 0xFE, 0x7F, 0xFF, 0xF3,
0xFF, 0xFF, 0x07, 0xFF, 0xF0, 0x0F, 0xFE, 0x00, 0x00, 0x40, 0x01, 0xFF,
0xC0, 0xFF, 0xFE, 0x3F, 0xFF, 0xE7, 0xFF, 0xFD, 0xFC, 0x1F, 0xFF, 0x01,
0xFF, 0xE0, 0x3F, 0xF8, 0x07, 0xFF, 0x00, 0xFF, 0xE0, 0x1F, 0xFE, 0x01,
0xFF, 0xC0, 0x3F, 0xFC, 0x1F, 0xFF, 0xFF, 0xFB, 0xFF, 0xFF, 0x3F, 0xFF,
0xE3, 0xFE, 0xFC, 0x00, 0x1F, 0x80, 0x03, 0xF0, 0x00, 0x7E, 0x00, 0x1F,
0xC0, 0x03, 0xF0, 0x03, 0xFE, 0x7F, 0xFF, 0x8F, 0xFF, 0xF1, 0xFF, 0xFC,
0x1F, 0xFC, 0x00, 0xFB, 0xFF, 0xFF, 0xFF, 0xE0, 0x00, 0x00, 0x00, 0x00,
0xFB, 0xFF, 0xFF, 0xFD, 0xE0, 0xFB, 0xFF, 0xFF, 0xFF, 0xE0, 0x00, 0x00,
0x00, 0x00, 0x7F, 0xFF, 0xFF, 0xFD, 0xF3, 0xCF, 0x38, 0xE7, 0x84, 0x00,
0x01, 0x00, 0x07, 0x00, 0x3F, 0x00, 0xFF, 0x07, 0xFF, 0x1F, 0xFC, 0xFF,
0xE0, 0xFF, 0x80, 0xFC, 0x00, 0xFC, 0x00, 0xFF, 0x80, 0xFF, 0xF0, 0x1F,
0xFC, 0x07, 0xFF, 0x00, 0xFF, 0x00, 0x3F, 0x00, 0x07, 0x00, 0x01, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xF0, 0x80, 0x00, 0x78, 0x00, 0x3F, 0x00, 0x1F, 0xF0,
0x0F, 0xFF, 0x00, 0xFF, 0xE0, 0x1F, 0xFE, 0x01, 0xFF, 0x00, 0x1F, 0x80,
0x0F, 0xC0, 0x3F, 0xE0, 0xFF, 0xE3, 0xFF, 0xC7, 0xFF, 0x03, 0xFE, 0x01,
0xF8, 0x00, 0xF0, 0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x3F, 0xFF, 0x8F,
0xFF, 0xFB, 0xFF, 0xFF, 0xFF, 0xFF, 0xC0, 0x07, 0xF0, 0x00, 0xFC, 0x00,
0x3F, 0x00, 0x0F, 0xC0, 0x07, 0xF0, 0x01, 0xF8, 0x00, 0xFC, 0x00, 0x7F,
0x00, 0x3F, 0x80, 0x0F, 0xC0, 0x07, 0xE0, 0x01, 0xF0, 0x00, 0x7C, 0x00,
0x3E, 0x00, 0x0F, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F,
0x80, 0x03, 0xF0, 0x00, 0xFC, 0x00, 0x3F, 0x00, 0x0F, 0xC0, 0x03, 0xE0,
0x00, 0x0F, 0xFF, 0xFE, 0x07, 0xFF, 0xFF, 0xE3, 0xFF, 0xFF, 0xF9, 0xFF,
0xFF, 0xFF, 0x7F, 0x00, 0x0F, 0xDF, 0x80, 0x03, 0xF7, 0xC0, 0x00, 0xFF,
0xF0, 0x7F, 0xFF, 0xFC, 0x7F, 0xFF, 0xFF, 0x1F, 0xFF, 0xFF, 0xCF, 0xC0,
0xFF, 0xF3, 0xF0, 0x3F, 0xFC, 0xFC, 0x0F, 0xFF, 0x3F, 0x0F, 0xFF, 0xC7,
0xFF, 0xFF, 0xF1, 0xFF, 0xFF, 0xFC, 0x7F, 0xE7, 0xFF, 0x07, 0xF0, 0xF7,
0xC0, 0x00, 0x01, 0xF0, 0x00, 0x00, 0x7E, 0x00, 0x00, 0x1F, 0xFE, 0x00,
0x03, 0xFF, 0xFF, 0xFC, 0xFF, 0xFF, 0xFF, 0x0F, 0xFF, 0xFF, 0xC0, 0xFF,
0xFF, 0xF0, 0x00, 0x7F, 0x80, 0x00, 0x3F, 0xF0, 0x00, 0x0F, 0xFC, 0x00,
0x07, 0xFF, 0x80, 0x01, 0xF3, 0xE0, 0x00, 0x7C, 0xF8, 0x00, 0x3F, 0x3F,
0x00, 0x0F, 0xCF, 0xC0, 0x03, 0xE1, 0xF0, 0x00, 0xF8, 0x7C, 0x00, 0x7E,
0x1F, 0x80, 0x1F, 0x87, 0xE0, 0x07, 0xC0, 0xF8, 0x03, 0xF0, 0x3F, 0x00,
0xFC, 0x0F, 0xC0, 0x3F, 0x03, 0xF0, 0x1F, 0xFF, 0xFE, 0x07, 0xFF, 0xFF,
0x81, 0xFF, 0xFF, 0xE0, 0xFF, 0xFF, 0xFC, 0x3F, 0x00, 0x3F, 0x0F, 0xC0,
0x0F, 0xC7, 0xF0, 0x03, 0xF9, 0xF8, 0x00, 0x7E, 0x7E, 0x00, 0x1F, 0x9F,
0x80, 0x07, 0xEF, 0xC0, 0x00, 0xFC, 0xFF, 0xFE, 0x07, 0xFF, 0xFE, 0x3F,
0xFF, 0xF9, 0xFF, 0xFF, 0xCF, 0xC1, 0xFF, 0x7E, 0x01, 0xFB, 0xF0, 0x0F,
0xDF, 0x80, 0x7E, 0xFC, 0x03, 0xF7, 0xE0, 0x1F, 0xBF, 0x00, 0xF9, 0xF8,
0x3F, 0xCF, 0xFF, 0xFC, 0x7F, 0xFF, 0x83, 0xFF, 0xFF, 0x1F, 0xFF, 0xFC,
0xFC, 0x07, 0xF7, 0xE0, 0x1F, 0xBF, 0x00, 0x7F, 0xF8, 0x03, 0xFF, 0xC0,
0x1F, 0xFE, 0x00, 0xFF, 0xF0, 0x0F, 0xFF, 0x83, 0xFF, 0xFF, 0xFF, 0xF7,
0xFF, 0xFF, 0xBF, 0xFF, 0xF9, 0xFF, 0xFE, 0x00, 0x00, 0x10, 0x00, 0x7F,
0xFF, 0x0F, 0xFF, 0xF1, 0xFF, 0xFF, 0x3F, 0xFF, 0xE7, 0xFE, 0x00, 0x7F,
0x00, 0x07, 0xE0, 0x00, 0xFE, 0x00, 0x0F, 0xE0, 0x00, 0xFC, 0x00, 0x0F,
0xC0, 0x00, 0xFC, 0x00, 0x0F, 0xC0, 0x00, 0xFC, 0x00, 0x0F, 0xC0, 0x00,
0xFC, 0x00, 0x0F, 0xC0, 0x00, 0xFE, 0x00, 0x0F, 0xE0, 0x00, 0xFE, 0x00,
0x07, 0xF0, 0x00, 0x7F, 0x80, 0x07, 0xFF, 0xFF, 0x3F, 0xFF, 0xF1, 0xFF,
0xFF, 0x0F, 0xFF, 0xF0, 0x1F, 0xFC, 0xFF, 0xFE, 0x03, 0xFF, 0xFF, 0x0F,
0xFF, 0xFE, 0x3F, 0xFF, 0xFC, 0xFC, 0x0F, 0xFB, 0xF0, 0x0F, 0xEF, 0xC0,
0x1F, 0xFF, 0x00, 0x7F, 0xFC, 0x01, 0xFF, 0xF0, 0x03, 0xFF, 0xC0, 0x0F,
0xFF, 0x00, 0x3F, 0xFC, 0x00, 0xFF, 0xF0, 0x03, 0xFF, 0xC0, 0x0F, 0xFF,
0x00, 0x3F, 0xFC, 0x00, 0xFF, 0xF0, 0x03, 0xFF, 0xC0, 0x1F, 0xFF, 0x00,
0x7F, 0xFC, 0x01, 0xFF, 0xF0, 0x0F, 0xEF, 0xC0, 0xFF, 0xBF, 0xFF, 0xFC,
0xFF, 0xFF, 0xE3, 0xFF, 0xFF, 0x0F, 0xFF, 0xE0, 0x00, 0x1F, 0xFF, 0xDF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0x00, 0x3F, 0x00, 0x0F, 0xC0,
0x03, 0xF0, 0x00, 0xFC, 0x00, 0x3F, 0x00, 0x0F, 0xC0, 0x03, 0xFF, 0xFE,
0xFF, 0xFF, 0xBF, 0xFF, 0xEF, 0xFF, 0xFB, 0xF0, 0x00, 0xFC, 0x00, 0x3F,
0x00, 0x0F, 0xC0, 0x03, 0xF0, 0x00, 0xFC, 0x00, 0x3F, 0x00, 0x0F, 0xE0,
0x03, 0xFF, 0xFF, 0xFF, 0xFF, 0xDF, 0xFF, 0xF1, 0xFF, 0xFC, 0x1F, 0xFF,
0xDF, 0xFF, 0xF7, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x3F, 0x00, 0x0F,
0xC0, 0x03, 0xF0, 0x00, 0xFC, 0x00, 0x3F, 0x00, 0x0F, 0xC0, 0x03, 0xFF,
0xFC, 0xFF, 0xFF, 0x3F, 0xFF, 0xCF, 0xFF, 0xF3, 0xF0, 0x00, 0xFC, 0x00,
0x3F, 0x00, 0x0F, 0xC0, 0x03, 0xF0, 0x00, 0xFC, 0x00, 0x3F, 0x00, 0x0F,
0xC0, 0x03, 0xF0, 0x00, 0xFC, 0x00, 0x3F, 0x00, 0x0F, 0xC0, 0x00, 0x00,
0x08, 0x00, 0x0F, 0xFF, 0xE0, 0xFF, 0xFF, 0x87, 0xFF, 0xFC, 0x3F, 0xFF,
0xF1, 0xFF, 0xC0, 0x07, 0xF0, 0x00, 0x1F, 0x80, 0x00, 0xFE, 0x00, 0x03,
0xF8, 0x00, 0x0F, 0xE0, 0x00, 0x3F, 0x00, 0x00, 0xFC, 0x00, 0xFF, 0xF0,
0x03, 0xFF, 0xC0, 0x0F, 0xFF, 0x00, 0x3F, 0xFC, 0x00, 0xFF, 0xF0, 0x03,
0xFF, 0xC0, 0x0F, 0xFF, 0x80, 0x3F, 0xFE, 0x00, 0xFD, 0xF8, 0x03, 0xF7,
0xF0, 0x1F, 0xDF, 0xFF, 0xFF, 0x3F, 0xFF, 0xFC, 0xFF, 0xFD, 0xF1, 0xFF,
0xE7, 0xC3, 0xFE, 0x1F, 0x00, 0x80, 0x00, 0xFC, 0x00, 0xFF, 0xF0, 0x03,
0xFF, 0xC0, 0x0F, 0xFF, 0x00, 0x3F, 0xFC, 0x00, 0xFF, 0xF0, 0x03, 0xFF,
0xC0, 0x0F, 0xFF, 0x00, 0x3F, 0xFC, 0x00, 0xFF, 0xF0, 0x03, 0xFF, 0xC0,
0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0x00, 0x3F, 0xFC, 0x00, 0xFF, 0xF0, 0x03, 0xFF, 0xC0, 0x0F, 0xFF,
0x00, 0x3F, 0xFC, 0x00, 0xFF, 0xF0, 0x03, 0xFF, 0xC0, 0x0F, 0xFF, 0x00,
0x3F, 0xFC, 0x00, 0xFF, 0xF0, 0x03, 0xFF, 0xC0, 0x0F, 0xC0, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC0, 0x07, 0xE0, 0xFC, 0x1F, 0x83,
0xF0, 0x7E, 0x0F, 0xC1, 0xF8, 0x3F, 0x07, 0xE0, 0xFC, 0x1F, 0x83, 0xF0,
0x7E, 0x0F, 0xC1, 0xF8, 0x3F, 0x07, 0xE0, 0xFC, 0x1F, 0x83, 0xF0, 0x7E,
0x0F, 0xC7, 0xFF, 0xFF, 0xFF, 0xDF, 0xF3, 0xFC, 0x00, 0xFC, 0x01, 0xFF,
0xF0, 0x0F, 0xEF, 0xC0, 0x7F, 0x3F, 0x01, 0xF8, 0xFC, 0x0F, 0xE3, 0xF0,
0x7F, 0x0F, 0xC1, 0xF8, 0x3F, 0x0F, 0xE0, 0xFC, 0x7F, 0x03, 0xF1, 0xF8,
0x0F, 0xCF, 0xE0, 0x3F, 0xFF, 0x00, 0xFF, 0xF8, 0x03, 0xFF, 0xE0, 0x0F,
0xFF, 0xC0, 0x3F, 0x3F, 0x80, 0xFC, 0x7E, 0x03, 0xF1, 0xFC, 0x0F, 0xC3,
0xF8, 0x3F, 0x07, 0xE0, 0xFC, 0x1F, 0xC3, 0xF0, 0x3F, 0x8F, 0xC0, 0x7E,
0x3F, 0x01, 0xFC, 0xFC, 0x03, 0xF3, 0xF0, 0x0F, 0xEF, 0xC0, 0x1F, 0xC0,
0xFC, 0x00, 0x3F, 0x00, 0x0F, 0xC0, 0x03, 0xF0, 0x00, 0xFC, 0x00, 0x3F,
0x00, 0x0F, 0xC0, 0x03, 0xF0, 0x00, 0xFC, 0x00, 0x3F, 0x00, 0x0F, 0xC0,
0x03, 0xF0, 0x00, 0xFC, 0x00, 0x3F, 0x00, 0x0F, 0xC0, 0x03, 0xF0, 0x00,
0xFC, 0x00, 0x3F, 0x00, 0x0F, 0xC0, 0x03, 0xF0, 0x00, 0xFC, 0x00, 0x3F,
0x00, 0x0F, 0xF0, 0x03, 0xFF, 0xFF, 0x7F, 0xFF, 0xDF, 0xFF, 0xF1, 0xFF,
0xFC, 0x3F, 0xE0, 0x07, 0xFC, 0x7F, 0xF0, 0x07, 0xFE, 0x7F, 0xF0, 0x0F,
0xFE, 0x7F, 0xF0, 0x0F, 0xFE, 0x7E, 0xF8, 0x0F, 0xBE, 0x7E, 0xF8, 0x0F,
0xBE, 0x7E, 0xF8, 0x1F, 0x3E, 0x7E, 0xF8, 0x1F, 0x3E, 0x7E, 0x7C, 0x1F,
0x3E, 0x7E, 0x7C, 0x1F, 0x3E, 0x7E, 0x7C, 0x3E, 0x3E, 0x7E, 0x7C, 0x3E,
0x3F, 0x7E, 0x3E, 0x3E, 0x3F, 0x7E, 0x3E, 0x3E, 0x3F, 0x7E, 0x3E, 0x7C,
0x3F, 0x7C, 0x3E, 0x7C, 0x3F, 0x7C, 0x3E, 0x7C, 0x3F, 0x7C, 0x1F, 0x7C,
0x3F, 0x7C, 0x1F, 0x78, 0x3F, 0x7C, 0x1F, 0xF8, 0x3F, 0x7C, 0x1F, 0xF8,
0x3F, 0xFC, 0x0F, 0xF8, 0x3F, 0xFC, 0x0F, 0xF0, 0x3F, 0xFC, 0x00, 0x00,
0x3F, 0xFC, 0x00, 0x00, 0x3F, 0xFC, 0x00, 0x00, 0x3F, 0xFC, 0x00, 0x00,
0x3F, 0xFE, 0x00, 0x7F, 0xFE, 0x00, 0xFF, 0xFE, 0x01, 0xFF, 0xFC, 0x03,
0xFF, 0xFC, 0x07, 0xFF, 0xF8, 0x0F, 0xFF, 0xF8, 0x1F, 0xFD, 0xF0, 0x3F,
0xFB, 0xF0, 0x7F, 0xFB, 0xE0, 0xFF, 0xF7, 0xE1, 0xFF, 0xE7, 0xC3, 0xFF,
0xCF, 0xC7, 0xFF, 0x8F, 0x8F, 0xFF, 0x1F, 0x9F, 0xFE, 0x1F, 0x3F, 0xFC,
0x3F, 0x7F, 0xF8, 0x3E, 0xFF, 0xF0, 0x7F, 0xFF, 0xE0, 0x7D, 0xFF, 0xC0,
0xFF, 0xFF, 0x80, 0xFF, 0xFF, 0x01, 0xFF, 0xFE, 0x01, 0xFF, 0xFC, 0x03,
0xFF, 0xF8, 0x03, 0xFF, 0xF0, 0x03, 0xF0, 0x00, 0x10, 0x00, 0x07, 0xFF,
0xC0, 0x1F, 0xFF, 0xF0, 0x3F, 0xFF, 0xF8, 0x3F, 0xFF, 0xFC, 0x7F, 0x81,
0xFC, 0x7F, 0x00, 0xFE, 0x7E, 0x00, 0xFE, 0xFE, 0x00, 0x7E, 0xFE, 0x00,
0x7E, 0xFC, 0x00, 0x7E, 0xFC, 0x00, 0x7E, 0xFC, 0x00, 0x7E, 0xFC, 0x00,
0x7E, 0xFC, 0x00, 0x7F, 0xFC, 0x00, 0x7E, 0xFC, 0x00, 0x7E, 0xFC, 0x00,
0x7E, 0xFC, 0x00, 0x7E, 0xFE, 0x00, 0x7E, 0xFE, 0x00, 0x7E, 0x7E, 0x00,
0xFE, 0x7F, 0x00, 0xFE, 0x7F, 0x81, 0xFC, 0x3F, 0xFF, 0xFC, 0x3F, 0xFF,
0xF8, 0x1F, 0xFF, 0xF0, 0x07, 0xFF, 0xC0, 0x00, 0x10, 0x00, 0xFF, 0xFE,
0x0F, 0xFF, 0xFC, 0xFF, 0xFF, 0xEF, 0xFF, 0xFE, 0xFC, 0x1F, 0xFF, 0xC0,
0x7F, 0xFC, 0x03, 0xFF, 0xC0, 0x3F, 0xFC, 0x03, 0xFF, 0xC0, 0x3F, 0xFC,
0x03, 0xFF, 0xC0, 0x3F, 0xFC, 0x07, 0xFF, 0xC1, 0xFF, 0xFF, 0xFF, 0xEF,
0xFF, 0xFE, 0xFF, 0xFF, 0xCF, 0xFF, 0xF0, 0xFC, 0x00, 0x0F, 0xC0, 0x00,
0xFC, 0x00, 0x0F, 0xC0, 0x00, 0xFC, 0x00, 0x0F, 0xC0, 0x00, 0xFC, 0x00,
0x0F, 0xC0, 0x00, 0xFC, 0x00, 0x0F, 0xC0, 0x00, 0x00, 0x10, 0x00, 0x07,
0xFF, 0xC0, 0x1F, 0xFF, 0xF0, 0x3F, 0xFF, 0xF8, 0x3F, 0xFF, 0xFC, 0x7F,
0x81, 0xFC, 0x7F, 0x00, 0xFE, 0x7E, 0x00, 0xFE, 0xFE, 0x00, 0x7E, 0xFE,
0x00, 0x7E, 0xFC, 0x00, 0x7E, 0xFC, 0x00, 0x7E, 0xFC, 0x00, 0x7E, 0xFC,
0x00, 0x7E, 0xFC, 0x00, 0x7F, 0xFC, 0x00, 0x7E, 0xFC, 0x00, 0x7E, 0xFC,
0x00, 0x7E, 0xFC, 0x00, 0x7E, 0xFE, 0x00, 0x7E, 0xFE, 0x00, 0x7E, 0x7E,
0x00, 0xFE, 0x7F, 0x00, 0xFE, 0x7F, 0x81, 0xFC, 0x3F, 0xFF, 0xFC, 0x3F,
0xFF, 0xF8, 0x1F, 0xFF, 0xF0, 0x07, 0xFF, 0xC0, 0x00, 0x10, 0x00, 0x00,
0x40, 0x00, 0x00, 0x7C, 0x00, 0x00, 0x7F, 0xC0, 0x00, 0xFF, 0xFC, 0x00,
0x3F, 0xF8, 0x00, 0x0F, 0xF8, 0x00, 0x03, 0xF8, 0x00, 0x00, 0x70, 0xFF,
0xFE, 0x03, 0xFF, 0xFF, 0x0F, 0xFF, 0xFE, 0x3F, 0xFF, 0xFC, 0xFC, 0x1F,
0xF3, 0xF0, 0x0F, 0xCF, 0xC0, 0x3F, 0x3F, 0x00, 0xFC, 0xFC, 0x03, 0xFB,
0xF0, 0x0F, 0xCF, 0xC0, 0x3F, 0x3F, 0x00, 0xFC, 0xFC, 0x07, 0xF3, 0xFF,
0xFF, 0x8F, 0xFF, 0xFC, 0x3F, 0xFF, 0x80, 0xFF, 0xFF, 0x83, 0xF0, 0x7F,
0x0F, 0xC0, 0x7E, 0x3F, 0x01, 0xF8, 0xFC, 0x07, 0xE3, 0xF0, 0x0F, 0xCF,
0xC0, 0x3F, 0x3F, 0x00, 0xFC, 0xFC, 0x03, 0xFB, 0xF0, 0x07, 0xEF, 0xC0,
0x1F, 0xBF, 0x00, 0x7F, 0x00, 0x40, 0x01, 0xFF, 0xFE, 0x7F, 0xFF, 0xE7,
0xFF, 0xFE, 0xFF, 0xFF, 0xEF, 0xFC, 0x00, 0xFC, 0x00, 0x0F, 0xC0, 0x00,
0xFC, 0x00, 0x0F, 0xC0, 0x00, 0xFE, 0x00, 0x0F, 0xFC, 0x00, 0x7F, 0xF8,
0x07, 0xFF, 0xF0, 0x1F, 0xFF, 0x80, 0xFF, 0xFC, 0x01, 0xFF, 0xE0, 0x03,
0xFE, 0x00, 0x0F, 0xF0, 0x00, 0x7F, 0x00, 0x03, 0xF0, 0x00, 0x3F, 0x00,
0x07, 0xF0, 0x03, 0xFF, 0xFF, 0xFF, 0xEF, 0xFF, 0xFE, 0xFF, 0xFF, 0xCF,
0xFF, 0xF0, 0x00, 0x40, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0xFC, 0x00, 0x03, 0xF0, 0x00, 0x0F, 0xC0,
0x00, 0x3F, 0x00, 0x00, 0xFC, 0x00, 0x03, 0xF0, 0x00, 0x0F, 0xC0, 0x00,
0x3F, 0x00, 0x00, 0xFC, 0x00, 0x03, 0xF0, 0x00, 0x0F, 0xC0, 0x00, 0x3F,
0x00, 0x00, 0xFC, 0x00, 0x03, 0xF0, 0x00, 0x0F, 0xC0, 0x00, 0x3F, 0x00,
0x00, 0xFC, 0x00, 0x03, 0xF0, 0x00, 0x0F, 0xC0, 0x00, 0x3F, 0x00, 0x00,
0xFC, 0x00, 0x03, 0xF0, 0x00, 0x0F, 0xC0, 0x00, 0xFC, 0x00, 0xFF, 0xF0,
0x03, 0xFF, 0xC0, 0x0F, 0xFF, 0x00, 0x3F, 0xFC, 0x00, 0xFF, 0xF0, 0x03,
0xFF, 0xC0, 0x0F, 0xFF, 0x00, 0x3F, 0xFC, 0x00, 0xFF, 0xF0, 0x03, 0xFF,
0xC0, 0x0F, 0xFF, 0x00, 0x3F, 0xFC, 0x00, 0xFF, 0xF0, 0x03, 0xFF, 0xC0,
0x0F, 0xFF, 0x00, 0x3F, 0xFC, 0x00, 0xFF, 0xF0, 0x03, 0xFF, 0xC0, 0x1F,
0xFF, 0x00, 0x7E, 0xFC, 0x01, 0xFB, 0xF8, 0x07, 0xE7, 0xF0, 0x3F, 0x9F,
0xFF, 0xFC, 0x3F, 0xFF, 0xF0, 0x7F, 0xFF, 0x80, 0x7F, 0xF8, 0x00, 0x08,
0x00, 0xFE, 0x00, 0x1F, 0xBF, 0x00, 0x1F, 0xDF, 0x80, 0x0F, 0xCF, 0xC0,
0x07, 0xE3, 0xF0, 0x03, 0xF1, 0xF8, 0x03, 0xF8, 0xFC, 0x01, 0xF8, 0x3E,
0x00, 0xFC, 0x1F, 0x80, 0x7E, 0x0F, 0xC0, 0x7E, 0x07, 0xE0, 0x3F, 0x01,
0xF0, 0x1F, 0x80, 0xFC, 0x0F, 0x80, 0x7E, 0x0F, 0xC0, 0x1F, 0x07, 0xE0,
0x0F, 0xC3, 0xF0, 0x07, 0xE1, 0xF0, 0x03, 0xF1, 0xF8, 0x00, 0xF8, 0xFC,
0x00, 0x7E, 0x7C, 0x00, 0x3F, 0x3E, 0x00, 0x0F, 0xBF, 0x00, 0x07, 0xDF,
0x80, 0x03, 0xFF, 0x80, 0x00, 0xFF, 0xC0, 0x00, 0x7F, 0xE0, 0x00, 0x1F,
0xE0, 0x00, 0xFC, 0x03, 0xFE, 0x01, 0xFF, 0xF0, 0x1F, 0xF0, 0x1F, 0xFF,
0x80, 0xFF, 0x80, 0xFC, 0xFC, 0x0F, 0xFE, 0x07, 0xE7, 0xE0, 0x7D, 0xF0,
0x3F, 0x3F, 0x03, 0xEF, 0x81, 0xF9, 0xF8, 0x1F, 0x7C, 0x0F, 0xCF, 0xC0,
0xFB, 0xE0, 0x7E, 0x3F, 0x0F, 0x9F, 0x07, 0xE1, 0xF8, 0x7C, 0x7C, 0x3F,
0x0F, 0xC3, 0xE3, 0xE1, 0xF8, 0x7E, 0x1F, 0x1F, 0x0F, 0xC3, 0xF0, 0xF8,
0xF8, 0x7E, 0x1F, 0x87, 0xC7, 0xC3, 0xF0, 0x7C, 0x7C, 0x3E, 0x1F, 0x03,
0xF3, 0xE0, 0xF9, 0xF8, 0x1F, 0x9F, 0x07, 0xCF, 0xC0, 0xFC, 0xF8, 0x3E,
0x7E, 0x07, 0xE7, 0xC1, 0xF3, 0xF0, 0x3F, 0x3E, 0x0F, 0x9F, 0x80, 0xFB,
0xE0, 0x7C, 0xF8, 0x07, 0xDF, 0x01, 0xF7, 0xC0, 0x3E, 0xF8, 0x0F, 0xBE,
0x01, 0xFF, 0xC0, 0x7F, 0xF0, 0x0F, 0xFE, 0x03, 0xFF, 0x80, 0x7F, 0xF0,
0x1F, 0xF8, 0x01, 0xFF, 0x00, 0x7F, 0xC0, 0x7E, 0x00, 0x3F, 0x9F, 0x80,
0x1F, 0x8F, 0xC0, 0x1F, 0x83, 0xF0, 0x0F, 0xC1, 0xF8, 0x0F, 0xC0, 0x7E,
0x07, 0xE0, 0x3F, 0x07, 0xE0, 0x0F, 0xC3, 0xF0, 0x07, 0xE3, 0xF0, 0x01,
0xF9, 0xF8, 0x00, 0xFD, 0xF8, 0x00, 0x3F, 0xFC, 0x00, 0x1F, 0xFC, 0x00,
0x0F, 0xFE, 0x00, 0x07, 0xFF, 0x80, 0x07, 0xEF, 0xC0, 0x03, 0xF3, 0xF0,
0x03, 0xF1, 0xF8, 0x01, 0xF8, 0x7E, 0x01, 0xF8, 0x3F, 0x00, 0xFC, 0x0F,
0xC0, 0xFC, 0x07, 0xE0, 0x7E, 0x01, 0xF8, 0x7E, 0x00, 0xFC, 0x3F, 0x00,
0x3F, 0x3F, 0x00, 0x1F, 0xBF, 0x80, 0x07, 0xE0, 0xFE, 0x00, 0x3F, 0x7E,
0x00, 0x7F, 0x7F, 0x00, 0x7E, 0x3F, 0x00, 0xFE, 0x3F, 0x00, 0xFC, 0x1F,
0x81, 0xFC, 0x1F, 0x81, 0xF8, 0x0F, 0xC1, 0xF8, 0x0F, 0xC3, 0xF0, 0x07,
0xE3, 0xF0, 0x07, 0xE7, 0xE0, 0x03, 0xE7, 0xE0, 0x03, 0xF7, 0xC0, 0x01,
0xFF, 0xC0, 0x01, 0xFF, 0x80, 0x00, 0xFF, 0x80, 0x00, 0xFF, 0x00, 0x00,
0x7F, 0x00, 0x00, 0x7E, 0x00, 0x00, 0x7E, 0x00, 0x00, 0x7E, 0x00, 0x00,
0x7E, 0x00, 0x00, 0x7E, 0x00, 0x00, 0x7E, 0x00, 0x00, 0x7E, 0x00, 0x00,
0x7E, 0x00, 0x00, 0x7E, 0x00, 0xFF, 0xFF, 0xEF, 0xFF, 0xFE, 0xFF, 0xFF,
0xEF, 0xFF, 0xFE, 0x00, 0x07, 0xE0, 0x00, 0xFE, 0x00, 0x1F, 0xC0, 0x03,
0xF8, 0x00, 0x3F, 0x80, 0x07, 0xF0, 0x00, 0xFE, 0x00, 0x0F, 0xC0, 0x01,
0xFC, 0x00, 0x3F, 0x80, 0x07, 0xF0, 0x00, 0x7E, 0x00, 0x0F, 0xE0, 0x01,
0xFC, 0x00, 0x1F, 0x80, 0x03, 0xF8, 0x00, 0x7F, 0x00, 0x0F, 0xE0, 0x00,
0xFC, 0x00, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xF0, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC, 0x3F, 0x0F, 0xC3, 0xF0, 0xFC,
0x3F, 0x0F, 0xC3, 0xF0, 0xFC, 0x3F, 0x0F, 0xC3, 0xF0, 0xFC, 0x3F, 0x0F,
0xC3, 0xF0, 0xFC, 0x3F, 0x0F, 0xC3, 0xF0, 0xFC, 0x3F, 0x0F, 0xC3, 0xF0,
0xFC, 0x3F, 0x0F, 0xC3, 0xF0, 0xFC, 0x3F, 0xFF, 0xFF, 0xFF, 0x7F, 0xC0,
0xF8, 0x00, 0x07, 0x80, 0x00, 0x7C, 0x00, 0x03, 0xC0, 0x00, 0x3E, 0x00,
0x01, 0xE0, 0x00, 0x1F, 0x00, 0x00, 0xF0, 0x00, 0x0F, 0x80, 0x00, 0x78,
0x00, 0x07, 0xC0, 0x00, 0x3E, 0x00, 0x03, 0xE0, 0x00, 0x1F, 0x00, 0x01,
0xF0, 0x00, 0x0F, 0x80, 0x00, 0xF8, 0x00, 0x07, 0xC0, 0x00, 0x7C, 0x00,
0x03, 0xE0, 0x00, 0x1E, 0x00, 0x01, 0xF0, 0x00, 0x0F, 0x00, 0x00, 0xF8,
0x00, 0x07, 0x80, 0x00, 0x7C, 0x00, 0x03, 0xC0, 0x00, 0x3E, 0x00, 0x01,
0xE0, 0x00, 0x1F, 0xFF, 0x3F, 0xEF, 0xFF, 0xFF, 0x0F, 0xC3, 0xF0, 0xFC,
0x3F, 0x0F, 0xC3, 0xF0, 0xFC, 0x3F, 0x0F, 0xC3, 0xF0, 0xFC, 0x3F, 0x0F,
0xC3, 0xF0, 0xFC, 0x3F, 0x0F, 0xC3, 0xF0, 0xFC, 0x3F, 0x0F, 0xC3, 0xF0,
0xFC, 0x3F, 0x0F, 0xC3, 0xF0, 0xFC, 0x3F, 0x0F, 0xFF, 0xFF, 0xFF, 0xFE,
0xFF, 0x00, 0x03, 0xE0, 0x07, 0xE0, 0x0F, 0xF0, 0x0F, 0xF8, 0x1E, 0x78,
0x3E, 0x3C, 0x3C, 0x1E, 0x78, 0x0E, 0xF0, 0x07, 0x60, 0x06, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x10, 0x07, 0x00, 0xF0, 0x3F,
0x8F, 0xF8, 0x3F, 0x81, 0xF8, 0x0E, 0x00, 0x40, 0x00, 0x10, 0x0F, 0xFF,
0xF0, 0xFF, 0xFF, 0x1F, 0xFF, 0xF3, 0xFF, 0xFE, 0x00, 0x0F, 0xC0, 0x00,
0xF8, 0x7F, 0xFF, 0x3F, 0xFF, 0xEF, 0xFF, 0xFD, 0xFF, 0xFF, 0xFF, 0x01,
0xFF, 0xC0, 0x3F, 0xF8, 0x07, 0xFF, 0x03, 0xFB, 0xFB, 0xFF, 0x7F, 0xFF,
0xEF, 0xFF, 0x7C, 0xFF, 0xCF, 0x87, 0xE0, 0xF0, 0xFC, 0x00, 0x0F, 0xC0,
0x00, 0xFC, 0x00, 0x0F, 0xC0, 0x00, 0xFC, 0x00, 0x0F, 0xC0, 0x00, 0xFC,
0x00, 0x0F, 0xC0, 0x00, 0xFC, 0x08, 0x0F, 0xC7, 0xF8, 0xFD, 0xFF, 0xCF,
0xFF, 0xFE, 0xFF, 0xFF, 0xEF, 0xF0, 0x7F, 0xFC, 0x03, 0xFF, 0xC0, 0x3F,
0xFC, 0x03, 0xFF, 0xC0, 0x3F, 0xFC, 0x03, 0xFF, 0xC0, 0x3F, 0xFC, 0x03,
0xFF, 0xC0, 0x3F, 0xFC, 0x07, 0xEF, 0xFB, 0xFE, 0xFF, 0xFF, 0xEF, 0xFF,
0xFC, 0xFF, 0xFF, 0x80, 0xFF, 0xC0, 0x00, 0x40, 0x07, 0xFF, 0x8F, 0xFF,
0xEF, 0xFF, 0xE7, 0xFF, 0xF7, 0xF0, 0x03, 0xF0, 0x01, 0xF8, 0x00, 0xFC,
0x00, 0x7E, 0x00, 0x3F, 0x00, 0x1F, 0x80, 0x0F, 0xC0, 0x07, 0xE0, 0x03,
0xF8, 0x01, 0xFF, 0x9F, 0x7F, 0xFF, 0x9F, 0xFF, 0xC7, 0xFF, 0xE0, 0xFF,
0xC0, 0x00, 0x07, 0xE0, 0x00, 0xFC, 0x00, 0x1F, 0x80, 0x03, 0xF0, 0x00,
0x7E, 0x00, 0x0F, 0xC0, 0x01, 0xF8, 0x00, 0x3F, 0x01, 0x07, 0xE3, 0xFE,
0x7C, 0xFF, 0xFF, 0xBF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC, 0x0F, 0xFF, 0x01,
0xFF, 0xE0, 0x3F, 0xFC, 0x07, 0xFF, 0x80, 0xFF, 0xF0, 0x1F, 0xFE, 0x03,
0xFF, 0xC0, 0x7F, 0xF8, 0x0F, 0xFF, 0x01, 0xFF, 0xFD, 0xFF, 0x7F, 0xFF,
0xEF, 0xFF, 0xFC, 0xFF, 0xCF, 0x87, 0xE0, 0xF0, 0x00, 0x40, 0x01, 0xFF,
0xE0, 0xFF, 0xFE, 0x3F, 0xFF, 0xE7, 0xFF, 0xFF, 0xFC, 0x0F, 0xFF, 0x01,
0xFF, 0xE0, 0x3F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFB, 0xFF, 0xFF, 0x7F, 0xFF,
0x8F, 0xC0, 0x01, 0xF8, 0x00, 0x3F, 0x80, 0x07, 0xFC, 0x7E, 0x7F, 0xFF,
0xC7, 0xFF, 0xF8, 0x7F, 0xFF, 0x03, 0xFF, 0x00, 0x00, 0x38, 0x03, 0xFF,
0x0F, 0xFF, 0x0F, 0xFF, 0x1F, 0xFF, 0x1F, 0xC0, 0x1F, 0x80, 0x1F, 0x80,
0x1F, 0x80, 0x1F, 0x80, 0xFF, 0xFE, 0xFF, 0xFE, 0xFF, 0xFE, 0xFF, 0xFE,
0x1F, 0x80, 0x1F, 0x80, 0x1F, 0x80, 0x1F, 0x80, 0x1F, 0x80, 0x1F, 0x80,
0x1F, 0x80, 0x1F, 0x80, 0x1F, 0x80, 0x1F, 0x80, 0x1F, 0x80, 0x1F, 0x80,
0x1F, 0x80, 0x1F, 0x80, 0x1F, 0x80, 0x00, 0x20, 0x00, 0x7F, 0xFF, 0xF3,
0xFF, 0xFF, 0xDF, 0xFF, 0xFE, 0x7F, 0xFF, 0xE1, 0xF0, 0x0F, 0x87, 0xC0,
0x3E, 0x1F, 0x81, 0xF8, 0x7F, 0xFF, 0xE0, 0xFF, 0xFF, 0x81, 0xFF, 0xFC,
0x07, 0xFF, 0x80, 0x3C, 0x00, 0x00, 0xF8, 0x00, 0x03, 0xFE, 0x00, 0x0F,
0xFF, 0xF0, 0x1F, 0xFF, 0xE0, 0xFF, 0xFF, 0xC7, 0xE3, 0xFF, 0x3F, 0x00,
0x7E, 0xFC, 0x01, 0xFB, 0xF0, 0x07, 0xEF, 0xF0, 0xFF, 0xBF, 0xFF, 0xFC,
0x7F, 0xFF, 0xF0, 0xFF, 0xFF, 0x80, 0xFF, 0xF0, 0x00, 0xFC, 0x00, 0x0F,
0xC0, 0x00, 0xFC, 0x00, 0x0F, 0xC0, 0x00, 0xFC, 0x00, 0x0F, 0xC0, 0x00,
0xFC, 0x00, 0x0F, 0xC0, 0x00, 0xFC, 0x02, 0x0F, 0xC7, 0xFC, 0xFD, 0xFF,
0xEF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF, 0xF8, 0x7F, 0xFE, 0x03, 0xFF, 0xC0,
0x3F, 0xFC, 0x03, 0xFF, 0xC0, 0x3F, 0xFC, 0x03, 0xFF, 0xC0, 0x3F, 0xFC,
0x03, 0xFF, 0xC0, 0x3F, 0xFC, 0x03, 0xFF, 0xC0, 0x3F, 0xFC, 0x03, 0xFF,
0xC0, 0x3F, 0xFC, 0x03, 0xFF, 0xC0, 0x3F, 0x38, 0xFB, 0xFF, 0xFF, 0xEF,
0x8E, 0x00, 0x00, 0x01, 0xF3, 0xE7, 0xCF, 0x9F, 0x3E, 0x7C, 0xF9, 0xF3,
0xE7, 0xCF, 0x9F, 0x3E, 0x7C, 0xF9, 0xF3, 0xE7, 0xC0, 0x0E, 0x0F, 0x87,
0xE3, 0xF1, 0xF8, 0xF8, 0x38, 0x00, 0x00, 0x00, 0x07, 0xE3, 0xF1, 0xF8,
0xFC, 0x7E, 0x3F, 0x1F, 0x8F, 0xC7, 0xE3, 0xF1, 0xF8, 0xFC, 0x7E, 0x3F,
0x1F, 0x8F, 0xC7, 0xE3, 0xF1, 0xF8, 0xF8, 0xFC, 0x7E, 0x3F, 0x3F, 0x3F,
0x8F, 0x81, 0x80, 0xFC, 0x00, 0x0F, 0xC0, 0x00, 0xFC, 0x00, 0x0F, 0xC0,
0x00, 0xFC, 0x00, 0x0F, 0xC0, 0x00, 0xFC, 0x00, 0x0F, 0xC0, 0x00, 0xFC,
0x00, 0x0F, 0xC0, 0xFE, 0xFC, 0x0F, 0xCF, 0xC1, 0xF8, 0xFC, 0x3F, 0x8F,
0xC7, 0xF0, 0xFC, 0xFE, 0x0F, 0xFF, 0xC0, 0xFF, 0xF8, 0x0F, 0xFF, 0x80,
0xFF, 0xFC, 0x0F, 0xCF, 0xE0, 0xFC, 0x7E, 0x0F, 0xC7, 0xF0, 0xFC, 0x3F,
0x0F, 0xC1, 0xF8, 0xFC, 0x1F, 0xCF, 0xC0, 0xFC, 0xFC, 0x07, 0xEF, 0xC0,
0x7F, 0xFC, 0x1F, 0x83, 0xF0, 0x7E, 0x0F, 0xC1, 0xF8, 0x3F, 0x07, 0xE0,
0xFC, 0x1F, 0x83, 0xF0, 0x7E, 0x0F, 0xC1, 0xF8, 0x3F, 0x07, 0xE0, 0xFC,
0x1F, 0x83, 0xF0, 0x7E, 0x0F, 0xC1, 0xF8, 0x3F, 0x03, 0xF8, 0x7F, 0xCF,
0xFC, 0xFF, 0x8F, 0xE0, 0x00, 0x04, 0x00, 0x41, 0xF0, 0xFF, 0x0F, 0xF3,
0xE7, 0xFF, 0x7F, 0xF7, 0xFF, 0xFF, 0xFF, 0xEF, 0xFF, 0xFF, 0xFF, 0xFF,
0xE1, 0xFE, 0x0F, 0xFF, 0x81, 0xF8, 0x1F, 0xFE, 0x03, 0xE0, 0x3F, 0xFC,
0x07, 0xC0, 0x7F, 0xF8, 0x0F, 0x80, 0xFF, 0xF0, 0x1F, 0x01, 0xFF, 0xE0,
0x3E, 0x03, 0xFF, 0xC0, 0x7C, 0x07, 0xFF, 0x80, 0xF8, 0x0F, 0xFF, 0x01,
0xF0, 0x1F, 0xFE, 0x03, 0xE0, 0x3F, 0xFC, 0x07, 0xC0, 0x7F, 0xF8, 0x0F,
0x80, 0xFF, 0xF0, 0x1F, 0x01, 0xFF, 0xE0, 0x3E, 0x03, 0xF0, 0x00, 0x02,
0x0F, 0x87, 0xFC, 0xFD, 0xFF, 0xEF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF, 0xF8,
0x7F, 0xFE, 0x03, 0xFF, 0xC0, 0x3F, 0xFC, 0x03, 0xFF, 0xC0, 0x3F, 0xFC,
0x03, 0xFF, 0xC0, 0x3F, 0xFC, 0x03, 0xFF, 0xC0, 0x3F, 0xFC, 0x03, 0xFF,
0xC0, 0x3F, 0xFC, 0x03, 0xFF, 0xC0, 0x3F, 0xFC, 0x03, 0xFF, 0xC0, 0x3F,
0x00, 0x40, 0x00, 0xFF, 0xF0, 0x3F, 0xFF, 0x87, 0xFF, 0xFC, 0x7F, 0xFF,
0xEF, 0xE0, 0xFE, 0xFC, 0x07, 0xEF, 0xC0, 0x7F, 0xFC, 0x03, 0xFF, 0xC0,
0x3F, 0xFC, 0x03, 0xFF, 0xC0, 0x3F, 0xFC, 0x03, 0xFF, 0xC0, 0x7F, 0xFC,
0x07, 0xFF, 0xE0, 0xFE, 0x7F, 0xFF, 0xE7, 0xFF, 0xFC, 0x3F, 0xFF, 0x80,
0xFF, 0xF0, 0x00, 0x40, 0x00, 0x00, 0x04, 0x0F, 0x87, 0xF8, 0xF9, 0xFF,
0xCF, 0xFF, 0xFE, 0xFF, 0xFF, 0xEF, 0xF0, 0x7F, 0xFE, 0x03, 0xFF, 0xC0,
0x3F, 0xFC, 0x03, 0xFF, 0xC0, 0x3F, 0xFC, 0x03, 0xFF, 0xC0, 0x3F, 0xFC,
0x03, 0xFF, 0xC0, 0x3F, 0xFC, 0x03, 0xFF, 0xE0, 0x7F, 0xFF, 0xFF, 0xEF,
0xFF, 0xFE, 0xFF, 0xFF, 0xCF, 0xCF, 0xF8, 0xFC, 0x08, 0x0F, 0xC0, 0x00,
0xFC, 0x00, 0x0F, 0xC0, 0x00, 0xFC, 0x00, 0x0F, 0xC0, 0x00, 0xFC, 0x00,
0x00, 0x00, 0x40, 0x01, 0xFF, 0xF8, 0xFF, 0xFF, 0xBF, 0xFF, 0xF7, 0xFF,
0xFF, 0xFC, 0x0F, 0xFF, 0x01, 0xFF, 0xE0, 0x3F, 0xFC, 0x07, 0xFF, 0x80,
0xFF, 0xF0, 0x1F, 0xFE, 0x03, 0xFF, 0xC0, 0x7F, 0xF8, 0x0F, 0xFF, 0x01,
0xFF, 0xF0, 0x7F, 0xFF, 0xFF, 0xEF, 0xFF, 0xFC, 0xFF, 0xEF, 0x8F, 0xF3,
0xF0, 0x20, 0x7E, 0x00, 0x0F, 0xC0, 0x01, 0xF8, 0x00, 0x3F, 0x00, 0x07,
0xE0, 0x00, 0xFC, 0x00, 0x1F, 0x80, 0x00, 0x03, 0xF0, 0xFB, 0xE7, 0xF7,
0xFF, 0xEF, 0xFF, 0xDF, 0xFE, 0x3F, 0xC0, 0x7E, 0x00, 0xFC, 0x01, 0xF8,
0x03, 0xF0, 0x07, 0xE0, 0x0F, 0xC0, 0x1F, 0x80, 0x3F, 0x00, 0x7E, 0x00,
0xFC, 0x01, 0xF8, 0x03, 0xF0, 0x07, 0xE0, 0x00, 0x00, 0x80, 0x03, 0xFF,
0xF9, 0xFF, 0xFF, 0x3F, 0xFF, 0xE7, 0xFF, 0xFD, 0xF8, 0x00, 0x1F, 0x00,
0x03, 0xF8, 0x00, 0x7F, 0xF0, 0x07, 0xFF, 0xC0, 0x7F, 0xFE, 0x01, 0xFF,
0xE0, 0x03, 0xFC, 0x00, 0x0F, 0xC0, 0x01, 0xF8, 0x00, 0xFF, 0x7F, 0xFF,
0xCF, 0xFF, 0xF9, 0xFF, 0xFE, 0x1F, 0xFF, 0x00, 0x1F, 0x80, 0x3F, 0x00,
0x7E, 0x00, 0xFC, 0x01, 0xF8, 0x03, 0xF0, 0x07, 0xE0, 0x7F, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xF8, 0xFC, 0x01, 0xF8, 0x03, 0xF0, 0x07, 0xE0,
0x0F, 0xC0, 0x1F, 0x80, 0x3F, 0x00, 0x7E, 0x00, 0xFC, 0x01, 0xF8, 0x03,
0xFC, 0x07, 0xFF, 0x07, 0xFE, 0x07, 0xFC, 0x07, 0xF8, 0xFC, 0x07, 0xFF,
0x80, 0xFF, 0xF0, 0x1F, 0xFE, 0x03, 0xFF, 0xC0, 0x7F, 0xF8, 0x0F, 0xFF,
0x01, 0xFF, 0xE0, 0x3F, 0xFC, 0x07, 0xFF, 0x80, 0xFF, 0xF0, 0x1F, 0xFE,
0x03, 0xFF, 0xC0, 0x7F, 0xF8, 0x0F, 0xFF, 0x87, 0xFF, 0xFF, 0xFF, 0x7F,
0xFF, 0xEF, 0xFF, 0x7C, 0xFF, 0x8F, 0x82, 0x00, 0x00, 0xFE, 0x00, 0xFD,
0xF8, 0x07, 0xF7, 0xE0, 0x1F, 0x8F, 0xC0, 0x7E, 0x3F, 0x01, 0xF8, 0xFC,
0x0F, 0xC1, 0xF8, 0x3F, 0x07, 0xE0, 0xF8, 0x1F, 0x87, 0xE0, 0x3F, 0x1F,
0x80, 0xFC, 0x7C, 0x03, 0xF3, 0xF0, 0x07, 0xCF, 0xC0, 0x1F, 0xBE, 0x00,
0x3E, 0xF8, 0x00, 0xFF, 0xE0, 0x03, 0xFF, 0x00, 0x07, 0xFC, 0x00, 0x1F,
0xE0, 0x00, 0xFC, 0x0F, 0xE0, 0x3F, 0xFC, 0x0F, 0xF0, 0x3F, 0xFC, 0x0F,
0xF0, 0x3F, 0x7C, 0x1F, 0xF0, 0x7E, 0x7E, 0x1E, 0xF8, 0x7E, 0x7E, 0x1E,
0xF8, 0x7E, 0x7E, 0x1E, 0x78, 0x7C, 0x3E, 0x1E, 0x78, 0x7C, 0x3E, 0x3E,
0x78, 0xFC, 0x3F, 0x3E, 0x7C, 0xFC, 0x1F, 0x3C, 0x7C, 0xF8, 0x1F, 0x3C,
0x3C, 0xF8, 0x1F, 0x3C, 0x3D, 0xF8, 0x1F, 0xBC, 0x3D, 0xF8, 0x0F, 0xFC,
0x3F, 0xF0, 0x0F, 0xFC, 0x3F, 0xF0, 0x0F, 0xF8, 0x3F, 0xF0, 0x0F, 0xF8,
0x1F, 0xE0, 0x07, 0xF8, 0x1F, 0xE0, 0x7E, 0x01, 0xFC, 0xFC, 0x07, 0xE3,
0xF0, 0x3F, 0x07, 0xE0, 0xFC, 0x0F, 0x87, 0xE0, 0x3F, 0x3F, 0x00, 0x7E,
0xFC, 0x01, 0xFF, 0xE0, 0x03, 0xFF, 0x80, 0x0F, 0xFC, 0x00, 0x3F, 0xF8,
0x01, 0xFB, 0xE0, 0x0F, 0xCF, 0xC0, 0x3F, 0x1F, 0x81, 0xF8, 0x3E, 0x07,
0xC0, 0xFC, 0x3F, 0x01, 0xF9, 0xF8, 0x07, 0xEF, 0xE0, 0x0F, 0xC0, 0xFE,
0x00, 0xFD, 0xF8, 0x07, 0xF7, 0xE0, 0x1F, 0x8F, 0xC0, 0x7E, 0x3F, 0x03,
0xF0, 0xFC, 0x0F, 0xC1, 0xF8, 0x3F, 0x07, 0xE0, 0xF8, 0x1F, 0x87, 0xE0,
0x3E, 0x1F, 0x80, 0xFC, 0x7C, 0x03, 0xF3, 0xF0, 0x07, 0xCF, 0x80, 0x1F,
0xBE, 0x00, 0x3E, 0xF8, 0x00, 0xFF, 0xC0, 0x03, 0xFF, 0x00, 0x07, 0xFC,
0x00, 0x1F, 0xE0, 0x00, 0x1F, 0x80, 0x00, 0x7C, 0x00, 0x03, 0xF0, 0x00,
0x7F, 0x80, 0x03, 0xFC, 0x00, 0x0F, 0xE0, 0x00, 0x3E, 0x00, 0x00, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x03, 0xF8, 0x03, 0xF8,
0x03, 0xF8, 0x03, 0xF8, 0x03, 0xF8, 0x03, 0xF8, 0x03, 0xF8, 0x03, 0xF8,
0x03, 0xF8, 0x03, 0xF8, 0x03, 0xF0, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xE0, 0x03, 0xE1, 0xFC, 0x7F, 0x8F, 0xF1, 0xF8, 0x7E,
0x0F, 0xC1, 0xF8, 0x3F, 0x07, 0xE0, 0xFC, 0x1F, 0x83, 0xF0, 0x7E, 0x0F,
0xC3, 0xF8, 0xFE, 0x1F, 0x03, 0xF0, 0x7F, 0x03, 0xF0, 0x3E, 0x07, 0xC0,
0xF8, 0x1F, 0x03, 0xE0, 0x7C, 0x0F, 0x81, 0xF0, 0x3E, 0x07, 0xC0, 0xF8,
0x1F, 0x83, 0xFC, 0x7F, 0x87, 0xF0, 0x3E, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xF0, 0xFC, 0x1F, 0xE3, 0xFC, 0x7F, 0xC1, 0xF8, 0x3F, 0x03, 0xE0,
0x7C, 0x0F, 0x81, 0xF0, 0x3E, 0x07, 0xC1, 0xF8, 0x1F, 0x03, 0xE0, 0x7E,
0x07, 0xE0, 0x3C, 0x1F, 0x87, 0xF0, 0xF8, 0x3F, 0x07, 0xE0, 0xFC, 0x1F,
0x83, 0xF0, 0x7E, 0x0F, 0xC1, 0xF8, 0x3F, 0x07, 0xE0, 0xFC, 0x1F, 0x9F,
0xF3, 0xFC, 0x7F, 0x0F, 0xC0, 0x3E, 0x07, 0x7F, 0xC7, 0x7F, 0xFF, 0xFF,
0xFF, 0xE3, 0xFF, 0xE0, 0x3E };
const GFXglyph Exo2_Bold_36pt7bGlyphs[] = {
{ 0, 1, 1, 9, 0, 0 }, // 0x20 ' '
{ 1, 6, 27, 12, 3, -26 }, // 0x21 '!'
{ 22, 11, 9, 15, 2, -26 }, // 0x22 '"'
{ 35, 26, 27, 28, 1, -26 }, // 0x23 '#'
{ 123, 20, 36, 23, 2, -31 }, // 0x24 '$'
{ 213, 34, 28, 36, 1, -27 }, // 0x25 '%'
{ 332, 27, 28, 31, 2, -27 }, // 0x26 '&'
{ 427, 4, 9, 9, 2, -26 }, // 0x27 '''
{ 432, 12, 39, 15, 2, -31 }, // 0x28 '('
{ 491, 12, 39, 15, 1, -31 }, // 0x29 ')'
{ 550, 15, 14, 18, 2, -26 }, // 0x2A '*'
{ 577, 18, 17, 22, 2, -19 }, // 0x2B '+'
{ 616, 6, 12, 10, 2, -5 }, // 0x2C ','
{ 625, 12, 4, 17, 2, -11 }, // 0x2D '-'
{ 631, 6, 6, 10, 2, -5 }, // 0x2E '.'
{ 636, 20, 30, 22, 1, -26 }, // 0x2F '/'
{ 711, 21, 29, 25, 2, -27 }, // 0x30 '0'
{ 788, 13, 27, 17, 0, -26 }, // 0x31 '1'
{ 832, 19, 28, 23, 2, -27 }, // 0x32 '2'
{ 899, 19, 29, 23, 2, -27 }, // 0x33 '3'
{ 968, 23, 27, 25, 1, -26 }, // 0x34 '4'
{ 1046, 18, 27, 22, 2, -26 }, // 0x35 '5'
{ 1107, 20, 28, 24, 2, -27 }, // 0x36 '6'
{ 1177, 19, 27, 21, 1, -26 }, // 0x37 '7'
{ 1242, 21, 28, 25, 2, -27 }, // 0x38 '8'
{ 1316, 19, 28, 24, 2, -27 }, // 0x39 '9'
{ 1383, 6, 18, 10, 2, -17 }, // 0x3A ':'
{ 1397, 6, 24, 10, 2, -17 }, // 0x3B ';'
{ 1415, 16, 18, 21, 2, -20 }, // 0x3C '<'
{ 1451, 19, 12, 23, 2, -16 }, // 0x3D '='
{ 1480, 17, 18, 21, 2, -20 }, // 0x3E '>'
{ 1519, 18, 29, 21, 1, -28 }, // 0x3F '?'
{ 1585, 26, 26, 30, 2, -22 }, // 0x40 '@'
{ 1670, 26, 27, 26, 0, -26 }, // 0x41 'A'
{ 1758, 21, 28, 25, 3, -27 }, // 0x42 'B'
{ 1832, 20, 28, 23, 2, -27 }, // 0x43 'C'
{ 1902, 22, 27, 27, 3, -26 }, // 0x44 'D'
{ 1977, 18, 27, 23, 3, -26 }, // 0x45 'E'
{ 2038, 18, 27, 22, 3, -26 }, // 0x46 'F'
{ 2099, 22, 29, 26, 2, -27 }, // 0x47 'G'
{ 2179, 22, 27, 28, 3, -26 }, // 0x48 'H'
{ 2254, 6, 27, 12, 3, -26 }, // 0x49 'I'
{ 2275, 11, 27, 15, 1, -26 }, // 0x4A 'J'
{ 2313, 22, 27, 25, 3, -26 }, // 0x4B 'K'
{ 2388, 18, 27, 21, 3, -26 }, // 0x4C 'L'
{ 2449, 32, 27, 36, 2, -26 }, // 0x4D 'M'
{ 2557, 23, 27, 29, 3, -26 }, // 0x4E 'N'
{ 2635, 24, 29, 27, 2, -27 }, // 0x4F 'O'
{ 2722, 20, 28, 25, 3, -27 }, // 0x50 'P'
{ 2792, 24, 37, 27, 2, -27 }, // 0x51 'Q'
{ 2903, 22, 28, 26, 3, -27 }, // 0x52 'R'
{ 2980, 20, 29, 23, 2, -27 }, // 0x53 'S'
{ 3053, 22, 27, 24, 1, -26 }, // 0x54 'T'
{ 3128, 22, 28, 27, 3, -26 }, // 0x55 'U'
{ 3205, 25, 27, 25, 0, -26 }, // 0x56 'V'
{ 3290, 37, 27, 39, 1, -26 }, // 0x57 'W'
{ 3415, 25, 27, 26, 0, -26 }, // 0x58 'X'
{ 3500, 24, 27, 24, 0, -26 }, // 0x59 'Y'
{ 3581, 20, 27, 23, 2, -26 }, // 0x5A 'Z'
{ 3649, 10, 37, 14, 3, -30 }, // 0x5B '['
{ 3696, 20, 30, 22, 1, -26 }, // 0x5C '\'
{ 3771, 10, 37, 14, 1, -30 }, // 0x5D ']'
{ 3818, 16, 10, 18, 1, -24 }, // 0x5E '^'
{ 3838, 18, 4, 18, 0, 1 }, // 0x5F '_'
{ 3847, 11, 9, 14, 1, -29 }, // 0x60 '`'
{ 3860, 19, 20, 23, 1, -19 }, // 0x61 'a'
{ 3908, 20, 28, 24, 2, -27 }, // 0x62 'b'
{ 3978, 17, 20, 20, 2, -19 }, // 0x63 'c'
{ 4021, 19, 28, 24, 2, -27 }, // 0x64 'd'
{ 4088, 19, 20, 22, 2, -19 }, // 0x65 'e'
{ 4136, 16, 29, 16, 1, -28 }, // 0x66 'f'
{ 4194, 22, 27, 23, 1, -19 }, // 0x67 'g'
{ 4269, 20, 28, 24, 2, -27 }, // 0x68 'h'
{ 4339, 7, 29, 11, 2, -28 }, // 0x69 'i'
{ 4365, 9, 37, 11, 0, -28 }, // 0x6A 'j'
{ 4407, 20, 28, 22, 2, -27 }, // 0x6B 'k'
{ 4477, 11, 28, 13, 2, -27 }, // 0x6C 'l'
{ 4516, 31, 20, 35, 2, -19 }, // 0x6D 'm'
{ 4594, 20, 20, 24, 2, -19 }, // 0x6E 'n'
{ 4644, 20, 21, 23, 2, -19 }, // 0x6F 'o'
{ 4697, 20, 27, 24, 2, -19 }, // 0x70 'p'
{ 4765, 19, 27, 24, 2, -19 }, // 0x71 'q'
{ 4830, 15, 20, 17, 2, -19 }, // 0x72 'r'
{ 4868, 19, 20, 21, 1, -19 }, // 0x73 's'
{ 4916, 15, 26, 16, 1, -25 }, // 0x74 't'
{ 4965, 19, 20, 24, 2, -18 }, // 0x75 'u'
{ 5013, 22, 19, 23, 0, -18 }, // 0x76 'v'
{ 5066, 32, 19, 34, 1, -18 }, // 0x77 'w'
{ 5142, 22, 19, 23, 0, -18 }, // 0x78 'x'
{ 5195, 22, 26, 22, 0, -18 }, // 0x79 'y'
{ 5267, 17, 19, 21, 2, -18 }, // 0x7A 'z'
{ 5308, 11, 37, 14, 1, -29 }, // 0x7B '{'
{ 5359, 4, 37, 10, 3, -29 }, // 0x7C '|'
{ 5378, 11, 37, 14, 1, -29 }, // 0x7D '}'
{ 5429, 16, 6, 21, 2, -13 } }; // 0x7E '~'
const GFXfont Exo2_Bold_36pt7b = {
(uint8_t *)Exo2_Bold_36pt7bBitmaps,
(GFXglyph *)Exo2_Bold_36pt7bGlyphs,
0x20, 0x7E, 36 };//B
// Approx. 6113 bytes
|
908628.c | /*------------------------------------------------------------------------------
Copyright (c) 2008 The Khronos Group Inc.
All Rights Reserved. This code is protected by copyright laws and contains
material proprietary to the Khronos Group, Inc. This is UNPUBLISHED
PROPRIETARY SOURCE CODE that may not be disclosed in whole or in part to third
parties, and may not be reproduced, republished, distributed, transmitted,
displayed, broadcast or otherwise exploited in any manner without the express
prior written permission of Khronos Group.
The receipt or possession of this code does not convey any rights to reproduce,
disclose, or distribute its contents, or to manufacture, use, or sell anything
that it may describe, in whole or in part other than under the terms of the
Khronos Adopters Agreement or Khronos Conformance Test Source License Agreement
as executed between Khronos and the recipient.
For the avoidance of doubt, this code when provided: a) under the Khronos
Conformance Test Source License Agreement is for the sole purpose of creating
conformance tests for delivery to Khronos and does not provide for formally
testing products or use of Khronos trademarks on conformant products; b) under
the Khronos Adopters Agreement is for the sole purpose of formally
administering tests to products pursuant to the Khronos Conformance Process
Document.
Khronos, OpenKODE, OpenVG, OpenWF, glFX, OpenMAX and OpenSL ES are trademarks
of the Khronos Group Inc. COLLADA is a trademark of Sony Computer
Entertainment Inc. used by permission by Khronos. OpenGL and OpenML are
registered trademarks and the OpenGL ES logo is a trademark of Silicon Graphics
Inc. used by permission by Khronos.
Use, duplication or disclosure by the Government is subject to restrictions as
set forth in subdivision (c)(1)(ii) of the Rights in Technical Data and
Computer Software clause at DFARS 252.227-7013, and/or in similar or successor
clauses in the FAR, DOD or NASA FAR Supplement. Unpublished rights reserved
under the Copyright Laws of the United States and other countries.
------------------------------------------------------------------------------*/
#include "../main.h"
#include "../util/util.h"
int A30101_ParameterObject_by_HUONE (CT_File AnsFile, CT_File RefFile)
{
return (int)ValueDiff_by_HUONE( AnsFile.dat, RefFile.dat );
}
|
672840.c | /*
* FIG : Facility for Interactive Generation of figures
* Copyright (c) 1991 by Paul King
* Parts Copyright (c) 1989-2002 by Brian V. Smith
*
* Any party obtaining a copy of these files is granted, free of charge, a
* full and unrestricted irrevocable, world-wide, paid up, royalty-free,
* nonexclusive right and license to deal in this software and documentation
* files (the "Software"), including without limitation the rights to use,
* copy, modify, merge, publish distribute, sublicense and/or sell copies of
* the Software, and to permit persons who receive copies from any such
* party to do so, with the only requirement being that the above copyright
* and this permission notice remain intact.
*
*/
#include "fig.h"
#include "resources.h"
#include "object.h"
#include "paintop.h"
#include "mode.h"
#include "u_create.h"
#include "u_draw.h"
#include "u_search.h"
#include "u_undo.h"
#include "w_canvas.h"
#include "w_layers.h"
#include "w_mousefun.h"
#include "w_msgpanel.h"
#include "w_setup.h"
#include "u_bound.h"
#include "u_markers.h"
#include "u_translate.h"
#include "w_cursor.h"
static int llx, lly, urx, ury;
static int xcmin, ycmin, xcmax, ycmax;
static int dx, dy;
static Boolean pos_arc(F_arc *a, int *min, int *size, int dir);
static Boolean pos_ellipse(F_ellipse *e, int *min, int *size, int dir);
static Boolean pos_line(F_line *l, int *min, int *size, int dir);
static Boolean pos_spline(F_spline *s, int *min, int *size, int dir);
static Boolean pos_text(F_text *t, int *min, int *size, int dir);
static Boolean pos_compound(F_compound *c, int *min, int *size, int dir);
static void init_align(F_line *p, int type, int x, int y, int px, int py);
static void init_align_canvas(int x, int y, unsigned int shift);
static void align_arc(void);
static void align_ellipse(void);
static void align_line(void);
static void align_spline(void);
static void align_text(void);
static void align_compound(void);
static void get_dx_dy(void);
static void distribute_horizontally(void);
static void distribute_vertically(void);
void
align_selected(void)
{
set_mousefun("align compound", "align canvas", "", LOC_OBJ, "", LOC_OBJ);
canvas_kbd_proc = null_proc;
canvas_locmove_proc = null_proc;
canvas_ref_proc = null_proc;
init_searchproc_left(init_align);
canvas_leftbut_proc = object_search_left;
canvas_middlebut_proc = init_align_canvas;
canvas_rightbut_proc = null_proc;
set_cursor(pick15_cursor);
reset_action_on();
}
/* align objects to the whole canvas */
static void
init_align_canvas(int x, int y, unsigned int shift)
/* Shift Key Status from XEvent */
{
int ux;
cur_c = &objects;
toggle_all_compoundmarkers();
draw_compoundelements(cur_c, ERASE);
old_c = copy_compound(&objects);
xcmin=ycmin=0;
/* get the current page size */
xcmax = paper_sizes[appres.papersize].width;
ycmax = paper_sizes[appres.papersize].height;
if (!appres.INCHES) {
xcmax = (int)(xcmax*2.54*PIX_PER_CM/PIX_PER_INCH);
ycmax = (int)(ycmax*2.54*PIX_PER_CM/PIX_PER_INCH);
}
/* swap height and width if landscape */
if (appres.landscape) {
ux = xcmax;
xcmax = ycmax;
ycmax = ux;
}
align_ellipse();
align_arc();
align_line();
align_spline();
align_compound();
align_text();
/*
* Display messages indicating that distribution or alignment can't be
* performed with respect to the canvas.
*/
if ((cur_halign == ALIGN_DISTRIB_C) || (cur_halign == ALIGN_DISTRIB_E))
put_msg("Can't DISTRIBUTE horizontally with respect to the canvas");
else if (cur_halign == ALIGN_ABUT)
put_msg("Can't ABUT horizontally with respect to the canvas");
if ((cur_valign == ALIGN_DISTRIB_C) || (cur_valign == ALIGN_DISTRIB_E))
put_msg("Can't DISTRIBUTE vertically with respect to the canvas");
else if (cur_valign == ALIGN_ABUT)
put_msg("Can't ABUT vertically with respect to the canvas");
draw_compoundelements(cur_c, PAINT);
toggle_all_compoundmarkers();
clean_up();
set_latestobjects(old_c);
set_action_object(F_EDIT, O_ALL_OBJECT);
set_modifiedflag();
}
static void
init_align(F_line *p, int type, int x, int y, int px, int py)
{
if (type != O_COMPOUND)
return;
cur_c = (F_compound *) p;
toggle_compoundmarker(cur_c);
draw_compoundelements(cur_c, ERASE);
old_c = copy_compound(cur_c);
compound_bound(cur_c, &xcmin, &ycmin, &xcmax, &ycmax);
align_ellipse();
align_arc();
align_line();
align_spline();
align_compound();
align_text();
/*
* Perform the distribution of the objects in the compound
*/
if ( (cur_halign == ALIGN_DISTRIB_C) || (cur_halign == ALIGN_DISTRIB_E)
|| (cur_halign == ALIGN_ABUT) )
distribute_horizontally();
if ( (cur_valign == ALIGN_DISTRIB_C) || (cur_valign == ALIGN_DISTRIB_E)
|| (cur_valign == ALIGN_ABUT) )
distribute_vertically();
/*
* recompute the compound's bounding box
*/
compound_bound(cur_c, &cur_c->nwcorner.x, &cur_c->nwcorner.y,
&cur_c->secorner.x, &cur_c->secorner.y);
draw_compoundelements(cur_c, PAINT);
toggle_compoundmarker(cur_c);
clean_up();
old_c->next = cur_c;
set_latestcompound(old_c);
set_action_object(F_EDIT, O_COMPOUND);
set_modifiedflag();
}
static void
align_ellipse(void)
{
F_ellipse *e;
for (e = cur_c->ellipses; e != NULL; e = e->next) {
if (!active_layer(e->depth))
continue;
ellipse_bound(e, &llx, &lly, &urx, &ury);
get_dx_dy();
translate_ellipse(e, dx, dy);
}
}
static void
align_arc(void)
{
F_arc *a;
for (a = cur_c->arcs; a != NULL; a = a->next) {
if (!active_layer(a->depth))
continue;
arc_bound(a, &llx, &lly, &urx, &ury);
get_dx_dy();
translate_arc(a, dx, dy);
}
}
static void
align_line(void)
{
F_line *l;
for (l = cur_c->lines; l != NULL; l = l->next) {
if (!active_layer(l->depth))
continue;
line_bound(l, &llx, &lly, &urx, &ury);
get_dx_dy();
translate_line(l, dx, dy);
}
}
static void
align_spline(void)
{
F_spline *s;
for (s = cur_c->splines; s != NULL; s = s->next) {
if (!active_layer(s->depth))
continue;
spline_bound(s, &llx, &lly, &urx, &ury);
get_dx_dy();
translate_spline(s, dx, dy);
}
}
static void
align_compound(void)
{
F_compound *c;
for (c = cur_c->compounds; c != NULL; c = c->next) {
if (!any_active_in_compound(c))
continue;
compound_bound(c, &llx, &lly, &urx, &ury);
get_dx_dy();
translate_compound(c, dx, dy);
}
}
static void
align_text(void)
{
F_text *t;
int dum;
for (t = cur_c->texts; t != NULL; t = t->next) {
if (!active_layer(t->depth))
continue;
text_bound(t, &llx, &lly, &urx, &ury,
&dum,&dum,&dum,&dum,&dum,&dum,&dum,&dum);
get_dx_dy();
translate_text(t, dx, dy);
}
}
static void
get_dx_dy(void)
{
switch (cur_valign) {
case ALIGN_NONE:
dy = 0;
break;
case ALIGN_TOP:
dy = ycmin - lly;
break;
case ALIGN_BOTTOM:
dy = ycmax - ury;
break;
case ALIGN_CENTER:
dy = (ycmin - lly) + (abs(ycmin - lly) + abs(ycmax - ury)) / 2;
break;
case ALIGN_DISTRIB_C:
case ALIGN_DISTRIB_E:
case ALIGN_ABUT:
break;
}
switch (cur_halign) {
case ALIGN_NONE:
dx = 0;
break;
case ALIGN_LEFT:
dx = xcmin - llx;
break;
case ALIGN_RIGHT:
dx = xcmax - urx;
break;
case ALIGN_CENTER:
dx = (xcmin - llx) + (abs(xcmin - llx) + abs(xcmax - urx)) / 2;
break;
case ALIGN_DISTRIB_C:
case ALIGN_DISTRIB_E:
case ALIGN_ABUT:
break;
}
}
/* ====================== Object distribution routines =================== */
/*
* pos_arc: If the position of the given arc is less than
* passed in and the arc hasn't already been distributed, adjust the value
* of the passed in parameter. Also set the width/height if smaller.
* If dir == 0, handle horizontal, otherwise vertical.
*/
static Boolean
pos_arc (F_arc *a, int *min, int *size, int dir)
{
int center;
arc_bound (a, &llx, &lly, &urx, &ury);
if (dir == 0) {
if (cur_halign == ALIGN_DISTRIB_C)
center = (urx + llx)/2;
else
center = min2(urx, llx);
} else {
if (cur_valign == ALIGN_DISTRIB_C)
center = (ury + lly)/2;
else
center = min2(ury, lly);
}
if ( (center < *min) && (a->distrib == 0) ) {
*min = center;
if (dir == 0)
*size = abs(urx - llx);
else
*size = abs(ury - lly);
return True;
} else
return False;
} /* pos_arc */
/*
* pos_ellipse: If the position of the given ellipse is less
* than passed in and the ellipse hasn't already been distributed, adjust the
* value of the passed in parameter. Also set the width/height if smaller.
* If dir == 0, handle horizontal, otherwise vertical.
*/
static Boolean
pos_ellipse (F_ellipse *e, int *min, int *size, int dir)
{
int center;
ellipse_bound (e, &llx, &lly, &urx, &ury);
if (dir == 0) {
if (cur_halign == ALIGN_DISTRIB_C)
center = (urx + llx)/2;
else
center = min2(urx, llx);
} else {
if (cur_valign == ALIGN_DISTRIB_C)
center = (ury + lly)/2;
else
center = min2(ury, lly);
}
if ( (center < *min) && (e->distrib == 0) ) {
*min = center;
if (dir == 0)
*size = abs(urx - llx);
else
*size = abs(ury - lly);
return True;
} else
return False;
} /* pos_ellipse */
/*
* pos_line: If the position of the given line is less than
* passed in and the line hasn't already been distributed, adjust the value
* of the passed in parameter. Also set the width/height if smaller.
* If dir == 0, handle horizontal, otherwise vertical.
*/
static Boolean
pos_line (F_line *l, int *min, int *size, int dir)
{
int center;
line_bound (l, &llx, &lly, &urx, &ury);
if (dir == 0) {
if (cur_halign == ALIGN_DISTRIB_C)
center = (urx + llx)/2;
else
center = min2(urx, llx);
} else {
if (cur_valign == ALIGN_DISTRIB_C)
center = (ury + lly)/2;
else
center = min2(ury, lly);
}
if ( (center < *min) && (l->distrib == 0) ) {
*min = center;
if (dir == 0)
*size = abs(urx - llx);
else
*size = abs(ury - lly);
return True;
} else
return False;
} /* pos_line */
/*
* pos_spline: If the position of the given spline is less than
* passed in and the spline hasn't already been distributed, adjust the value
* of the passed in parameter. Also set the width/height if smaller.
* If dir == 0, handle horizontal, otherwise vertical.
*/
static Boolean
pos_spline (F_spline *s, int *min, int *size, int dir)
{
int center;
spline_bound (s, &llx, &lly, &urx, &ury);
if (dir == 0) {
if (cur_halign == ALIGN_DISTRIB_C)
center = (urx + llx)/2;
else
center = min2(urx, llx);
} else {
if (cur_valign == ALIGN_DISTRIB_C)
center = (ury + lly)/2;
else
center = min2(ury, lly);
}
if ( (center < *min) && (s->distrib == 0) ) {
*min = center;
if (dir == 0)
*size = abs(urx - llx);
else
*size = abs(ury - lly);
return True;
} else
return False;
} /* pos_spline */
/*
* pos_text: If the position of the given text is less than
* passed in and the text hasn't already been distributed, adjust the value
* of the passed in parameter. Also set the width/height if smaller.
* If dir == 0, handle horizontal, otherwise vertical.
*/
static Boolean
pos_text (F_text *t, int *min, int *size, int dir)
{
int center, dum;
text_bound (t, &llx, &lly, &urx, &ury,
&dum,&dum,&dum,&dum,&dum,&dum,&dum,&dum);
if (dir == 0) {
if (cur_halign == ALIGN_DISTRIB_C)
center = (urx + llx)/2;
else
center = min2(urx, llx);
} else {
if (cur_valign == ALIGN_DISTRIB_C)
center = (ury + lly)/2;
else
center = min2(ury, lly);
}
if ( (center < *min) && (t->distrib == 0) ) {
*min = center;
if (dir == 0)
*size = abs(urx - llx);
else
*size = abs(ury - lly);
return True;
} else
return False;
} /* pos_text */
/*
* pos_compound: If the position of the given compound is less
* than passed in and the compound hasn't already been distributed, adjust the
* value of the passed in parameter. Also set the width/height if smaller.
* If dir == 0, handle horizontal, otherwise vertical.
*/
static Boolean
pos_compound (F_compound *c, int *min, int *size, int dir)
{
int center;
compound_bound (c, &llx, &lly, &urx, &ury);
if (dir == 0) {
if (cur_halign == ALIGN_DISTRIB_C)
center = (urx + llx)/2;
else
center = min2(urx, llx);
} else {
if (cur_valign == ALIGN_DISTRIB_C)
center = (ury + lly)/2;
else
center = min2(ury, lly);
}
if ( (center < *min) && (c->distrib == 0) ) {
*min = center;
if (dir == 0)
*size = abs(urx - llx);
else
*size = abs(ury - lly);
return True;
} else
return False;
} /* pos_compound */
#define MIN_MAX_CENTRE(lower,upper,min,max) \
{ \
int centre = (lower + upper)/2; \
if (centre < min) \
min = centre; \
if (centre > max) \
max = centre; \
}
/*
* Determine:
* - the number of objects,
* - the left/top most centre and the right/bottom most centre,
* - mark all objects as not distributed.
*
* dir = 0 for horizontal, 1 for vertical.
*/
static int
init_distrib_centres (int *min, int *max, int dir)
{
F_ellipse *e;
F_arc *a;
F_line *l;
F_spline *s;
F_compound *c;
F_text *t;
int num_objects = 0;
*min = INT_MAX;
*max = INT_MIN;
for (e = cur_c->ellipses; e != NULL; e = e->next) {
num_objects++;
e->distrib = 0;
ellipse_bound (e, &llx, &lly, &urx, &ury);
if (dir == 0)
MIN_MAX_CENTRE(llx, urx, *min, *max)
else
MIN_MAX_CENTRE(lly, ury, *min, *max)
}
for (a = cur_c->arcs; a != NULL; a = a->next) {
num_objects++;
a->distrib = 0;
arc_bound (a, &llx, &lly, &urx, &ury);
if (dir == 0)
MIN_MAX_CENTRE(llx, urx, *min, *max)
else
MIN_MAX_CENTRE(lly, ury, *min, *max)
}
for (l = cur_c->lines; l != NULL; l = l->next) {
num_objects++;
l->distrib = 0;
line_bound (l, &llx, &lly, &urx, &ury);
if (dir == 0)
MIN_MAX_CENTRE(llx, urx, *min, *max)
else
MIN_MAX_CENTRE(lly, ury, *min, *max)
}
for (s = cur_c->splines; s != NULL; s = s->next) {
num_objects++;
s->distrib = 0;
spline_bound (s, &llx, &lly, &urx, &ury);
if (dir == 0)
MIN_MAX_CENTRE(llx, urx, *min, *max)
else
MIN_MAX_CENTRE(lly, ury, *min, *max)
}
for (c = cur_c->compounds; c != NULL; c = c->next) {
num_objects++;
c->distrib = 0;
compound_bound (c, &llx, &lly, &urx, &ury);
if (dir == 0)
MIN_MAX_CENTRE(llx, urx, *min, *max)
else
MIN_MAX_CENTRE(lly, ury, *min, *max)
}
for (t = cur_c->texts; t != NULL; t = t->next) {
int dum;
num_objects++;
t->distrib = 0;
text_bound (t, &llx, &lly, &urx, &ury,
&dum,&dum,&dum,&dum,&dum,&dum,&dum,&dum);
if (dir == 0)
MIN_MAX_CENTRE(llx, urx, *min, *max)
else
MIN_MAX_CENTRE(lly, ury, *min, *max)
}
return (num_objects);
} /* init_distrib_centres */
/*
* Determine:
* - the number of objects,
* - the sum of the widths/heights of all objects,
* - the left/top most left/top object edge,
* - the right/bottom most right/bottom object edge,
* - mark all objects as not distributed.
*
* dir = 0 for horizontal, 1 for vertical.
*/
static int
init_distrib_edges (int *min, int *max, int *sum, int dir)
{
F_ellipse *e;
F_arc *a;
F_line *l;
F_spline *s;
F_compound *c;
F_text *t;
int num_objects = 0;
*min = INT_MAX;
*max = INT_MIN;
*sum = 0;
for (e = cur_c->ellipses; e != NULL; e = e->next) {
num_objects++;
e->distrib = 0;
ellipse_bound (e, &llx, &lly, &urx, &ury);
if (dir == 0) {
*sum += abs(urx - llx);
if (llx < *min) *min = llx;
if (urx > *max) *max = urx;
} else {
*sum += abs(ury - lly);
if (lly < *min) *min = lly;
if (ury > *max) *max = ury;
}
}
for (a = cur_c->arcs; a != NULL; a = a->next) {
num_objects++;
a->distrib = 0;
arc_bound (a, &llx, &lly, &urx, &ury);
if (dir == 0) {
*sum += abs(urx - llx);
if (llx < *min) *min = llx;
if (urx > *max) *max = urx;
} else {
*sum += abs(ury - lly);
if (lly < *min) *min = lly;
if (ury > *max) *max = ury;
}
}
for (l = cur_c->lines; l != NULL; l = l->next) {
num_objects++;
l->distrib = 0;
line_bound (l, &llx, &lly, &urx, &ury);
if (dir == 0) {
*sum += abs(urx - llx);
if (llx < *min) *min = llx;
if (urx > *max) *max = urx;
} else {
*sum += abs(ury - lly);
if (lly < *min) *min = lly;
if (ury > *max) *max = ury;
}
}
for (s = cur_c->splines; s != NULL; s = s->next) {
num_objects++;
s->distrib = 0;
spline_bound (s, &llx, &lly, &urx, &ury);
if (dir == 0) {
*sum += abs(urx - llx);
if (llx < *min) *min = llx;
if (urx > *max) *max = urx;
} else {
*sum += abs(ury - lly);
if (lly < *min) *min = lly;
if (ury > *max) *max = ury;
}
}
for (c = cur_c->compounds; c != NULL; c = c->next) {
num_objects++;
c->distrib = 0;
compound_bound (c, &llx, &lly, &urx, &ury);
if (dir == 0) {
*sum += abs(urx - llx);
if (llx < *min) *min = llx;
if (urx > *max) *max = urx;
} else {
*sum += abs(ury - lly);
if (lly < *min) *min = lly;
if (ury > *max) *max = ury;
}
}
for (t = cur_c->texts; t != NULL; t = t->next) {
int dum;
num_objects++;
t->distrib = 0;
text_bound (t, &llx, &lly, &urx, &ury,
&dum,&dum,&dum,&dum,&dum,&dum,&dum,&dum);
if (dir == 0) {
*sum += abs(urx - llx);
if (llx < *min) *min = llx;
if (urx > *max) *max = urx;
} else {
*sum += abs(ury - lly);
if (lly < *min) *min = lly;
if (ury > *max) *max = ury;
}
}
return (num_objects);
} /* init_distrib_edges */
static void
adjust_object_pos (F_line *obj_ptr, int obj_type, int delta_x, int delta_y)
{
F_ellipse *e;
F_arc *a;
F_line *l;
F_spline *s;
F_compound *c;
F_text *t;
switch (obj_type) {
case O_ELLIPSE:
e = (F_ellipse *) obj_ptr;
translate_ellipse(e, delta_x, delta_y);
e->distrib = 1;
break;
case O_POLYLINE:
l = (F_line *) obj_ptr;
translate_line(l, delta_x, delta_y);
l->distrib = 1;
break;
case O_SPLINE:
s = (F_spline *) obj_ptr;
translate_spline(s, delta_x, delta_y);
s->distrib = 1;
break;
case O_TEXT:
t = (F_text *) obj_ptr;
translate_text(t, delta_x, delta_y);
t->distrib = 1;
break;
case O_ARC:
a = (F_arc *) obj_ptr;
translate_arc(a, delta_x, delta_y);
a->distrib = 1;
break;
case O_COMPOUND:
c = (F_compound *) obj_ptr;
translate_compound(c, delta_x, delta_y);
c->distrib = 1;
break;
default:
break;
}
} /* adjust_object_pos */
static void
distribute_horizontally(void)
{
int num_objects = 0;
F_ellipse *e;
F_arc *a;
F_line *l;
F_spline *s;
F_compound *c;
F_text *t;
float inter_obj_space;
int min_x, max_x;
int obj1, obj2;
int obj_type;
F_line *obj_ptr;
int min_left, min_width;
int req_pos;
int sum_obj_width;
if (cur_halign == ALIGN_DISTRIB_C)
num_objects = init_distrib_centres (&min_x, &max_x, 0);
else {
num_objects = init_distrib_edges (&min_x, &max_x, &sum_obj_width, 0);
req_pos = min_x;
}
if (num_objects <= 1)
return;
/* Determine the amount of space between objects (centres or edges) */
if (cur_halign == ALIGN_DISTRIB_C)
inter_obj_space = (float) (max_x - min_x) / (float)(num_objects - 1);
else if (cur_halign == ALIGN_DISTRIB_E)
inter_obj_space = (float) (max_x - min_x - sum_obj_width) / (float)(num_objects - 1);
else
inter_obj_space = 0.0;
/*
* Go through all of the objects, finding the left most, then the second
* left-most, ...
*/
for (obj1=0; obj1<num_objects; obj1++) {
min_left = INT_MAX;
for (obj2=0; obj2<num_objects; obj2++) {
for (e = cur_c->ellipses; e != NULL; e = e->next)
if (pos_ellipse(e, &min_left, &min_width, 0))
{ obj_ptr = (F_line *) e; obj_type = O_ELLIPSE; }
for (a = cur_c->arcs; a != NULL; a = a->next)
if (pos_arc(a, &min_left, &min_width, 0))
{ obj_ptr = (F_line *) a; obj_type = O_ARC; }
for (l = cur_c->lines; l != NULL; l = l->next)
if (pos_line(l, &min_left, &min_width, 0))
{ obj_ptr = l; obj_type = O_POLYLINE; }
for (s = cur_c->splines; s != NULL; s = s->next)
if (pos_spline(s, &min_left, &min_width, 0))
{ obj_ptr = (F_line *) s; obj_type = O_SPLINE; }
for (c = cur_c->compounds; c != NULL; c = c->next)
if (pos_compound(c, &min_left, &min_width, 0))
{ obj_ptr = (F_line *) c; obj_type = O_COMPOUND; }
for (t = cur_c->texts; t != NULL; t = t->next)
if (pos_text(t, &min_left, &min_width, 0))
{ obj_ptr = (F_line *) t; obj_type = O_TEXT; }
}
/* Determine the new horizontal position of the object */
if (cur_halign == ALIGN_DISTRIB_C)
req_pos = min_x + (int)((float)obj1 * inter_obj_space);
/* Adjust position of left-most undistributed object */
adjust_object_pos (obj_ptr, obj_type, req_pos - min_left, 0);
/* Determine the horizontal position of the next object */
if ( (cur_halign == ALIGN_DISTRIB_E) || (cur_halign == ALIGN_ABUT) )
req_pos += min_width + (int)inter_obj_space;
} /* next object */
} /* distribute_horizontally */
static void
distribute_vertically(void)
{
int num_objects = 0;
F_ellipse *e;
F_arc *a;
F_line *l;
F_spline *s;
F_compound *c;
F_text *t;
float inter_obj_space;
int min_y, max_y;
int obj1, obj2;
int obj_type;
F_line *obj_ptr;
int min_top, min_height;
int req_pos;
int sum_obj_height;
if (cur_valign == ALIGN_DISTRIB_C)
num_objects = init_distrib_centres (&min_y, &max_y, 1);
else {
num_objects = init_distrib_edges (&min_y, &max_y, &sum_obj_height, 1);
req_pos = min_y;
}
if (num_objects <= 1)
return;
/* Determine the amount of space between objects (centres or edges) */
if (cur_valign == ALIGN_DISTRIB_C)
inter_obj_space = (float) (max_y - min_y) / (float)(num_objects - 1);
else if (cur_valign == ALIGN_DISTRIB_E)
inter_obj_space = (float) (max_y - min_y - sum_obj_height) / (float)(num_objects - 1);
else
inter_obj_space = 0.0;
/*
* Go through all of the objects, finding the top-most, then the second
* top-most, ...
*/
for (obj1=0; obj1<num_objects; obj1++) {
min_top = INT_MAX;
for (obj2=0; obj2<num_objects; obj2++) {
for (e = cur_c->ellipses; e != NULL; e = e->next)
if (pos_ellipse(e, &min_top, &min_height, 1))
{ obj_ptr = (F_line *) e; obj_type = O_ELLIPSE; }
for (a = cur_c->arcs; a != NULL; a = a->next)
if (pos_arc(a, &min_top, &min_height, 1))
{ obj_ptr = (F_line *) a; obj_type = O_ARC; }
for (l = cur_c->lines; l != NULL; l = l->next)
if (pos_line(l, &min_top, &min_height, 1))
{ obj_ptr = (F_line *) l; obj_type = O_POLYLINE; }
for (s = cur_c->splines; s != NULL; s = s->next)
if (pos_spline(s, &min_top, &min_height, 1))
{ obj_ptr = (F_line *) s; obj_type = O_SPLINE; }
for (c = cur_c->compounds; c != NULL; c = c->next)
if (pos_compound(c, &min_top, &min_height, 1))
{ obj_ptr = (F_line *) c; obj_type = O_COMPOUND; }
for (t = cur_c->texts; t != NULL; t = t->next)
if (pos_text(t, &min_top, &min_height, 1))
{ obj_ptr = (F_line *) t; obj_type = O_TEXT; }
}
/* Determine the new vertical position of the object */
if (cur_valign == ALIGN_DISTRIB_C)
req_pos = min_y + (int)((float)obj1 * inter_obj_space);
/* Adjust position of left-most undistributed object */
adjust_object_pos (obj_ptr, obj_type, 0, req_pos - min_top);
/* Determine the virtical position of the next object */
if ((cur_valign == ALIGN_DISTRIB_E) || (cur_valign == ALIGN_ABUT) )
req_pos += min_height + (int)inter_obj_space;
}
} /* distribute_vertically */
|
373395.c | /*
% Copyright (C) 2003 - 2019 GraphicsMagick Group
% Copyright (C) 2002 ImageMagick Studio
% Copyright 1991-1999 E. I. du Pont de Nemours and Company
%
% This program is covered by multiple licenses, which are described in
% Copyright.txt. You should have received a copy of Copyright.txt with this
% package; otherwise see http://www.graphicsmagick.org/www/Copyright.html.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% DDDD IIIII SSSSS PPPP L AAA Y Y %
% D D I SS P P L A A Y Y %
% D D I SSS PPPP L AAAAA Y %
% D D I SS P L A A Y %
% DDDD IIIII SSSSS P LLLLL A A Y %
% %
% %
% Methods to Interactively Display and Edit an Image %
% %
% %
% Software Design %
% John Cristy %
% July 1992 %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#if defined(HasX11)
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/color.h"
#include "magick/color_lookup.h"
#include "magick/composite.h"
#include "magick/constitute.h"
#include "magick/decorate.h"
#include "magick/delegate.h"
#include "magick/effect.h"
#include "magick/enhance.h"
#include "magick/fx.h"
#include "magick/log.h"
#include "magick/monitor.h"
#include "magick/montage.h"
#include "magick/paint.h"
#include "magick/pixel_cache.h"
#include "magick/quantize.h"
#include "magick/render.h"
#include "magick/resize.h"
#include "magick/shear.h"
#include "magick/tempfile.h"
#include "magick/transform.h"
#include "magick/utility.h"
#include "magick/version.h"
#include "magick/xwindow.h"
/*
Enumeration declarations.
*/
typedef enum
{
CopyMode,
CropMode,
CutMode
} ClipboardMode;
typedef enum
{
OpenCommand,
NextCommand,
FormerCommand,
SelectCommand,
SaveCommand,
PrintCommand,
DeleteCommand,
NewCommand,
VisualDirectoryCommand,
QuitCommand,
UndoCommand,
RedoCommand,
CutCommand,
CopyCommand,
PasteCommand,
HalfSizeCommand,
OriginalSizeCommand,
DoubleSizeCommand,
ResizeCommand,
ApplyCommand,
RefreshCommand,
RestoreCommand,
CropCommand,
ChopCommand,
FlopCommand,
FlipCommand,
RotateRightCommand,
RotateLeftCommand,
RotateCommand,
ShearCommand,
RollCommand,
TrimCommand,
HueCommand,
SaturationCommand,
BrightnessCommand,
GammaCommand,
SpiffCommand,
DullCommand,
EqualizeCommand,
NormalizeCommand,
NegateCommand,
GrayscaleCommand,
MapCommand,
QuantizeCommand,
DespeckleCommand,
EmbossCommand,
ReduceNoiseCommand,
AddNoiseCommand,
SharpenCommand,
BlurCommand,
ThresholdCommand,
EdgeDetectCommand,
SpreadCommand,
ShadeCommand,
RaiseCommand,
SegmentCommand,
SolarizeCommand,
SwirlCommand,
ImplodeCommand,
WaveCommand,
OilPaintCommand,
CharcoalDrawCommand,
AnnotateCommand,
DrawCommand,
ColorCommand,
MatteCommand,
CompositeCommand,
AddBorderCommand,
AddFrameCommand,
CommentCommand,
LaunchCommand,
RegionofInterestCommand,
ROIHelpCommand,
ROIDismissCommand,
InfoCommand,
ZoomCommand,
ShowPreviewCommand,
ShowHistogramCommand,
ShowMatteCommand,
BackgroundCommand,
SlideShowCommand,
PreferencesCommand,
HelpCommand,
BrowseDocumentationCommand,
VersionCommand,
SaveToUndoBufferCommand,
FreeBuffersCommand,
NullCommand
} CommandType;
typedef enum
{
AnnotateNameCommand,
AnnotateFontColorCommand,
AnnotateBackgroundColorCommand,
AnnotateRotateCommand,
AnnotateHelpCommand,
AnnotateDismissCommand,
TextHelpCommand,
TextApplyCommand,
ChopDirectionCommand,
ChopHelpCommand,
ChopDismissCommand,
HorizontalChopCommand,
VerticalChopCommand,
ColorEditMethodCommand,
ColorEditColorCommand,
ColorEditBorderCommand,
ColorEditFuzzCommand,
ColorEditUndoCommand,
ColorEditHelpCommand,
ColorEditDismissCommand,
CompositeOperatorsCommand,
CompositeDissolveCommand,
CompositeDisplaceCommand,
CompositeHelpCommand,
CompositeDismissCommand,
CropHelpCommand,
CropDismissCommand,
RectifyCopyCommand,
RectifyHelpCommand,
RectifyDismissCommand,
DrawElementCommand,
DrawColorCommand,
DrawStippleCommand,
DrawWidthCommand,
DrawUndoCommand,
DrawHelpCommand,
DrawDismissCommand,
MatteEditMethod,
MatteEditBorderCommand,
MatteEditFuzzCommand,
MatteEditValueCommand,
MatteEditUndoCommand,
MatteEditHelpCommand,
MatteEditDismissCommand,
PasteOperatorsCommand,
PasteHelpCommand,
PasteDismissCommand,
RotateColorCommand,
RotateDirectionCommand,
RotateCropCommand,
RotateSharpenCommand,
RotateHelpCommand,
RotateDismissCommand,
HorizontalRotateCommand,
VerticalRotateCommand,
TileLoadCommand,
TileNextCommand,
TileFormerCommand,
TileDeleteCommand,
TileUpdateCommand
} ModeType;
/*
Function prototypes.
*/
static CommandType
MagickXImageWindowCommand(Display *,MagickXResourceInfo *,MagickXWindows *,const unsigned int,
KeySym,Image **);
static Image
*MagickXMagickCommand(Display *,MagickXResourceInfo *,MagickXWindows *,const CommandType,
Image **),
*MagickXOpenImage(Display *,MagickXResourceInfo *,MagickXWindows *,const unsigned int),
*MagickXTileImage(Display *,MagickXResourceInfo *,MagickXWindows *,Image *,XEvent *),
*MagickXVisualDirectoryImage(Display *,MagickXResourceInfo *,MagickXWindows *);
static unsigned int
MagickXAnnotateEditImage(Display *,MagickXResourceInfo *,MagickXWindows *,Image *),
MagickXDrawEditImage(Display *,MagickXResourceInfo *,MagickXWindows *,Image **),
MagickXChopImage(Display *,MagickXResourceInfo *,MagickXWindows *,Image **),
MagickXCropImage(Display *,MagickXResourceInfo *,MagickXWindows *,Image *,const ClipboardMode),
MagickXBackgroundImage(Display *,MagickXResourceInfo *,MagickXWindows *,Image **),
MagickXColorEditImage(Display *,MagickXResourceInfo *,MagickXWindows *,Image **),
MagickXCompositeImage(Display *,MagickXResourceInfo *,MagickXWindows *,Image *),
MagickXConfigureImage(Display *,MagickXResourceInfo *,MagickXWindows *,Image *),
MagickXMatteEditImage(Display *,MagickXResourceInfo *,MagickXWindows *,Image **),
MagickXPasteImage(Display *,MagickXResourceInfo *,MagickXWindows *,Image *),
MagickXPrintImage(Display *,MagickXResourceInfo *,MagickXWindows *,Image *),
MagickXRotateImage(Display *,MagickXResourceInfo *,MagickXWindows *,double,Image **),
MagickXROIImage(Display *,MagickXResourceInfo *,MagickXWindows *,Image **),
MagickXSaveImage(Display *,MagickXResourceInfo *,MagickXWindows *,Image *),
MagickXTrimImage(Display *,MagickXResourceInfo *,MagickXWindows *,Image *);
static void
MagickXDrawPanRectangle(Display *,MagickXWindows *),
MagickXImageCache(Display *,MagickXResourceInfo *,MagickXWindows *,const CommandType,Image **),
MagickXMagnifyImage(Display *,MagickXWindows *,XEvent *),
MagickXMakePanImage(Display *,MagickXResourceInfo *,MagickXWindows *,Image *),
MagickXPanImage(Display *,MagickXWindows *,XEvent *),
MagickXMagnifyWindowCommand(Display *,MagickXWindows *,const unsigned int,const KeySym),
MagickXSetCropGeometry(Display *,MagickXWindows *,RectangleInfo *,Image *),
MagickXScreenEvent(Display *,MagickXWindows *,XEvent *),
MagickXTranslateImage(Display *,MagickXWindows *,Image *,const KeySym);
/*
Define declarations.
*/
#define MaxColors Min(windows->visual_info->colormap_size,256)
/*
Stipples.
*/
#define BricksWidth 20
#define BricksHeight 20
#define DiagonalWidth 16
#define DiagonalHeight 16
#define HighlightWidth 8
#define HighlightHeight 8
#define ScalesWidth 16
#define ScalesHeight 16
#define ShadowWidth 8
#define ShadowHeight 8
#define VerticalWidth 16
#define VerticalHeight 16
#define WavyWidth 16
#define WavyHeight 16
/*
Constant declarations.
*/
static const unsigned char
BricksBitmap[] =
{
0xff, 0xff, 0x0f, 0x03, 0x0c, 0x00, 0x03, 0x0c, 0x00, 0x03, 0x0c, 0x00,
0x03, 0x0c, 0x00, 0xff, 0xff, 0x0f, 0x60, 0x80, 0x01, 0x60, 0x80, 0x01,
0x60, 0x80, 0x01, 0x60, 0x80, 0x01, 0xff, 0xff, 0x0f, 0x03, 0x0c, 0x00,
0x03, 0x0c, 0x00, 0x03, 0x0c, 0x00, 0x03, 0x0c, 0x00, 0xff, 0xff, 0x0f,
0x60, 0x80, 0x01, 0x60, 0x80, 0x01, 0x60, 0x80, 0x01, 0x60, 0x80, 0x01
},
DiagonalBitmap[] =
{
0x44, 0x44, 0x88, 0x88, 0x11, 0x11, 0x22, 0x22, 0x44, 0x44, 0x88, 0x88,
0x11, 0x11, 0x22, 0x22, 0x44, 0x44, 0x88, 0x88, 0x11, 0x11, 0x22, 0x22,
0x44, 0x44, 0x88, 0x88, 0x11, 0x11, 0x22, 0x22
},
ScalesBitmap[] =
{
0x08, 0x08, 0x08, 0x08, 0x14, 0x14, 0xe3, 0xe3, 0x80, 0x80, 0x80, 0x80,
0x41, 0x41, 0x3e, 0x3e, 0x08, 0x08, 0x08, 0x08, 0x14, 0x14, 0xe3, 0xe3,
0x80, 0x80, 0x80, 0x80, 0x41, 0x41, 0x3e, 0x3e
},
VerticalBitmap[] =
{
0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11
},
WavyBitmap[] =
{
0xfe, 0xff, 0xfe, 0xff, 0xfe, 0xff, 0xfd, 0xff, 0xfd, 0xff, 0xfb, 0xff,
0xe7, 0xff, 0x1f, 0xff, 0xff, 0xf8, 0xff, 0xe7, 0xff, 0xdf, 0xff, 0xbf,
0xff, 0xbf, 0xff, 0x7f, 0xff, 0x7f, 0xff, 0x7f
};
static const int
RoiDelta = 8;
static unsigned const char
HighlightBitmap[8] =
{
0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55
},
ShadowBitmap[8] =
{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
#define PAGE_SIZES \
"Letter", \
"Tabloid", \
"Ledger", \
"Legal", \
"Statement", \
"Executive", \
"A3", \
"A4", \
"A5", \
"B4", \
"B5", \
"Folio", \
"Quarto", \
"10x14", \
(char *) NULL
/*
Help widget declarations.
*/
static const char ImageAnnotateHelp[]=
"In annotate mode, the Command widget has these options:\0"
"\0"
" Font Name\0"
" fixed\0"
" variable\0"
" 5x8\0"
" 6x10\0"
" 7x13bold\0"
" 8x13bold\0"
" 9x15bold\0"
" 10x20\0"
" 12x24\0"
" Browser...\0"
" Font Color\0"
" black\0"
" blue\0"
" cyan\0"
" green\0"
" gray\0"
" red\0"
" magenta\0"
" yellow\0"
" white\0"
" transparent\0"
" Browser...\0"
" Font Color\0"
" black\0"
" blue\0"
" cyan\0"
" green\0"
" gray\0"
" red\0"
" magenta\0"
" yellow\0"
" white\0"
" transparent\0"
" Browser...\0"
" Rotate Text\0"
" -90\0"
" -45\0"
" -30\0"
" 0\0"
" 30\0"
" 45\0"
" 90\0"
" 180\0"
" Dialog...\0"
" Help\0"
" Dismiss\0"
"\0"
"Choose a font name from the Font Name sub-menu. Additional\0"
"font names can be specified with the font browser. You can\0"
"change the menu names by setting the X resources font1\0"
"through font9.\0"
"\0"
"Choose a font color from the Font Color sub-menu.\0"
"Additional font colors can be specified with the color\0"
"browser. You can change the menu colors by setting the X\0"
"resources pen1 through pen9.\0"
"\0"
"If you select the color browser and press Grab, you can\0"
"choose the font color by moving the pointer to the desired\0"
"color on the screen and press any button.\0"
"\0"
"If you choose to rotate the text, choose Rotate Text from the\0"
"menu and select an angle. Typically you will only want to\0"
"rotate one line of text at a time. Depending on the angle you\0"
"choose, subsequent lines may end up overwriting each other.\0"
"\0"
"Choosing a font and its color is optional. The default font\0"
"is fixed and the default color is black. However, you must\0"
"choose a location to begin entering text and press button 1.\0"
"An underscore character will appear at the location of the\0"
"pointer. The cursor changes to a pencil to indicate you are\0"
"in text mode. To exit immediately, press Dismiss.\0"
"\0"
"In text mode, any key presses will display the character at\0"
"the location of the underscore and advance the underscore\0"
"cursor. Enter your text and once completed press Apply to\0"
"finish your image annotation. To correct errors press BACK\0"
"SPACE. To delete an entire line of text, press DELETE. Any\0"
"text that exceeds the boundaries of the image window is\0"
"automatically continued onto the next line.\0"
"\0"
"The actual color you request for the font is saved in the\0"
"image. However, the color that appears in your image window\0"
"may be different. For example, on a monochrome screen the\0"
"text will appear black or white even if you choose the color\0"
"red as the font color. However, the image saved to a file\0"
"with -write is written with red lettering. To assure the\0"
"correct color text in the final image, any PseudoClass image\0"
"is promoted to DirectClass (see miff(5)). To force a\0"
"PseudoClass image to remain PseudoClass, use -colors.",
ImageChopHelp[]=
"In chop mode, the Command widget has these options:\0"
"\0"
" Direction\0"
" horizontal\0"
" vertical\0"
" Help\0"
" Dismiss\0"
"\0"
"If the you choose the horizontal direction (this is the\0"
"default), the area of the image between the two horizontal\0"
"endpoints of the chop line is removed. Otherwise, the area\0"
"of the image between the two vertical endpoints of the chop\0"
"line is removed.\0"
"\0"
"Select a location within the image window to begin your chop,\0"
"press and hold any button. Next, move the pointer to\0"
"another location in the image. As you move a line will\0"
"connect the initial location and the pointer. When you\0"
"release the button, the area within the image to chop is\0"
"determined by which direction you choose from the Command\0"
"widget.\0"
"\0"
"To cancel the image chopping, move the pointer back to the\0"
"starting point of the line and release the button.",
ImageColorEditHelp[]=
"In color edit mode, the Command widget has these options:\0"
"\0"
" Method\0"
" point\0"
" replace\0"
" floodfill\0"
" filltoborder\0"
" reset\0"
" Pixel Color\0"
" black\0"
" blue\0"
" cyan\0"
" green\0"
" gray\0"
" red\0"
" magenta\0"
" yellow\0"
" white\0"
" Browser...\0"
" Border Color\0"
" black\0"
" blue\0"
" cyan\0"
" green\0"
" gray\0"
" red\0"
" magenta\0"
" yellow\0"
" white\0"
" Browser...\0"
" Fuzz\0"
" 0%\0"
" 2%\0"
" 5%\0"
" 10%\0"
" 15%\0"
" Dialog...\0"
" Undo\0"
" Help\0"
" Dismiss\0"
"\0"
"Choose a color editing method from the Method sub-menu\0"
"of the Command widget. The point method recolors any pixel\0"
"selected with the pointer until the button is released. The\0"
"replace method recolors any pixel that matches the color of\0"
"the pixel you select with a button press. Floodfill recolors\0"
"any pixel that matches the color of the pixel you select with\0"
"a button press and is a neighbor. Whereas filltoborder recolors\0"
"any neighbor pixel that is not the border color. Finally reset\0"
"changes the entire image to the designated color.\0"
"\0"
"Next, choose a pixel color from the Pixel Color sub-menu.\0"
"Additional pixel colors can be specified with the color\0"
"browser. You can change the menu colors by setting the X\0"
"resources pen1 through pen9.\0"
"\0"
"Now press button 1 to select a pixel within the image window\0"
"to change its color. Additional pixels may be recolored as\0"
"prescribed by the method you choose.\0"
"\0"
"If the Magnify widget is mapped, it can be helpful in positioning\0"
"your pointer within the image (refer to button 2).\0"
"\0"
"The actual color you request for the pixels is saved in the\0"
"image. However, the color that appears in your image window\0"
"may be different. For example, on a monochrome screen the\0"
"pixel will appear black or white even if you choose the\0"
"color red as the pixel color. However, the image saved to a\0"
"file with -write is written with red pixels. To assure the\0"
"correct color text in the final image, any PseudoClass image\0"
"is promoted to DirectClass (see miff(5)). To force a\0"
"PseudoClass image to remain PseudoClass, use -colors.",
ImageCompositeHelp[]=
"First a widget window is displayed requesting you to enter an\0"
"image name. Press Composite, Grab or type a file name.\0"
"Press Cancel if you choose not to create a composite image.\0"
"When you choose Grab, move the pointer to the desired window\0"
"and press any button.\0"
"\0"
"If the Composite image does not have any matte information,\0"
"you are informed and the file browser is displayed again.\0"
"Enter the name of a mask image. The image is typically\0"
"grayscale and the same size as the composite image. If the\0"
"image is not grayscale, it is converted to grayscale and the\0"
"resulting intensities are used as matte information.\0"
"\0"
"A small window appears showing the location of the cursor in\0"
"the image window. You are now in composite mode. To exit\0"
"immediately, press Dismiss. In composite mode, the Command\0"
"widget has these options:\0"
"\0"
" Operators\0"
" Over\0"
" In\0"
" Out\0"
" Atop\0"
" Xor\0"
" Plus\0"
" Minus\0"
" Add\0"
" Subtract\0"
" Difference\0"
" Multiply\0"
" Bumpmap\0"
" Copy\0"
" CopyRed\0"
" CopyGreen\0"
" CopyBlue\0"
" CopyOpacity\0"
" Clear\0"
" Dissolve\0"
" Displace\0"
" Help\0"
" Dismiss\0"
"\0"
"Choose a composite operation from the Operators sub-menu of\0"
"the Command widget. How each operator behaves is described\0"
"below. Image window is the image currently displayed on\0"
"your X server and image is the image obtained with the File\0"
"Browser widget.\0"
"\0"
"Over The result is the union of the two image shapes,\0"
" with image obscuring image window in the region of\0"
" overlap.\0"
"\0"
"In The result is simply image cut by the shape of\0"
" image window. None of the image data of image\0"
" window is in the result.\0"
"\0"
"Out The resulting image is image with the shape of\0"
" image window cut out.\0"
"\0"
"Atop The result is the same shape as image image window,\0"
" with image obscuring image window where the image\0"
" shapes overlap. Note this differs from over\0"
" because the portion of image outside image window's\0"
" shape does not appear in the result.\0"
"\0"
"Xor The result is the image data from both image and\0"
" image window that is outside the overlap region.\0"
" The overlap region is blank.\0"
"\0"
"Plus The result is just the sum of the image data.\0"
" Output values are cropped to 255 (no overflow).\0"
" This operation is independent of the matte\0"
" channels.\0"
"\0"
"Minus The result of image - image window, with underflow\0"
" cropped to zero. The matte channel is ignored (set\0"
" to 255, full coverage).\0"
"\0"
"Add The result of image + image window, with overflow\0"
" wrapping around (mod 256).\0"
"\0"
"Subtract The result of image - image window, with underflow\0"
" wrapping around (mod 256). The add and subtract\0"
" operators can be used to perform reversible\0"
" transformations.\0"
"\0"
"Difference\0"
" The result of abs(image - image window). This is\0"
" useful for comparing two very similar images.\0"
"\0"
"Multiply\0"
" The result of image * image window. This is\0"
" useful for the creation of drop-shadows.\0"
"\0"
"Bumpmap The result of surface normals from image * image\0"
" window.\0"
"\0"
"Copy The resulting image is image window replaced with\0"
" image. Here the matte information is ignored.\0"
"\0"
"CopyRed The red layer of the image window is replace with\0"
" the red layer of the image. The other layers are\0"
" untouched.\0"
"\0"
"CopyGreen\0"
" The green layer of the image window is replace with\0"
" the green layer of the image. The other layers are\0"
" untouched.\0"
"\0"
"CopyBlue The blue layer of the image window is replace with\0"
" the blue layer of the image. The other layers are\0"
" untouched.\0"
"\0"
"CopyOpacity\0"
" The matte layer of the image window is replace with\0"
" the matte layer of the image. The other layers are\0"
" untouched.\0"
"\0"
"The image compositor requires a matte, or alpha channel in\0"
"the image for some operations. This extra channel usually\0"
"defines a mask which represents a sort of a cookie-cutter\0"
"for the image. This is the case when matte is 255 (full\0"
"coverage) for pixels inside the shape, zero outside, and\0"
"between zero and 255 on the boundary. If image does not\0"
"have a matte channel, it is initialized with 0 for any pixel\0"
"matching in color to pixel location (0,0), otherwise 255.\0"
"\0"
"If you choose Dissolve, the composite operator becomes Over. The\0"
"image matte channel percent transparency is initialized to factor.\0"
"The image window is initialized to (100-factor). Where factor is the\0"
"value you specify in the Dialog widget.\0"
"\0"
"Displace shifts the image pixels as defined by a displacement\0"
"map. With this option, image is used as a displacement map.\0"
"Black, within the displacement map, is a maximum positive\0"
"displacement. White is a maximum negative displacement and\0"
"middle gray is neutral. The displacement is scaled to determine\0"
"the pixel shift. By default, the displacement applies in both the\0"
"horizontal and vertical directions. However, if you specify a mask,\0"
"image is the horizontal X displacement and mask the vertical Y\0"
"displacement.\0"
"\0"
"Note that matte information for image window is not retained\0"
"for colormapped X server visuals (e.g. StaticColor,\0"
"StaticColor, GrayScale, PseudoColor). Correct compositing\0"
"behavior may require a TrueColor or DirectColor visual or a\0"
"Standard Colormap.\0"
"\0"
"Choosing a composite operator is optional. The default\0"
"operator is replace. However, you must choose a location to\0"
"composite your image and press button 1. Press and hold the\0"
"button before releasing and an outline of the image will\0"
"appear to help you identify your location.\0"
"\0"
"The actual colors of the composite image is saved. However,\0"
"the color that appears in image window may be different.\0"
"For example, on a monochrome screen image window will appear\0"
"black or white even though your composited image may have\0"
"many colors. If the image is saved to a file it is written\0"
"with the correct colors. To assure the correct colors are\0"
"saved in the final image, any PseudoClass image is promoted\0"
"to DirectClass (see miff(5)). To force a PseudoClass image\0"
"to remain PseudoClass, use -colors.",
ImageCutHelp[]=
"In cut mode, the Command widget has these options:\0"
"\0"
" Help\0"
" Dismiss\0"
"\0"
"To define a cut region, press button 1 and drag. The\0"
"cut region is defined by a highlighted rectangle that\0"
"expands or contracts as it follows the pointer. Once you\0"
"are satisfied with the cut region, release the button.\0"
"You are now in rectify mode. In rectify mode, the Command\0"
"widget has these options:\0"
"\0"
" Cut\0"
" Help\0"
" Dismiss\0"
"\0"
"You can make adjustments by moving the pointer to one of the\0"
"cut rectangle corners, pressing a button, and dragging.\0"
"Finally, press Cut to commit your copy region. To\0"
"exit without cutting the image, press Dismiss.",
ImageCopyHelp[]=
"In copy mode, the Command widget has these options:\0"
"\0"
" Help\0"
" Dismiss\0"
"\0"
"To define a copy region, press button 1 and drag. The\0"
"copy region is defined by a highlighted rectangle that\0"
"expands or contracts as it follows the pointer. Once you\0"
"are satisfied with the copy region, release the button.\0"
"You are now in rectify mode. In rectify mode, the Command\0"
"widget has these options:\0"
"\0"
" Copy\0"
" Help\0"
" Dismiss\0"
"\0"
"You can make adjustments by moving the pointer to one of the\0"
"copy rectangle corners, pressing a button, and dragging.\0"
"Finally, press Copy to commit your copy region. To\0"
"exit without copying the image, press Dismiss.",
ImageCropHelp[]=
"In crop mode, the Command widget has these options:\0"
"\0"
" Help\0"
" Dismiss\0"
"\0"
"To define a cropping region, press button 1 and drag. The\0"
"cropping region is defined by a highlighted rectangle that\0"
"expands or contracts as it follows the pointer. Once you\0"
"are satisfied with the cropping region, release the button.\0"
"You are now in rectify mode. In rectify mode, the Command\0"
"widget has these options:\0"
"\0"
" Crop\0"
" Help\0"
" Dismiss\0"
"\0"
"You can make adjustments by moving the pointer to one of the\0"
"cropping rectangle corners, pressing a button, and dragging.\0"
"Finally, press Crop to commit your cropping region. To\0"
"exit without cropping the image, press Dismiss.",
ImageDrawHelp[]=
"The cursor changes to a crosshair to indicate you are in\0"
"draw mode. To exit immediately, press Dismiss. In draw mode,\0"
"the Command widget has these options:\0"
"\0"
" Element\0"
" point\0"
" line\0"
" rectangle\0"
" fill rectangle\0"
" circle\0"
" fill circle\0"
" ellipse\0"
" fill ellipse\0"
" polygon\0"
" fill polygon\0"
" Color\0"
" black\0"
" blue\0"
" cyan\0"
" green\0"
" gray\0"
" red\0"
" magenta\0"
" yellow\0"
" white\0"
" transparent\0"
" Browser...\0"
" Stipple\0"
" Brick\0"
" Diagonal\0"
" Scales\0"
" Vertical\0"
" Wavy\0"
" Translucent\0"
" Opaque\0"
" Open...\0"
" Width\0"
" 1\0"
" 2\0"
" 4\0"
" 8\0"
" 16\0"
" Dialog...\0"
" Undo\0"
" Help\0"
" Dismiss\0"
"\0"
"Choose a drawing primitive from the Element sub-menu.\0"
"\0"
"Choose a color from the Color sub-menu. Additional\0"
"colors can be specified with the color browser.\0"
"\0"
"If you choose the color browser and press Grab, you can\0"
"select the color by moving the pointer to the desired\0"
"color on the screen and press any button. The transparent\0"
"color updates the image matte channel and is useful for\0"
"image compositing.\0"
"\0"
"Choose a stipple, if appropriate, from the Stipple sub-menu.\0"
"Additional stipples can be specified with the file browser.\0"
"Stipples obtained from the file browser must be on disk in the\0"
"X11 bitmap format.\0"
"\0"
"Choose a width, if appropriate, from the Width sub-menu. To\0"
"choose a specific width select the Dialog widget.\0"
"\0"
"Choose a point in the Image window and press button 1 and\0"
"hold. Next, move the pointer to another location in the\0"
"image. As you move, a line connects the initial location and\0"
"the pointer. When you release the button, the image is\0"
"updated with the primitive you just drew. For polygons, the\0"
"image is updated when you press and release the button without\0"
"moving the pointer.\0"
"\0"
"To cancel image drawing, move the pointer back to the\0"
"starting point of the line and release the button.",
DisplayHelp[]=
"BUTTONS\0"
" The effects of each button press is described below. Three\0"
" buttons are required. If you have a two button mouse,\0"
" button 1 and 3 are returned. Press ALT and button 3 to\0"
" simulate button 2.\0"
"\0"
" 1 Press this button to map or unmap the Command widget.\0"
"\0"
" 2 Press and drag to define a region of the image to\0"
" magnify.\0"
"\0"
" 3 Press and drag to choose from a select set of commands.\0"
" This button behaves differently if the image being\0"
" displayed is a visual image directory. Here, choose a\0"
" particular tile of the directory and press this button and\0"
" drag to select a command from a pop-up menu. Choose from\0"
" these menu items:\0"
"\0"
" Open\0"
" Next\0"
" Former\0"
" Delete\0"
" Update\0"
"\0"
" If you choose Open, the image represented by the tile is\0"
" displayed. To return to the visual image directory, choose\0"
" Next from the Command widget. Next and Former moves to the\0"
" next or former image respectively. Choose Delete to delete\0"
" a particular image tile. Finally, choose Update to\0"
" synchronize all the image tiles with their respective\0"
" images.\0"
"\0"
"COMMAND WIDGET\0"
" The Command widget lists a number of sub-menus and commands.\0"
" They are\0"
"\0"
" File\0"
" Open...\0"
" Next\0"
" Former\0"
" Select...\0"
" Save...\0"
" Print...\0"
" Delete...\0"
" New...\0"
" Visual Directory...\0"
" Quit\0"
" Edit\0"
" Undo\0"
" Redo\0"
" Cut\0"
" Copy\0"
" Paste\0"
" View\0"
" Half Size\0"
" Original Size\0"
" Double Size\0"
" Resize...\0"
" Apply\0"
" Refresh\0"
" Restore\0"
" Transform\0"
" Crop\0"
" Chop\0"
" Flop\0"
" Flip\0"
" Rotate Right\0"
" Rotate Left\0"
" Rotate...\0"
" Shear...\0"
" Roll...\0"
" Trim Edges\0"
" Enhance\0"
" Brightness...\0"
" Saturation...\0"
" Hue...\0"
" Gamma...\0"
" Sharpen...\0"
" Dull\0"
" Equalize\0"
" Normalize\0"
" Negate\0"
" Grayscale\0"
" Map...\0"
" Quantize...\0"
" Effects\0"
" Despeckle\0"
" Emboss\0"
" Reduce Noise\0"
" Add Noise\0"
" Sharpen...\0"
" Blur...\0"
" Threshold...\0"
" Edge Detect...\0"
" Spread...\0"
" Shade...\0"
" Painting...\0"
" Segment...\0"
" F/X\0"
" Solarize...\0"
" Swirl...\0"
" Implode...\0"
" Wave...\0"
" Oil Painting...\0"
" Charcoal Drawing...\0"
" Image Edit\0"
" Annotate...\0"
" Draw...\0"
" Color...\0"
" Matte...\0"
" Composite...\0"
" Add Border...\0"
" Add Frame...\0"
" Comment...\0"
" Launch...\0"
" Region of Interest...\0"
" Miscellany\0"
" Image Info\0"
" Zoom Image\0"
" Show Preview...\0"
" Show Histogram\0"
" Show Matte\0"
" Background...\0"
" Slide Show\0"
" Preferences...\0"
" Help\0"
" Overview\0"
" Browse Documentation\0"
" About Display\0"
"\0"
" Menu items with a indented triangle have a sub-menu. They\0"
" are represented above as the indented items. To access a\0"
" sub-menu item, move the pointer to the appropriate menu and\0"
" press a button and drag. When you find the desired sub-menu\0"
" item, release the button and the command is executed. Move\0"
" the pointer away from the sub-menu if you decide not to\0"
" execute a particular command.\0"
"\0"
"KEYBOARD ACCELERATORS\0"
" Accelerators are one or two key presses that effect a\0"
" particular command. The keyboard accelerators that\0"
" display(1) understands is:\0"
"\0"
" Ctl+O Press to open an image from a file.\0"
"\0"
" space Press to display the next image.\0"
"\0"
" If the image is a multi-paged document such as a Postscript\0"
" document, you can skip ahead several pages by preceeding\0"
" this command with a number. For example to display the\0"
" fourth page beyond the current page, press 4n.\0"
"\0"
" backspace Press to display the former image.\0"
"\0"
" If the image is a multi-paged document such as a Postscript\0"
" document, you can skip behind several pages by preceeding\0"
" this command with a number. For example to display the\0"
" fourth page preceeding the current page, press 4space.\0"
"\0"
" Ctl+S Press to write the image to a file.\0"
"\0"
" Ctl+P Press to print the image to a Postscript printer.\0"
"\0"
" Ctl+D Press to delete an image file.\0"
"\0"
" Ctl+N Press to create a blank canvas.\0"
"\0"
" Ctl+Q Press to discard all images and exit program.\0"
"\0"
" Ctl+Z Press to undo last image transformation.\0"
"\0"
" Ctl+R Press to redo last image transformation.\0"
"\0"
" Ctl+X Press to cut a region of the image.\0"
"\0"
" Ctl+C Press to copy a region of the image.\0"
"\0"
" Ctl+V Press to paste a region to the image.\0"
"\0"
" < Press to half the image size.\0"
"\0"
" - Press to return to the original image size.\0"
"\0"
" > Press to double the image size.\0"
"\0"
" % Press to resize the image to a width and height you\0"
" specify.\0"
"\0"
"Cmd-A Press to make any image transformations permanent."
"\0"
" By default, any image size transformations are applied\0"
" to the original image to create the image displayed on\0"
" the X server. However, the transformations are not\0"
" permanent (i.e. the original image does not change\0"
" size only the X image does). For example, if you\0"
" press > the X image will appear to double in size,\0"
" but the original image will in fact remain the same size.\0"
" To force the original image to double in size, press >\0"
" followed by Cmd-A.\0"
"\0"
" @ Press to refresh the image window.\0"
"\0"
" C Press to crop the image.\0"
"\0"
" [ Press to chop the image.\0"
"\0"
" H Press to flop image in the horizontal direction.\0"
"\0"
" V Press to flip image in the vertical direction.\0"
"\0"
" / Press to rotate the image 90 degrees clockwise.\0"
"\0"
" \\ Press to rotate the image 90 degrees counter-clockwise.\0"
"\0"
" * Press to rotate the image the number of degrees you\0"
" specify.\0"
"\0"
" S Press to shear the image the number of degrees you\0"
" specify.\0"
"\0"
" R Press to roll the image.\0"
"\0"
" T Press to trim the image edges.\0"
"\0"
" Shft-H Press to vary the image hue.\0"
"\0"
" Shft-S Press to vary the color saturation.\0"
"\0"
" Shft-L Press to vary the color brightness.\0"
"\0"
" Shft-G Press to gamma correct the image.\0"
"\0"
" Shft-C Press to sharpen the image contrast.\0"
"\0"
" Shft-Z Press to dull the image contrast.\0"
"\0"
" = Press to perform histogram equalization on the image.\0"
"\0"
" Shft-N Press to perform histogram normalization on the image.\0"
"\0"
" Shft-~ Press to negate the colors of the image.\0"
"\0"
" . Press to convert the image colors to gray.\0"
"\0"
" Shft-# Press to set the maximum number of unique colors in the\0"
" image.\0"
"\0"
" F2 Press to reduce the speckles in an image.\0"
"\0"
" F3 Press to eliminate peak noise from an image.\0"
"\0"
" F4 Press to add noise to an image.\0"
"\0"
" F5 Press to sharpen an image.\0"
"\0"
" F6 Press to delete an image file.\0"
"\0"
" F7 Press to threshold the image.\0"
"\0"
" F8 Press to detect edges within an image.\0"
"\0"
" F9 Press to emboss an image.\0"
"\0"
" F10 Press to displace pixels by a random amount.\0"
"\0"
" F11 Press to negate all pixels above the threshold level.\0"
"\0"
" F12 Press to shade the image using a distant light source.\0"
"\0"
" F13 Press to lighten or darken image edges to create a 3-D effect.\0"
"\0"
" F14 Press to segment the image by color.\0"
"\0"
" Meta-S Press to swirl image pixels about the center.\0"
"\0"
" Meta-I Press to implode image pixels about the center.\0"
"\0"
" Meta-W Press to alter an image along a sine wave.\0"
"\0"
" Meta-P Press to simulate an oil painting.\0"
"\0"
" Meta-C Press to simulate a charcoal drawing.\0"
"\0"
" Alt-A Press to annotate the image with text.\0"
"\0"
" Alt-D Press to draw on an image.\0"
"\0"
" Alt-P Press to edit an image pixel color.\0"
"\0"
" Alt-M Press to edit the image matte information.\0"
"\0"
" Alt-V Press to composite the image with another.\0"
"\0"
" Alt-B Press to add a border to the image.\0"
"\0"
" Alt-F Press to add an ornamental border to the image.\0"
"\0"
" Alt-Shft-!\0"
" Press to add an image comment.\0"
"\0"
" Ctl-A Press to apply image processing techniques to a region\0"
" of interest.\0"
"\0"
" Shft-? Press to display information about the image.\0"
"\0"
" Shft-+ Press to map the zoom image window.\0"
"\0"
" Shft-P Press to preview an image enhancement, effect, or f/x.\0"
"\0"
" F1 Press to display helpful information about display(1).\0"
"\0"
" Find Press to browse documentation about ImageMagick.\0"
"\0"
" 1-9 Press to change the level of magnification.\0"
"\0"
" Use the arrow keys to move the image one pixel up, down,\0"
" left, or right within the magnify window. Be sure to first\0"
" map the magnify window by pressing button 2.\0"
"\0"
" Press ALT and one of the arrow keys to trim off one pixel\0"
" from any side of the image.",
ImageMatteEditHelp[]=
"Matte information within an image is useful for some\0"
"operations such as image compositing (See IMAGE\0"
"COMPOSITING). This extra channel usually defines a mask\0"
"which represents a sort of a cookie-cutter for the image.\0"
"This is the case when matte is 255 (full coverage) for\0"
"pixels inside the shape, zero outside, and between zero and\0"
"255 on the boundary.\0"
"\0"
"A small window appears showing the location of the cursor in\0"
"the image window. You are now in matte edit mode. To exit\0"
"immediately, press Dismiss. In matte edit mode, the Command\0"
"widget has these options:\0"
"\0"
" Method\0"
" point\0"
" replace\0"
" floodfill\0"
" filltoborder\0"
" reset\0"
" Border Color\0"
" black\0"
" blue\0"
" cyan\0"
" green\0"
" gray\0"
" red\0"
" magenta\0"
" yellow\0"
" white\0"
" Browser...\0"
" Fuzz\0"
" 0%\0"
" 2%\0"
" 5%\0"
" 10%\0"
" 15%\0"
" Dialog...\0"
" Matte\0"
" Opaque\0"
" Transparent\0"
" Dialog...\0"
" Undo\0"
" Help\0"
" Dismiss\0"
"\0"
"Choose a matte editing method from the Method sub-menu of\0"
"the Command widget. The point method changes the matte value\0"
"of any pixel selected with the pointer until the button is\0"
"is released. The replace method changes the matte value of\0"
"any pixel that matches the color of the pixel you select with\0"
"a button press. Floodfill changes the matte value of any pixel\0"
"that matches the color of the pixel you select with a button\0"
"press and is a neighbor. Whereas filltoborder changes the matte\0"
"value any neighbor pixel that is not the border color. Finally\0"
"reset changes the entire image to the designated matte value.\0"
"\0"
"Choose Matte Value and pick Opaque or Transarent. For other values\0"
"select the Dialog entry. Here a dialog appears requesting a matte\0"
"value. The value you select is assigned as the opacity value of the\0"
"selected pixel or pixels.\0"
"\0"
"Now, press any button to select a pixel within the image\0"
"window to change its matte value.\0"
"\0"
"If the Magnify widget is mapped, it can be helpful in positioning\0"
"your pointer within the image (refer to button 2).\0"
"\0"
"Matte information is only valid in a DirectClass image.\0"
"Therefore, any PseudoClass image is promoted to DirectClass\0"
"(see miff(5)). Note that matte information for PseudoClass\0"
"is not retained for colormapped X server visuals (e.g.\0"
"StaticColor, StaticColor, GrayScale, PseudoColor) unless you\0"
"immediately save your image to a file (refer to Write).\0"
"Correct matte editing behavior may require a TrueColor or\0"
"DirectColor visual or a Standard Colormap.",
ImagePanHelp[]=
"When an image exceeds the width or height of the X server\0"
"screen, display maps a small panning icon. The rectangle\0"
"within the panning icon shows the area that is currently\0"
"displayed in the the image window. To pan about the image,\0"
"press any button and drag the pointer within the panning\0"
"icon. The pan rectangle moves with the pointer and the\0"
"image window is updated to reflect the location of the\0"
"rectangle within the panning icon. When you have selected\0"
"the area of the image you wish to view, release the button.\0"
"\0"
"Use the arrow keys to pan the image one pixel up, down,\0"
"left, or right within the image window.\0"
"\0"
"The panning icon is withdrawn if the image becomes smaller\0"
"than the dimensions of the X server screen.",
ImagePasteHelp[]=
"A small window appears showing the location of the cursor in\0"
"the image window. You are now in paste mode. To exit\0"
"immediately, press Dismiss. In paste mode, the Command\0"
"widget has these options:\0"
"\0"
" Operators\0"
" over\0"
" in\0"
" out\0"
" atop\0"
" xor\0"
" plus\0"
" minus\0"
" add\0"
" subtract\0"
" difference\0"
" replace\0"
" Help\0"
" Dismiss\0"
"\0"
"Choose a composite operation from the Operators sub-menu of\0"
"the Command widget. How each operator behaves is described\0"
"below. Image window is the image currently displayed on\0"
"your X server and image is the image obtained with the File\0"
"Browser widget.\0"
"\0"
"Over The result is the union of the two image shapes,\0"
" with image obscuring image window in the region of\0"
" overlap.\0"
"\0"
"In The result is simply image cut by the shape of\0"
" image window. None of the image data of image\0"
" window is in the result.\0"
"\0"
"Out The resulting image is image with the shape of\0"
" image window cut out.\0"
"\0"
"Atop The result is the same shape as image image window,\0"
" with image obscuring image window where the image\0"
" shapes overlap. Note this differs from over\0"
" because the portion of image outside image window's\0"
" shape does not appear in the result.\0"
"\0"
"Xor The result is the image data from both image and\0"
" image window that is outside the overlap region.\0"
" The overlap region is blank.\0"
"\0"
"Plus The result is just the sum of the image data.\0"
" Output values are cropped to 255 (no overflow).\0"
" This operation is independent of the matte\0"
" channels.\0"
"\0"
"Minus The result of image - image window, with underflow\0"
" cropped to zero. The matte channel is ignored (set\0"
" to 255, full coverage).\0"
"\0"
"Add The result of image + image window, with overflow\0"
" wrapping around (mod 256).\0"
"\0"
"Subtract The result of image - image window, with underflow\0"
" wrapping around (mod 256). The add and subtract\0"
" operators can be used to perform reversible\0"
" transformations.\0"
"\0"
"Difference\0"
" The result of abs(image - image window). This is\0"
" useful for comparing two very similar images.\0"
"\0"
"Copy The resulting image is image window replaced with\0"
" image. Here the matte information is ignored.\0"
"\0"
"CopyRed The red layer of the image window is replace with\0"
" the red layer of the image. The other layers are\0"
" untouched.\0"
"\0"
"CopyGreen\0"
" The green layer of the image window is replace with\0"
" the green layer of the image. The other layers are\0"
" untouched.\0"
"\0"
"CopyBlue The blue layer of the image window is replace with\0"
" the blue layer of the image. The other layers are\0"
" untouched.\0"
"\0"
"CopyOpacity\0"
" The matte layer of the image window is replace with\0"
" the matte layer of the image. The other layers are\0"
" untouched.\0"
"\0"
"The image compositor requires a matte, or alpha channel in\0"
"the image for some operations. This extra channel usually\0"
"defines a mask which represents a sort of a cookie-cutter\0"
"for the image. This is the case when matte is 255 (full\0"
"coverage) for pixels inside the shape, zero outside, and\0"
"between zero and 255 on the boundary. If image does not\0"
"have a matte channel, it is initialized with 0 for any pixel\0"
"matching in color to pixel location (0,0), otherwise 255.\0"
"\0"
"Note that matte information for image window is not retained\0"
"for colormapped X server visuals (e.g. StaticColor,\0"
"StaticColor, GrayScale, PseudoColor). Correct compositing\0"
"behavior may require a TrueColor or DirectColor visual or a\0"
"Standard Colormap.\0"
"\0"
"Choosing a composite operator is optional. The default\0"
"operator is replace. However, you must choose a location to\0"
"paste your image and press button 1. Press and hold the\0"
"button before releasing and an outline of the image will\0"
"appear to help you identify your location.\0"
"\0"
"The actual colors of the pasted image is saved. However,\0"
"the color that appears in image window may be different.\0"
"For example, on a monochrome screen image window will appear\0"
"black or white even though your pasted image may have\0"
"many colors. If the image is saved to a file it is written\0"
"with the correct colors. To assure the correct colors are\0"
"saved in the final image, any PseudoClass image is promoted\0"
"to DirectClass (see miff(5)). To force a PseudoClass image\0"
"to remain PseudoClass, use -colors.",
ImageROIHelp[]=
"In region of interest mode, the Command widget has these\0"
"options:\0"
"\0"
" Help\0"
" Dismiss\0"
"\0"
"To define a region of interest, press button 1 and drag.\0"
"The region of interest is defined by a highlighted rectangle\0"
"that expands or contracts as it follows the pointer. Once\0"
"you are satisfied with the region of interest, release the\0"
"button. You are now in apply mode. In apply mode the\0"
"Command widget has these options:\0"
"\0"
" File\0"
" Save...\0"
" Print...\0"
" Edit\0"
" Undo\0"
" Redo\0"
" Transform\0"
" Flop\0"
" Flip\0"
" Rotate Right\0"
" Rotate Left\0"
" Enhance\0"
" Hue...\0"
" Saturation...\0"
" Brightness...\0"
" Gamma...\0"
" Spiff\0"
" Dull\0"
" Equalize\0"
" Normalize\0"
" Negate\0"
" Grayscale\0"
" Map...\0"
" Quantize...\0"
" Effects\0"
" Despeckle\0"
" Emboss\0"
" Reduce Noise\0"
" Sharpen...\0"
" Blur...\0"
" Threshold...\0"
" Edge Detect...\0"
" Spread...\0"
" Shade...\0"
" Raise...\0"
" Segment...\0"
" F/X\0"
" Solarize...\0"
" Swirl...\0"
" Implode...\0"
" Wave...\0"
" Oil Painting...\0"
" Charcoal Drawing...\0"
" Miscellany\0"
" Image Info\0"
" Zoom Image\0"
" Show Preview...\0"
" Show Histogram\0"
" Show Matte\0"
" Help\0"
" Dismiss\0"
"\0"
"You can make adjustments to the region of interest by moving\0"
"the pointer to one of the rectangle corners, pressing a\0"
"button, and dragging. Finally, choose an image processing\0"
"technique from the Command widget. You can choose more than\0"
"one image processing technique to apply to an area.\0"
"Alternatively, you can move the region of interest before\0"
"applying another image processing technique. To exit, press\0"
"Dismiss.",
ImageRotateHelp[]=
"In rotate mode, the Command widget has these options:\0"
"\0"
" Pixel Color\0"
" black\0"
" blue\0"
" cyan\0"
" green\0"
" gray\0"
" red\0"
" magenta\0"
" yellow\0"
" white\0"
" Browser...\0"
" Direction\0"
" horizontal\0"
" vertical\0"
" Help\0"
" Dismiss\0"
"\0"
"Choose a background color from the Pixel Color sub-menu.\0"
"Additional background colors can be specified with the color\0"
"browser. You can change the menu colors by setting the X\0"
"resources pen1 through pen9.\0"
"\0"
"If you choose the color browser and press Grab, you can\0"
"select the background color by moving the pointer to the\0"
"desired color on the screen and press any button.\0"
"\0"
"Choose a point in the image window and press this button and\0"
"hold. Next, move the pointer to another location in the\0"
"image. As you move a line connects the initial location and\0"
"the pointer. When you release the button, the degree of\0"
"image rotation is determined by the slope of the line you\0"
"just drew. The slope is relative to the direction you\0"
"choose from the Direction sub-menu of the Command widget.\0"
"\0"
"To cancel the image rotation, move the pointer back to the\0"
"starting point of the line and release the button.";
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X A n n o t a t e E d i t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXAnnotateEditImage annotates the image with text.
%
% The format of the MagickXAnnotateEditImage method is:
%
% unsigned int MagickXAnnotateEditImage(Display *display,
% MagickXResourceInfo *resource_info,MagickXWindows *windows,Image *image)
%
% A description of each parameter follows:
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o resource_info: Specifies a pointer to a X11 MagickXResourceInfo structure.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
% o image: Specifies a pointer to an Image structure; returned from
% ReadImage.
%
*/
static unsigned int MagickXAnnotateEditImage(Display *display,
MagickXResourceInfo *resource_info,MagickXWindows *windows,Image *image)
{
const char
* const AnnotateMenu[]=
{
"Font Name",
"Font Color",
"Box Color",
"Rotate Text",
"Help",
"Dismiss",
(char *) NULL
},
* const TextMenu[]=
{
"Help",
"Apply",
(char *) NULL
};
static double
degrees = 0.0;
static const ModeType
AnnotateCommands[]=
{
AnnotateNameCommand,
AnnotateFontColorCommand,
AnnotateBackgroundColorCommand,
AnnotateRotateCommand,
AnnotateHelpCommand,
AnnotateDismissCommand
},
TextCommands[]=
{
TextHelpCommand,
TextApplyCommand
};
static unsigned int
box_id = MaxNumberPens-2,
font_id = 0,
pen_id = 0,
transparent_box = True,
transparent_pen = False;
char
*ColorMenu[MaxNumberPens+1],
command[MaxTextExtent],
text[MaxTextExtent];
Cursor
cursor;
GC
annotate_context;
int
id,
pen_number,
x,
y;
KeySym
key_symbol;
register char
*p;
register long
i;
unsigned int
height,
status,
width;
unsigned long
state;
MagickXAnnotateInfo
*annotate_info,
*previous_info;
XColor
color;
XFontStruct
*font_info;
XEvent
event,
text_event;
/*
Map Command widget.
*/
(void) CloneString(&windows->command.name,"Annotate");
windows->command.data=4;
(void) MagickXCommandWidget(display,windows,AnnotateMenu,(XEvent *) NULL);
(void) XMapRaised(display,windows->command.id);
MagickXClientMessage(display,windows->image.id,windows->im_protocols,
windows->im_update_widget,CurrentTime);
/*
Track pointer until button 1 is pressed.
*/
MagickXQueryPosition(display,windows->image.id,&x,&y);
(void) XSelectInput(display,windows->image.id,
windows->image.attributes.event_mask | PointerMotionMask);
cursor=XCreateFontCursor(display,XC_left_side);
(void) XDefineCursor(display,windows->image.id,cursor);
state=DefaultState;
do
{
if (windows->info.mapped)
{
/*
Display pointer position.
*/
FormatString(text," %+d%+d ",x+windows->image.x,y+windows->image.y);
MagickXInfoWidget(display,windows,text);
}
/*
Wait for next event.
*/
MagickXScreenEvent(display,windows,&event);
if (event.xany.window == windows->command.id)
{
/*
Select a command from the Command widget.
*/
id=MagickXCommandWidget(display,windows,AnnotateMenu,&event);
(void) XDefineCursor(display,windows->image.id,cursor);
if (id < 0)
continue;
switch (AnnotateCommands[id])
{
case AnnotateNameCommand:
{
char
*FontMenu[MaxNumberFonts];
int
font_number;
/*
Initialize menu selections.
*/
for (i=0; i < MaxNumberFonts; i++)
FontMenu[i]=resource_info->font_name[i];
FontMenu[MaxNumberFonts-2]=(char *) "Browser...";
FontMenu[MaxNumberFonts-1]=(char *) NULL;
/*
Select a font name from the pop-up menu.
*/
font_number=MagickXMenuWidget(display,windows,AnnotateMenu[id],
(const char **) FontMenu,command);
if (font_number < 0)
break;
if (font_number == (MaxNumberFonts-2))
{
static char
font_name[MaxTextExtent] = "fixed";
/*
Select a font name from a browser.
*/
resource_info->font_name[font_number]=font_name;
MagickXFontBrowserWidget(display,windows,"Select",font_name);
if (*font_name == '\0')
break;
}
/*
Initialize font info.
*/
font_info=
XLoadQueryFont(display,resource_info->font_name[font_number]);
if (font_info == (XFontStruct *) NULL)
{
MagickXNoticeWidget(display,windows,"Unable to load font:",
resource_info->font_name[font_number]);
break;
}
font_id=font_number;
(void) XFreeFont(display,font_info);
break;
}
case AnnotateFontColorCommand:
{
/*
Initialize menu selections.
*/
for (i=0; i < (int) (MaxNumberPens-2); i++)
ColorMenu[i]=resource_info->pen_colors[i];
ColorMenu[MaxNumberPens-2]=(char *) "transparent";
ColorMenu[MaxNumberPens-1]=(char *) "Browser...";
ColorMenu[MaxNumberPens]=(char *) NULL;
/*
Select a pen color from the pop-up menu.
*/
pen_number=MagickXMenuWidget(display,windows,AnnotateMenu[id],
(const char **) ColorMenu,command);
if (pen_number < 0)
break;
transparent_pen=pen_number == (MaxNumberPens-2);
if (transparent_pen)
break;
if (pen_number == (MaxNumberPens-1))
{
static char
color_name[MaxTextExtent] = "gray";
/*
Select a pen color from a dialog.
*/
resource_info->pen_colors[pen_number]=color_name;
MagickXColorBrowserWidget(display,windows,"Select",color_name);
if (*color_name == '\0')
break;
}
/*
Set pen color.
*/
(void) XParseColor(display,windows->map_info->colormap,
resource_info->pen_colors[pen_number],&color);
MagickXBestPixel(display,windows->map_info->colormap,(XColor *) NULL,
(unsigned int) MaxColors,&color);
windows->pixel_info->pen_colors[pen_number]=color;
pen_id=pen_number;
break;
}
case AnnotateBackgroundColorCommand:
{
/*
Initialize menu selections.
*/
for (i=0; i < (int) (MaxNumberPens-2); i++)
ColorMenu[i]=resource_info->pen_colors[i];
ColorMenu[MaxNumberPens-2]=(char *) "transparent";
ColorMenu[MaxNumberPens-1]=(char *) "Browser...";
ColorMenu[MaxNumberPens]=(char *) NULL;
/*
Select a pen color from the pop-up menu.
*/
pen_number=MagickXMenuWidget(display,windows,AnnotateMenu[id],
(const char **) ColorMenu,command);
if (pen_number < 0)
break;
transparent_box=pen_number == (MaxNumberPens-2);
if (transparent_box)
break;
if (pen_number == (MaxNumberPens-1))
{
static char
color_name[MaxTextExtent] = "gray";
/*
Select a pen color from a dialog.
*/
resource_info->pen_colors[pen_number]=color_name;
MagickXColorBrowserWidget(display,windows,"Select",color_name);
if (*color_name == '\0')
break;
}
/*
Set pen color.
*/
(void) XParseColor(display,windows->map_info->colormap,
resource_info->pen_colors[pen_number],&color);
MagickXBestPixel(display,windows->map_info->colormap,(XColor *) NULL,
(unsigned int) MaxColors,&color);
windows->pixel_info->pen_colors[pen_number]=color;
box_id=pen_number;
break;
}
case AnnotateRotateCommand:
{
int
entry;
static char
angle[MaxTextExtent] = "30.0";
const char
* const RotateMenu[]=
{
"-90",
"-45",
"-30",
"0",
"30",
"45",
"90",
"180",
"Dialog...",
(char *) NULL,
};
/*
Select a command from the pop-up menu.
*/
entry=MagickXMenuWidget(display,windows,AnnotateMenu[id],RotateMenu,
command);
if (entry < 0)
break;
if (entry != 8)
{
degrees=MagickAtoF(RotateMenu[entry]);
break;
}
(void) MagickXDialogWidget(display,windows,"OK","Enter rotation angle:",
angle);
if (*angle == '\0')
break;
degrees=MagickAtoF(angle);
break;
}
case AnnotateHelpCommand:
{
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Image Annotation",
ImageAnnotateHelp,
sizeof(ImageAnnotateHelp));
break;
}
case AnnotateDismissCommand:
{
/*
Prematurely exit.
*/
state|=EscapeState;
state|=ExitState;
break;
}
default:
break;
}
continue;
}
switch (event.type)
{
case ButtonPress:
{
if (event.xbutton.button != Button1)
break;
if (event.xbutton.window != windows->image.id)
break;
/*
Change to text entering mode.
*/
x=event.xbutton.x;
y=event.xbutton.y;
state|=ExitState;
break;
}
case ButtonRelease:
break;
case Expose:
break;
case KeyPress:
{
if (event.xkey.window != windows->image.id)
break;
/*
Respond to a user key press.
*/
(void) XLookupString((XKeyEvent *) &event.xkey,command,sizeof(command),
&key_symbol,(XComposeStatus *) NULL);
switch ((int) key_symbol)
{
case XK_Escape:
case XK_F20:
{
/*
Prematurely exit.
*/
state|=EscapeState;
state|=ExitState;
break;
}
case XK_F1:
case XK_Help:
{
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Image Annotation",
ImageAnnotateHelp,
sizeof(ImageAnnotateHelp));
break;
}
default:
{
(void) XBell(display,0);
break;
}
}
break;
}
case MotionNotify:
{
/*
Map and unmap Info widget as cursor crosses its boundaries.
*/
x=event.xmotion.x;
y=event.xmotion.y;
if (windows->info.mapped)
{
if ((x < (int) (windows->info.x+windows->info.width)) &&
(y < (int) (windows->info.y+windows->info.height)))
(void) XWithdrawWindow(display,windows->info.id,
windows->info.screen);
}
else
if ((x > (int) (windows->info.x+windows->info.width)) ||
(y > (int) (windows->info.y+windows->info.height)))
(void) XMapWindow(display,windows->info.id);
break;
}
default:
break;
}
} while (!(state & ExitState));
(void) XSelectInput(display,windows->image.id,
windows->image.attributes.event_mask);
(void) XWithdrawWindow(display,windows->info.id,windows->info.screen);
if (state & EscapeState)
return(True);
/*
Set font info and check boundary conditions.
*/
font_info=XLoadQueryFont(display,resource_info->font_name[font_id]);
if (font_info == (XFontStruct *) NULL)
{
MagickXNoticeWidget(display,windows,"Unable to load font:",
resource_info->font_name[font_id]);
font_info=windows->font_info;
}
if ((x+font_info->max_bounds.width) >= (int) windows->image.width)
x=windows->image.width-font_info->max_bounds.width;
if (y < (long) (font_info->ascent+font_info->descent))
y=font_info->ascent+font_info->descent;
if ((font_info->max_bounds.width > (int) windows->image.width) ||
((font_info->ascent+font_info->descent) >= (int) windows->image.height))
return(False);
/*
Initialize annotate structure.
*/
annotate_info=MagickAllocateMemory(MagickXAnnotateInfo *,sizeof(MagickXAnnotateInfo));
if (annotate_info == (MagickXAnnotateInfo *) NULL)
return(False);
MagickXGetAnnotateInfo(annotate_info);
annotate_info->x=x;
annotate_info->y=y;
if (!transparent_box && !transparent_pen)
annotate_info->stencil=OpaqueStencil;
else
if (!transparent_box)
annotate_info->stencil=BackgroundStencil;
else
annotate_info->stencil=ForegroundStencil;
annotate_info->height=font_info->ascent+font_info->descent;
annotate_info->degrees=degrees;
annotate_info->font_info=font_info;
annotate_info->text=MagickAllocateMemory(char *,
windows->image.width/Max(font_info->min_bounds.width,1)+2);
if (annotate_info->text == (char *) NULL)
{
MagickFreeMemory(annotate_info);
return(False);
}
/*
Create cursor and set graphic context.
*/
cursor=XCreateFontCursor(display,XC_pencil);
(void) XDefineCursor(display,windows->image.id,cursor);
annotate_context=windows->image.annotate_context;
(void) XSetFont(display,annotate_context,font_info->fid);
(void) XSetBackground(display,annotate_context,
windows->pixel_info->pen_colors[box_id].pixel);
(void) XSetForeground(display,annotate_context,
windows->pixel_info->pen_colors[pen_id].pixel);
/*
Begin annotating the image with text.
*/
(void) CloneString(&windows->command.name,"Text");
windows->command.data=0;
(void) MagickXCommandWidget(display,windows,TextMenu,(XEvent *) NULL);
state=DefaultState;
(void) XDrawString(display,windows->image.id,annotate_context,x,y,"_",1);
text_event.xexpose.width=(unsigned int) font_info->max_bounds.width;
text_event.xexpose.height=font_info->max_bounds.ascent+
font_info->max_bounds.descent;
p=annotate_info->text;
do
{
/*
Display text cursor.
*/
*p='\0';
(void) XDrawString(display,windows->image.id,annotate_context,x,y,"_",1);
/*
Wait for next event.
*/
MagickXScreenEvent(display,windows,&event);
if (event.xany.window == windows->command.id)
{
/*
Select a command from the Command widget.
*/
(void) XSetBackground(display,annotate_context,
windows->pixel_info->background_color.pixel);
(void) XSetForeground(display,annotate_context,
windows->pixel_info->foreground_color.pixel);
id=MagickXCommandWidget(display,windows,AnnotateMenu,&event);
(void) XSetBackground(display,annotate_context,
windows->pixel_info->pen_colors[box_id].pixel);
(void) XSetForeground(display,annotate_context,
windows->pixel_info->pen_colors[pen_id].pixel);
if (id < 0)
continue;
switch (TextCommands[id])
{
case TextHelpCommand:
{
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Image Annotation",
ImageAnnotateHelp,
sizeof(ImageAnnotateHelp));
(void) XDefineCursor(display,windows->image.id,cursor);
break;
}
case TextApplyCommand:
{
/*
Finished annotating.
*/
annotate_info->width=XTextWidth(font_info,annotate_info->text,
(int) strlen(annotate_info->text));
MagickXRefreshWindow(display,&windows->image,&text_event);
state|=ExitState;
break;
}
default:
break;
}
continue;
}
/*
Erase text cursor.
*/
text_event.xexpose.x=x;
text_event.xexpose.y=y-font_info->max_bounds.ascent;
(void) XClearArea(display,windows->image.id,x,text_event.xexpose.y,
text_event.xexpose.width,text_event.xexpose.height,False);
MagickXRefreshWindow(display,&windows->image,&text_event);
switch (event.type)
{
case ButtonPress:
{
if (event.xbutton.window != windows->image.id)
break;
if (event.xbutton.button == Button2)
{
/*
Request primary selection.
*/
(void) XConvertSelection(display,XA_PRIMARY,XA_STRING,XA_STRING,
windows->image.id,CurrentTime);
break;
}
break;
}
case Expose:
{
if (event.xexpose.count == 0)
{
MagickXAnnotateInfo
*text_info;
/*
Refresh Image window.
*/
MagickXRefreshWindow(display,&windows->image,(XEvent *) NULL);
text_info=annotate_info;
while (text_info != (MagickXAnnotateInfo *) NULL)
{
if (annotate_info->stencil == ForegroundStencil)
(void) XDrawString(display,windows->image.id,annotate_context,
text_info->x,text_info->y,text_info->text,
(int) strlen(text_info->text));
else
(void) XDrawImageString(display,windows->image.id,
annotate_context,text_info->x,text_info->y,text_info->text,
(int) strlen(text_info->text));
text_info=text_info->previous;
}
(void) XDrawString(display,windows->image.id,annotate_context,
x,y,"_",1);
}
break;
}
case KeyPress:
{
int
length;
if (event.xkey.window != windows->image.id)
break;
/*
Respond to a user key press.
*/
length=XLookupString((XKeyEvent *) &event.xkey,command,sizeof(command),
&key_symbol,(XComposeStatus *) NULL);
*(command+length)='\0';
if ((event.xkey.state & ControlMask) || (event.xkey.state & Mod1Mask))
state|=ModifierState;
if (state & ModifierState)
switch ((int) key_symbol)
{
case XK_u:
case XK_U:
{
key_symbol=DeleteCommand;
break;
}
default:
break;
}
switch ((int) key_symbol)
{
case XK_BackSpace:
{
/*
Erase one character.
*/
if (p == annotate_info->text)
{
if (annotate_info->previous == (MagickXAnnotateInfo *) NULL)
break;
else
{
/*
Go to end of the previous line of text.
*/
annotate_info=annotate_info->previous;
p=annotate_info->text;
x=annotate_info->x+annotate_info->width;
y=annotate_info->y;
if (annotate_info->width != 0)
p+=strlen(annotate_info->text);
break;
}
}
p--;
x-=XTextWidth(font_info,p,1);
text_event.xexpose.x=x;
text_event.xexpose.y=y-font_info->max_bounds.ascent;
MagickXRefreshWindow(display,&windows->image,&text_event);
break;
}
case XK_bracketleft:
{
key_symbol=XK_Escape;
break;
}
case DeleteCommand:
{
/*
Erase the entire line of text.
*/
while (p != annotate_info->text)
{
p--;
x-=XTextWidth(font_info,p,1);
text_event.xexpose.x=x;
MagickXRefreshWindow(display,&windows->image,&text_event);
}
break;
}
case XK_Escape:
case XK_F20:
{
/*
Finished annotating.
*/
annotate_info->width=XTextWidth(font_info,annotate_info->text,
(int) strlen(annotate_info->text));
MagickXRefreshWindow(display,&windows->image,&text_event);
state|=ExitState;
break;
}
default:
{
/*
Draw a single character on the Image window.
*/
if (state & ModifierState)
break;
if (*command == '\0')
break;
*p=(*command);
if (annotate_info->stencil == ForegroundStencil)
(void) XDrawString(display,windows->image.id,annotate_context,
x,y,p,1);
else
(void) XDrawImageString(display,windows->image.id,
annotate_context,x,y,p,1);
x+=XTextWidth(font_info,p,1);
p++;
if ((x+font_info->max_bounds.width) < (int) windows->image.width)
break;
break; /* Not completely sure about this break (used to fall through) */
}
case XK_Return:
case XK_KP_Enter:
{
/*
Advance to the next line of text.
*/
*p='\0';
annotate_info->width=XTextWidth(font_info,annotate_info->text,
(int) strlen(annotate_info->text));
if (annotate_info->next != (MagickXAnnotateInfo *) NULL)
{
/*
Line of text already exists.
*/
annotate_info=annotate_info->next;
x=annotate_info->x;
y=annotate_info->y;
p=annotate_info->text;
break;
}
annotate_info->next=MagickAllocateMemory(MagickXAnnotateInfo *,
sizeof(MagickXAnnotateInfo));
if (annotate_info->next == (MagickXAnnotateInfo *) NULL)
return(False);
*annotate_info->next=(*annotate_info);
annotate_info->next->previous=annotate_info;
annotate_info=annotate_info->next;
annotate_info->text=MagickAllocateMemory(char *,windows->image.width/
Max(font_info->min_bounds.width,1)+2);
if (annotate_info->text == (char *) NULL)
return(False);
annotate_info->y+=annotate_info->height;
if (annotate_info->y > (int) windows->image.height)
annotate_info->y=annotate_info->height;
annotate_info->next=(MagickXAnnotateInfo *) NULL;
x=annotate_info->x;
y=annotate_info->y;
p=annotate_info->text;
break;
}
}
break;
}
case KeyRelease:
{
/*
Respond to a user key release.
*/
(void) XLookupString((XKeyEvent *) &event.xkey,command,sizeof(command),
&key_symbol,(XComposeStatus *) NULL);
state&=(~ModifierState);
break;
}
case SelectionNotify:
{
Atom
type;
int
format;
unsigned char
*data;
unsigned long
after,
length;
/*
Obtain response from primary selection.
*/
if (event.xselection.property == (Atom) None)
break;
status=XGetWindowProperty(display,event.xselection.requestor,
event.xselection.property,0L,MaxTextExtent-1,True,XA_STRING,&type,
&format,&length,&after,&data);
if ((status != Success) || (type != XA_STRING) || (format == 32) ||
(length == 0))
break;
/*
Annotate Image window with primary selection.
*/
for (i=0; i < (long) length; i++)
{
if ((char) data[i] != '\n')
{
/*
Draw a single character on the Image window.
*/
*p=data[i];
(void) XDrawString(display,windows->image.id,annotate_context,
x,y,p,1);
x+=XTextWidth(font_info,p,1);
p++;
if ((x+font_info->max_bounds.width) < (int) windows->image.width)
continue;
}
/*
Advance to the next line of text.
*/
*p='\0';
annotate_info->width=XTextWidth(font_info,annotate_info->text,
(int) strlen(annotate_info->text));
if (annotate_info->next != (MagickXAnnotateInfo *) NULL)
{
/*
Line of text already exists.
*/
annotate_info=annotate_info->next;
x=annotate_info->x;
y=annotate_info->y;
p=annotate_info->text;
continue;
}
annotate_info->next=MagickAllocateMemory(MagickXAnnotateInfo *,
sizeof(MagickXAnnotateInfo));
if (annotate_info->next == (MagickXAnnotateInfo *) NULL)
return(False);
*annotate_info->next=(*annotate_info);
annotate_info->next->previous=annotate_info;
annotate_info=annotate_info->next;
annotate_info->text=MagickAllocateMemory(char *,windows->image.width/
Max(font_info->min_bounds.width,1)+2);
if (annotate_info->text == (char *) NULL)
return(False);
annotate_info->y+=annotate_info->height;
if (annotate_info->y > (int) windows->image.height)
annotate_info->y=annotate_info->height;
annotate_info->next=(MagickXAnnotateInfo *) NULL;
x=annotate_info->x;
y=annotate_info->y;
p=annotate_info->text;
}
(void) XFree((void *) data);
break;
}
default:
break;
}
} while (!(state & ExitState));
(void) XFreeCursor(display,cursor);
/*
Annotation is relative to image configuration.
*/
width=(unsigned int) image->columns;
height=(unsigned int) image->rows;
x=0;
y=0;
if (windows->image.crop_geometry != (char *) NULL)
(void) XParseGeometry(windows->image.crop_geometry,&x,&y,&width,&height);
/*
Initialize annotated image.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
while (annotate_info != (MagickXAnnotateInfo *) NULL)
{
if (annotate_info->width == 0)
{
/*
No text on this line-- go to the next line of text.
*/
previous_info=annotate_info->previous;
MagickFreeMemory(annotate_info->text);
MagickFreeMemory(annotate_info);
annotate_info=previous_info;
continue;
}
/*
Determine pixel index for box and pen color.
*/
windows->pixel_info->box_color=windows->pixel_info->pen_colors[box_id];
if (windows->pixel_info->colors != 0)
for (i=0; i < (long) windows->pixel_info->colors; i++)
if (windows->pixel_info->pixels[i] ==
windows->pixel_info->pen_colors[box_id].pixel)
{
windows->pixel_info->box_index=(unsigned short) i;
break;
}
windows->pixel_info->pen_color=windows->pixel_info->pen_colors[pen_id];
if (windows->pixel_info->colors != 0)
for (i=0; i < (long) windows->pixel_info->colors; i++)
if (windows->pixel_info->pixels[i] ==
windows->pixel_info->pen_colors[pen_id].pixel)
{
windows->pixel_info->pen_index=(unsigned short) i;
break;
}
/*
Define the annotate geometry string.
*/
annotate_info->x=
width*(annotate_info->x+windows->image.x)/windows->image.ximage->width;
annotate_info->y=height*(annotate_info->y-font_info->ascent+
windows->image.y)/windows->image.ximage->height;
FormatString(annotate_info->geometry,"%ux%u%+d%+d",
width*annotate_info->width/windows->image.ximage->width,
height*annotate_info->height/windows->image.ximage->height,
annotate_info->x+x,annotate_info->y+y);
/*
Annotate image with text.
*/
status=MagickXAnnotateImage(display,windows->pixel_info,annotate_info,image);
if (status == 0)
return(False);
/*
Free up memory.
*/
previous_info=annotate_info->previous;
MagickFreeMemory(annotate_info->text);
MagickFreeMemory(annotate_info);
annotate_info=previous_info;
}
(void) XSetForeground(display,annotate_context,
windows->pixel_info->foreground_color.pixel);
(void) XSetBackground(display,annotate_context,
windows->pixel_info->background_color.pixel);
(void) XSetFont(display,annotate_context,windows->font_info->fid);
MagickXSetCursorState(display,windows,False);
(void) XFreeFont(display,font_info);
/*
Update image configuration.
*/
MagickXConfigureImageColormap(display,resource_info,windows,image);
(void) MagickXConfigureImage(display,resource_info,windows,image);
return(True);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X B a c k g r o u n d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXBackgroundImage displays the image in the background of a window.
%
% The format of the MagickXBackgroundImage method is:
%
% unsigned int MagickXBackgroundImage(Display *display,
% MagickXResourceInfo *resource_info,MagickXWindows *windows,Image **image)
%
% A description of each parameter follows:
%
% o status: Method MagickXBackgroundImage return True if the image is
% printed. False is returned is there is a memory shortage or if the
% image fails to print.
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o resource_info: Specifies a pointer to a X11 MagickXResourceInfo structure.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
% o image: Specifies a pointer to an Image structure; returned from
% ReadImage.
%
%
*/
static unsigned int MagickXBackgroundImage(Display *display,
MagickXResourceInfo *resource_info,MagickXWindows *windows,Image **image)
{
#define BackgroundImageText " Background the image... "
static char
window_id[MaxTextExtent] = "root";
MagickXResourceInfo
background_resources;
unsigned int
status;
/*
Put image in background.
*/
status=MagickXDialogWidget(display,windows,"Background",
"Enter window id (id 0x00 selects window with pointer):",window_id);
if (*window_id == '\0')
return(False);
(void) MagickXMagickCommand(display,resource_info,windows,ApplyCommand,image);
MagickXInfoWidget(display,windows,BackgroundImageText);
/*
Display hourglass cursor if progress indication enabled.
*/
if (resource_info->image_info->progress)
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
background_resources=(*resource_info);
background_resources.window_id=window_id;
background_resources.backdrop=status;
status=MagickXDisplayBackgroundImage(display,&background_resources,*image);
if (status)
MagickXClientMessage(display,windows->image.id,windows->im_protocols,
windows->im_retain_colors,CurrentTime);
MagickXSetCursorState(display,windows,False);
(void) MagickXMagickCommand(display,resource_info,windows,UndoCommand,image);
return(True);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X C h o p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXChopImage chops the X image.
%
% The format of the MagickXChopImage method is:
%
% unsigned int MagickXChopImage(Display *display,MagickXResourceInfo *resource_info,
% MagickXWindows *windows,Image **image)
%
% A description of each parameter follows:
%
% o status: Method MagickXChopImage return True if the image is
% cut. False is returned is there is a memory shortage or if the
% image fails to cut.
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o resource_info: Specifies a pointer to a X11 MagickXResourceInfo structure.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
% o image: Specifies a pointer to an Image structure; returned from
% ReadImage.
%
%
*/
static unsigned int MagickXChopImage(Display *display,MagickXResourceInfo *resource_info,
MagickXWindows *windows,Image **image)
{
const char
* const ChopMenu[]=
{
"Direction",
"Help",
"Dismiss",
(char *) NULL
};
static ModeType
direction = HorizontalChopCommand;
static const ModeType
ChopCommands[]=
{
ChopDirectionCommand,
ChopHelpCommand,
ChopDismissCommand
},
DirectionCommands[]=
{
HorizontalChopCommand,
VerticalChopCommand
};
char
text[MaxTextExtent];
double
scale_factor;
Image
*chop_image;
int
id,
x,
y;
RectangleInfo
chop_info;
unsigned int
distance,
height,
width;
unsigned long
state;
XEvent
event;
XSegment
segment_info;
/*
Map Command widget.
*/
(void) CloneString(&windows->command.name,"Chop");
windows->command.data=1;
(void) MagickXCommandWidget(display,windows,ChopMenu,(XEvent *) NULL);
(void) XMapRaised(display,windows->command.id);
MagickXClientMessage(display,windows->image.id,windows->im_protocols,
windows->im_update_widget,CurrentTime);
/*
Track pointer until button 1 is pressed.
*/
MagickXQueryPosition(display,windows->image.id,&x,&y);
(void) XSelectInput(display,windows->image.id,
windows->image.attributes.event_mask | PointerMotionMask);
state=DefaultState;
do
{
if (windows->info.mapped)
{
/*
Display pointer position.
*/
FormatString(text," %+d%+d ",x+windows->image.x,y+windows->image.y);
MagickXInfoWidget(display,windows,text);
}
/*
Wait for next event.
*/
MagickXScreenEvent(display,windows,&event);
if (event.xany.window == windows->command.id)
{
/*
Select a command from the Command widget.
*/
id=MagickXCommandWidget(display,windows,ChopMenu,&event);
if (id < 0)
continue;
switch (ChopCommands[id])
{
case ChopDirectionCommand:
{
char
command[MaxTextExtent];
const char
* const Directions[]=
{
"horizontal",
"vertical",
(char *) NULL,
};
/*
Select a command from the pop-up menu.
*/
id=
MagickXMenuWidget(display,windows,ChopMenu[id],Directions,command);
if (id >= 0)
direction=DirectionCommands[id];
break;
}
case ChopHelpCommand:
{
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Image Chop",
ImageChopHelp,
sizeof(ImageChopHelp));
break;
}
case ChopDismissCommand:
{
/*
Prematurely exit.
*/
state|=EscapeState;
state|=ExitState;
break;
}
default:
break;
}
continue;
}
switch (event.type)
{
case ButtonPress:
{
if (event.xbutton.button != Button1)
break;
if (event.xbutton.window != windows->image.id)
break;
/*
User has committed to start point of chopping line.
*/
segment_info.x1=event.xbutton.x;
segment_info.x2=event.xbutton.x;
segment_info.y1=event.xbutton.y;
segment_info.y2=event.xbutton.y;
state|=ExitState;
break;
}
case ButtonRelease:
break;
case Expose:
break;
case KeyPress:
{
char
command[MaxTextExtent];
KeySym
key_symbol;
if (event.xkey.window != windows->image.id)
break;
/*
Respond to a user key press.
*/
(void) XLookupString((XKeyEvent *) &event.xkey,command,
sizeof(command),&key_symbol,(XComposeStatus *) NULL);
switch ((int) key_symbol)
{
case XK_Escape:
case XK_F20:
{
/*
Prematurely exit.
*/
state|=EscapeState;
state|=ExitState;
break;
}
case XK_F1:
case XK_Help:
{
(void) XSetFunction(display,windows->image.highlight_context,
GXcopy);
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Image Chop",
ImageChopHelp,
sizeof(ImageChopHelp));
(void) XSetFunction(display,windows->image.highlight_context,
GXinvert);
break;
}
default:
{
(void) XBell(display,0);
break;
}
}
break;
}
case MotionNotify:
{
/*
Map and unmap Info widget as text cursor crosses its boundaries.
*/
x=event.xmotion.x;
y=event.xmotion.y;
if (windows->info.mapped)
{
if ((x < (int) (windows->info.x+windows->info.width)) &&
(y < (int) (windows->info.y+windows->info.height)))
(void) XWithdrawWindow(display,windows->info.id,
windows->info.screen);
}
else
if ((x > (int) (windows->info.x+windows->info.width)) ||
(y > (int) (windows->info.y+windows->info.height)))
(void) XMapWindow(display,windows->info.id);
}
}
} while (!(state & ExitState));
(void) XSelectInput(display,windows->image.id,
windows->image.attributes.event_mask);
(void) XWithdrawWindow(display,windows->info.id,windows->info.screen);
if (state & EscapeState)
return(True);
/*
Draw line as pointer moves until the mouse button is released.
*/
chop_info.width=0;
chop_info.height=0;
chop_info.x=0;
chop_info.y=0;
distance=0;
(void) XSetFunction(display,windows->image.highlight_context,GXinvert);
state=DefaultState;
do
{
if (distance > 9)
{
/*
Display info and draw chopping line.
*/
if (!windows->info.mapped)
(void) XMapWindow(display,windows->info.id);
FormatString(text," %lux%lu%+ld%+ld",chop_info.width,chop_info.height,
chop_info.x,chop_info.y);
MagickXInfoWidget(display,windows,text);
MagickXHighlightLine(display,windows->image.id,
windows->image.highlight_context,&segment_info);
}
else
if (windows->info.mapped)
(void) XWithdrawWindow(display,windows->info.id,windows->info.screen);
/*
Wait for next event.
*/
MagickXScreenEvent(display,windows,&event);
if (distance > 9)
MagickXHighlightLine(display,windows->image.id,
windows->image.highlight_context,&segment_info);
switch (event.type)
{
case ButtonPress:
{
segment_info.x2=event.xmotion.x;
segment_info.y2=event.xmotion.y;
break;
}
case ButtonRelease:
{
/*
User has committed to chopping line.
*/
segment_info.x2=event.xbutton.x;
segment_info.y2=event.xbutton.y;
state|=ExitState;
break;
}
case Expose:
break;
case MotionNotify:
{
segment_info.x2=event.xmotion.x;
segment_info.y2=event.xmotion.y;
}
default:
break;
}
/*
Check boundary conditions.
*/
if (segment_info.x2 < 0)
segment_info.x2=0;
else
if (segment_info.x2 > windows->image.ximage->width)
segment_info.x2=windows->image.ximage->width;
if (segment_info.y2 < 0)
segment_info.y2=0;
else
if (segment_info.y2 > windows->image.ximage->height)
segment_info.y2=windows->image.ximage->height;
distance=
((segment_info.x2-segment_info.x1)*(segment_info.x2-segment_info.x1))+
((segment_info.y2-segment_info.y1)*(segment_info.y2-segment_info.y1));
/*
Compute chopping geometry.
*/
if (direction == HorizontalChopCommand)
{
chop_info.width=segment_info.x2-segment_info.x1+1;
chop_info.x=windows->image.x+segment_info.x1;
chop_info.height=0;
chop_info.y=0;
if (segment_info.x1 > (int) segment_info.x2)
{
chop_info.width=segment_info.x1-segment_info.x2+1;
chop_info.x=windows->image.x+segment_info.x2;
}
}
else
{
chop_info.width=0;
chop_info.height=segment_info.y2-segment_info.y1+1;
chop_info.x=0;
chop_info.y=windows->image.y+segment_info.y1;
if (segment_info.y1 > segment_info.y2)
{
chop_info.height=segment_info.y1-segment_info.y2+1;
chop_info.y=windows->image.y+segment_info.y2;
}
}
} while (!(state & ExitState));
(void) XSetFunction(display,windows->image.highlight_context,GXcopy);
(void) XWithdrawWindow(display,windows->info.id,windows->info.screen);
if (distance <= 9)
return(True);
/*
Image chopping is relative to image configuration.
*/
(void) MagickXMagickCommand(display,resource_info,windows,ApplyCommand,image);
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
windows->image.window_changes.width=
windows->image.ximage->width-(unsigned int) chop_info.width;
windows->image.window_changes.height=
windows->image.ximage->height-(unsigned int) chop_info.height;
width=(unsigned int) (*image)->columns;
height=(unsigned int) (*image)->rows;
x=0;
y=0;
if (windows->image.crop_geometry != (char *) NULL)
(void) XParseGeometry(windows->image.crop_geometry,&x,&y,&width,&height);
scale_factor=(double) width/windows->image.ximage->width;
chop_info.x+=x;
chop_info.x=(int) (scale_factor*chop_info.x+0.5);
chop_info.width=(unsigned int) (scale_factor*chop_info.width+0.5);
scale_factor=(double) height/windows->image.ximage->height;
chop_info.y+=y;
chop_info.y=(int) (scale_factor*chop_info.y+0.5);
chop_info.height=(unsigned int) (scale_factor*chop_info.height+0.5);
/*
Chop image.
*/
chop_image=ChopImage(*image,&chop_info,&(*image)->exception);
MagickXSetCursorState(display,windows,False);
if (chop_image == (Image *) NULL)
return(False);
DestroyImage(*image);
*image=chop_image;
/*
Update image configuration.
*/
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
return(True);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X C o l o r E d i t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXColorEditImage allows the user to interactively change
% the color of one pixel for a DirectColor image or one colormap entry for
% a PseudoClass image.
%
% The format of the MagickXColorEditImage method is:
%
% unsigned int MagickXColorEditImage(Display *display,
% MagickXResourceInfo *resource_info,MagickXWindows *windows,Image **image)
%
% A description of each parameter follows:
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o resource_info: Specifies a pointer to a X11 MagickXResourceInfo structure.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
% o image: Specifies a pointer to an Image structure; returned from
% ReadImage.
%
*/
static unsigned int MagickXColorEditImage(Display *display,
MagickXResourceInfo *resource_info,MagickXWindows *windows,Image **image)
{
const char
* const ColorEditMenu[]=
{
"Method",
"Pixel Color",
"Border Color",
"Fuzz",
"Undo",
"Help",
"Dismiss",
(char *) NULL
};
static const ModeType
ColorEditCommands[]=
{
ColorEditMethodCommand,
ColorEditColorCommand,
ColorEditBorderCommand,
ColorEditFuzzCommand,
ColorEditUndoCommand,
ColorEditHelpCommand,
ColorEditDismissCommand
};
static PaintMethod
method = PointMethod;
static unsigned int
pen_id = 0;
static XColor
border_color = { 0, 0, 0, 0, 0, 0 }; /* Also fill 'pad' field */
char
command[MaxTextExtent],
text[MaxTextExtent];
Cursor
cursor;
int
entry,
id,
x,
x_offset,
y,
y_offset;
register PixelPacket
*q;
register long
i;
unsigned int
height,
width;
unsigned long
state;
XColor
color;
XEvent
event;
/*
Map Command widget.
*/
(void) CloneString(&windows->command.name,"Color Edit");
windows->command.data=4;
(void) MagickXCommandWidget(display,windows,ColorEditMenu,(XEvent *) NULL);
(void) XMapRaised(display,windows->command.id);
MagickXClientMessage(display,windows->image.id,windows->im_protocols,
windows->im_update_widget,CurrentTime);
/*
Make cursor.
*/
cursor=MagickXMakeCursor(display,windows->image.id,windows->map_info->colormap,
resource_info->background_color,resource_info->foreground_color);
(void) XDefineCursor(display,windows->image.id,cursor);
/*
Track pointer until button 1 is pressed.
*/
MagickXQueryPosition(display,windows->image.id,&x,&y);
(void) XSelectInput(display,windows->image.id,
windows->image.attributes.event_mask | PointerMotionMask);
state=DefaultState;
do
{
if (windows->info.mapped)
{
/*
Display pointer position.
*/
FormatString(text," %+d%+d ",x+windows->image.x,y+windows->image.y);
MagickXInfoWidget(display,windows,text);
}
/*
Wait for next event.
*/
MagickXScreenEvent(display,windows,&event);
if (event.xany.window == windows->command.id)
{
/*
Select a command from the Command widget.
*/
id=MagickXCommandWidget(display,windows,ColorEditMenu,&event);
if (id < 0)
{
(void) XDefineCursor(display,windows->image.id,cursor);
continue;
}
switch (ColorEditCommands[id])
{
case ColorEditMethodCommand:
{
const char
* const MethodMenu[]=
{
"point",
"replace",
"floodfill",
"filltoborder",
"reset",
(char *) NULL,
};
/*
Select a method from the pop-up menu.
*/
entry=
MagickXMenuWidget(display,windows,ColorEditMenu[id],MethodMenu,command);
if (entry >= 0)
method=(PaintMethod) entry;
break;
}
case ColorEditColorCommand:
{
const char
*ColorMenu[MaxNumberPens];
int
pen_number;
/*
Initialize menu selections.
*/
for (i=0; i < (int) (MaxNumberPens-2); i++)
ColorMenu[i]=resource_info->pen_colors[i];
ColorMenu[MaxNumberPens-2]="Browser...";
ColorMenu[MaxNumberPens-1]=NULL;
/*
Select a pen color from the pop-up menu.
*/
pen_number=MagickXMenuWidget(display,windows,ColorEditMenu[id],
(const char **) ColorMenu,command);
if (pen_number < 0)
break;
if (pen_number == (MaxNumberPens-2))
{
static char
color_name[MaxTextExtent] = "gray";
/*
Select a pen color from a dialog.
*/
resource_info->pen_colors[pen_number]=color_name;
MagickXColorBrowserWidget(display,windows,"Select",color_name);
if (*color_name == '\0')
break;
}
/*
Set pen color.
*/
(void) XParseColor(display,windows->map_info->colormap,
resource_info->pen_colors[pen_number],&color);
MagickXBestPixel(display,windows->map_info->colormap,(XColor *) NULL,
(unsigned int) MaxColors,&color);
windows->pixel_info->pen_colors[pen_number]=color;
pen_id=pen_number;
break;
}
case ColorEditBorderCommand:
{
const char
*ColorMenu[MaxNumberPens];
int
pen_number;
/*
Initialize menu selections.
*/
for (i=0; i < (int) (MaxNumberPens-2); i++)
ColorMenu[i]=resource_info->pen_colors[i];
ColorMenu[MaxNumberPens-2]="Browser...";
ColorMenu[MaxNumberPens-1]=NULL;
/*
Select a pen color from the pop-up menu.
*/
pen_number=MagickXMenuWidget(display,windows,ColorEditMenu[id],
(const char **) ColorMenu,command);
if (pen_number < 0)
break;
if (pen_number == (MaxNumberPens-2))
{
static char
color_name[MaxTextExtent] = "gray";
/*
Select a pen color from a dialog.
*/
resource_info->pen_colors[pen_number]=color_name;
MagickXColorBrowserWidget(display,windows,"Select",color_name);
if (*color_name == '\0')
break;
}
/*
Set border color.
*/
(void) XParseColor(display,windows->map_info->colormap,
resource_info->pen_colors[pen_number],&border_color);
break;
}
case ColorEditFuzzCommand:
{
static char
fuzz[MaxTextExtent];
const char
* const FuzzMenu[]=
{
"0%",
"2%",
"5%",
"10%",
"15%",
"Dialog...",
(char *) NULL,
};
/*
Select a command from the pop-up menu.
*/
entry=MagickXMenuWidget(display,windows,ColorEditMenu[id],FuzzMenu,
command);
if (entry < 0)
break;
if (entry != 5)
{
(*image)->fuzz=StringToDouble(FuzzMenu[entry],MaxRGB);
break;
}
(void) strcpy(fuzz,"20%");
(void) MagickXDialogWidget(display,windows,"Ok",
"Enter fuzz factor (0.0 - 99.9%):",fuzz);
if (*fuzz == '\0')
break;
(void) strcat(fuzz,"%");
(*image)->fuzz=StringToDouble(fuzz,MaxRGB);
break;
}
case ColorEditUndoCommand:
{
(void) MagickXMagickCommand(display,resource_info,windows,UndoCommand,
image);
break;
}
case ColorEditHelpCommand:
default:
{
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Image Annotation",
ImageColorEditHelp,
sizeof(ImageColorEditHelp));
break;
}
case ColorEditDismissCommand:
{
/*
Prematurely exit.
*/
state|=EscapeState;
state|=ExitState;
break;
}
}
(void) XDefineCursor(display,windows->image.id,cursor);
continue;
}
switch (event.type)
{
case ButtonPress:
{
if (event.xbutton.button != Button1)
break;
if ((event.xbutton.window != windows->image.id) &&
(event.xbutton.window != windows->magnify.id))
break;
/*
Exit loop.
*/
x=event.xbutton.x;
y=event.xbutton.y;
(void) MagickXMagickCommand(display,resource_info,windows,
SaveToUndoBufferCommand,image);
state|=UpdateConfigurationState;
break;
}
case ButtonRelease:
{
if (event.xbutton.button != Button1)
break;
if ((event.xbutton.window != windows->image.id) &&
(event.xbutton.window != windows->magnify.id))
break;
/*
Update colormap information.
*/
x=event.xbutton.x;
y=event.xbutton.y;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
MagickXInfoWidget(display,windows,text);
(void) XDefineCursor(display,windows->image.id,cursor);
state&=(~UpdateConfigurationState);
break;
}
case Expose:
break;
case KeyPress:
{
KeySym
key_symbol;
if (event.xkey.window == windows->magnify.id)
{
Window
window;
window=windows->magnify.id;
while (XCheckWindowEvent(display,window,KeyPressMask,&event));
}
if (event.xkey.window != windows->image.id)
break;
/*
Respond to a user key press.
*/
(void) XLookupString((XKeyEvent *) &event.xkey,command,sizeof(command),
&key_symbol,(XComposeStatus *) NULL);
switch ((int) key_symbol)
{
case XK_Escape:
case XK_F20:
{
/*
Prematurely exit.
*/
state|=ExitState;
break;
}
case XK_F1:
case XK_Help:
{
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Image Annotation",
ImageColorEditHelp,
sizeof(ImageColorEditHelp));
break;
}
default:
{
(void) XBell(display,0);
break;
}
}
break;
}
case MotionNotify:
{
/*
Map and unmap Info widget as cursor crosses its boundaries.
*/
x=event.xmotion.x;
y=event.xmotion.y;
if (windows->info.mapped)
{
if ((x < (int) (windows->info.x+windows->info.width)) &&
(y < (int) (windows->info.y+windows->info.height)))
(void) XWithdrawWindow(display,windows->info.id,
windows->info.screen);
}
else
if ((x > (int) (windows->info.x+windows->info.width)) ||
(y > (int) (windows->info.y+windows->info.height)))
(void) XMapWindow(display,windows->info.id);
break;
}
default:
break;
}
if (event.xany.window == windows->magnify.id)
{
x=windows->magnify.x-windows->image.x;
y=windows->magnify.y-windows->image.y;
}
x_offset=x;
y_offset=y;
if (state & UpdateConfigurationState)
{
int
x,
y;
/*
Pixel edit is relative to image configuration.
*/
(void) XClearArea(display,windows->image.id,x_offset,y_offset,1,1,True);
color=windows->pixel_info->pen_colors[pen_id];
XPutPixel(windows->image.ximage,x_offset,y_offset,color.pixel);
width=(unsigned int) (*image)->columns;
height=(unsigned int) (*image)->rows;
x=0;
y=0;
if (windows->image.crop_geometry != (char *) NULL)
(void) XParseGeometry(windows->image.crop_geometry,&x,&y,
&width,&height);
x_offset=
width*(windows->image.x+x_offset)/windows->image.ximage->width+x;
y_offset=
height*(windows->image.y+y_offset)/windows->image.ximage->height+y;
if ((x_offset < 0) || (y_offset < 0))
continue;
if ((x_offset >= (long) (*image)->columns) ||
(y_offset >= (long) (*image)->rows))
continue;
switch (method)
{
case PointMethod:
default:
{
/*
Update color information using point algorithm.
*/
(void) SetImageType(*image,TrueColorType);
q=GetImagePixels(*image,x_offset,y_offset,1,1);
if (q == (PixelPacket *) NULL)
break;
q->red=ScaleShortToQuantum(color.red);
q->green=ScaleShortToQuantum(color.green);
q->blue=ScaleShortToQuantum(color.blue);
(void) SyncImagePixels(*image);
break;
}
case ReplaceMethod:
{
PixelPacket
target;
/*
Update color information using replace algorithm.
*/
(void) AcquireOnePixelByReference(*image,&target,x_offset,y_offset,&((*image)->exception));
if ((*image)->storage_class == DirectClass)
{
for (y=0; y < (long) (*image)->rows; y++)
{
q=GetImagePixels(*image,0,y,(*image)->columns,1);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (int) (*image)->columns; x++)
{
if (FuzzyColorMatch(q,&target,(*image)->fuzz))
{
q->red=ScaleShortToQuantum(color.red);
q->green=ScaleShortToQuantum(color.green);
q->blue=ScaleShortToQuantum(color.blue);
}
q++;
}
if (!SyncImagePixels(*image))
break;
}
}
else
{
for (i=0; i < (int) (*image)->colors; i++)
if (FuzzyColorMatch((*image)->colormap+i,&target,(*image)->fuzz))
{
(*image)->colormap[i].red=ScaleShortToQuantum(color.red);
(*image)->colormap[i].green=
ScaleShortToQuantum(color.green);
(*image)->colormap[i].blue=
ScaleShortToQuantum(color.blue);
}
(void) SyncImage(*image);
}
break;
}
case FloodfillMethod:
case FillToBorderMethod:
{
DrawInfo
*draw_info;
PixelPacket
target;
/*
Update color information using floodfill algorithm.
*/
(void) AcquireOnePixelByReference(*image,&target,x_offset,y_offset,&((*image)->exception));
if (method == FillToBorderMethod)
{
target.red=ScaleShortToQuantum(border_color.red);
target.green=ScaleShortToQuantum(border_color.green);
target.blue=ScaleShortToQuantum(border_color.blue);
}
draw_info=
CloneDrawInfo(resource_info->image_info,(DrawInfo *) NULL);
(void) QueryColorDatabase(resource_info->pen_colors[pen_id],
&draw_info->fill,&(*image)->exception);
(void) ColorFloodfillImage(*image,draw_info,target,x_offset,
y_offset,method);
DestroyDrawInfo(draw_info);
break;
}
case ResetMethod:
{
/*
Update color information using reset algorithm.
*/
(void) SetImageType(*image,TrueColorType);
for (y=0; y < (long) (*image)->rows; y++)
{
q=SetImagePixels(*image,0,y,(*image)->columns,1);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (int) (*image)->columns; x++)
{
q->red=ScaleShortToQuantum(color.red);
q->green=ScaleShortToQuantum(color.green);
q->blue=ScaleShortToQuantum(color.blue);
q++;
}
if (!SyncImagePixels(*image))
break;
}
break;
}
}
state&=(~UpdateConfigurationState);
}
} while (!(state & ExitState));
(void) XSelectInput(display,windows->image.id,
windows->image.attributes.event_mask);
MagickXSetCursorState(display,windows,False);
(void) XFreeCursor(display,cursor);
return(True);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X C o m p o s i t e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXCompositeImage requests an image name from the user, reads
% the image and composites it with the X window image at a location the user
% chooses with the pointer.
%
% The format of the MagickXCompositeImage method is:
%
% unsigned int MagickXCompositeImage(Display *display,
% MagickXResourceInfo *resource_info,MagickXWindows *windows,Image *image)
%
% A description of each parameter follows:
%
% o status: Method MagickXCompositeImage returns True if the image is
% composited. False is returned is there is a memory shortage or if the
% image fails to be composited.
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o resource_info: Specifies a pointer to a X11 MagickXResourceInfo structure.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
% o image: Specifies a pointer to an Image structure; returned from
% ReadImage.
%
*/
static unsigned int MagickXCompositeImage(Display *display,
MagickXResourceInfo *resource_info,MagickXWindows *windows,Image *image)
{
static char
displacement_geometry[MaxTextExtent] = "30x30",
filename[MaxTextExtent] = "\0";
const char
* const CompositeMenu[]=
{
"Operators",
"Dissolve",
"Displace",
"Help",
"Dismiss",
(char *) NULL
};
static CompositeOperator
compose = CopyCompositeOp;
static const ModeType
CompositeCommands[]=
{
CompositeOperatorsCommand,
CompositeDissolveCommand,
CompositeDisplaceCommand,
CompositeHelpCommand,
CompositeDismissCommand
};
char
text[MaxTextExtent];
Cursor
cursor;
double
blend,
scale_factor;
Image
*composite_image;
int
id,
x,
y;
RectangleInfo
highlight_info,
composite_info;
unsigned int
height,
width;
unsigned long
state;
XEvent
event;
/*
Request image file name from user.
*/
MagickXFileBrowserWidget(display,windows,"Composite",filename);
if (*filename == '\0')
return(True);
/*
Read image.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
(void) strlcpy(resource_info->image_info->filename,filename,MaxTextExtent);
composite_image=ReadImage(resource_info->image_info,&image->exception);
if (image->exception.severity != UndefinedException)
MagickError2(image->exception.severity,image->exception.reason,
image->exception.description);
MagickXSetCursorState(display,windows,False);
if (composite_image == (Image *) NULL)
return(False);
if (!composite_image->matte)
{
/*
Request mask image file name from user.
*/
MagickXNoticeWidget(display,windows,
"Your image does not have the required matte information.",
"Press dismiss and choose an image to use as a mask.");
MagickXFileBrowserWidget(display,windows,"Composite",filename);
if (*filename != '\0')
{
char
size[MaxTextExtent];
Image
*mask_image;
ImageInfo
*image_info;
/*
Read image.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
image_info=CloneImageInfo((ImageInfo *) NULL);
(void) strlcpy(image_info->filename,filename,MaxTextExtent);
(void) CloneString(&image_info->size,size);
FormatString(image_info->size,"%lux%lu",composite_image->columns,
composite_image->rows);
mask_image=ReadImage(image_info,&image->exception);
if (image->exception.severity != UndefinedException)
MagickError2(image->exception.severity,image->exception.reason,
image->exception.description);
MagickXSetCursorState(display,windows,False);
if (mask_image == (Image *) NULL)
return(False);
(void) CompositeImage(composite_image,CopyOpacityCompositeOp,
mask_image,0,0);
DestroyImage(mask_image);
DestroyImageInfo(image_info);
}
}
/*
Map Command widget.
*/
(void) CloneString(&windows->command.name,"Composite");
windows->command.data=1;
(void) MagickXCommandWidget(display,windows,CompositeMenu,(XEvent *) NULL);
(void) XMapRaised(display,windows->command.id);
MagickXClientMessage(display,windows->image.id,windows->im_protocols,
windows->im_update_widget,CurrentTime);
/*
Track pointer until button 1 is pressed.
*/
MagickXQueryPosition(display,windows->image.id,&x,&y);
(void) XSelectInput(display,windows->image.id,
windows->image.attributes.event_mask | PointerMotionMask);
composite_info.x=windows->image.x+x;
composite_info.y=windows->image.y+y;
composite_info.width=0;
composite_info.height=0;
cursor=XCreateFontCursor(display,XC_ul_angle);
(void) XSetFunction(display,windows->image.highlight_context,GXinvert);
blend=0.0;
state=DefaultState;
do
{
if (windows->info.mapped)
{
/*
Display pointer position.
*/
FormatString(text," %+ld%+ld ",composite_info.x,composite_info.y);
MagickXInfoWidget(display,windows,text);
}
highlight_info=composite_info;
highlight_info.x=composite_info.x-windows->image.x;
highlight_info.y=composite_info.y-windows->image.y;
MagickXHighlightRectangle(display,windows->image.id,
windows->image.highlight_context,&highlight_info);
/*
Wait for next event.
*/
MagickXScreenEvent(display,windows,&event);
MagickXHighlightRectangle(display,windows->image.id,
windows->image.highlight_context,&highlight_info);
if (event.xany.window == windows->command.id)
{
/*
Select a command from the Command widget.
*/
id=MagickXCommandWidget(display,windows,CompositeMenu,&event);
if (id < 0)
continue;
switch (CompositeCommands[id])
{
case CompositeOperatorsCommand:
{
char
command[MaxTextExtent];
const char
* const OperatorMenu[]=
{
"Over",
"In",
"Out",
"Atop",
"Xor",
"Plus",
"Minus",
"Add",
"Subtract",
"Difference",
"Multiply",
"Bumpmap",
"Copy",
"CopyRed",
"CopyGreen",
"CopyBlue",
"CopyOpacity",
"Clear",
(char *) NULL,
};
/*
Select a command from the pop-up menu.
*/
compose=(CompositeOperator) (MagickXMenuWidget(display,windows,
CompositeMenu[id],OperatorMenu,command)+1);
break;
}
case CompositeDissolveCommand:
{
static char
factor[MaxTextExtent] = "20.0";
/*
Dissolve the two images a given percent.
*/
(void) XSetFunction(display,windows->image.highlight_context,
GXcopy);
(void) MagickXDialogWidget(display,windows,"Dissolve",
"Enter the blend factor (0.0 - 99.9%):",factor);
(void) XSetFunction(display,windows->image.highlight_context,
GXinvert);
if (*factor == '\0')
break;
blend=MagickAtoF(factor);
compose=DissolveCompositeOp;
break;
}
case CompositeDisplaceCommand:
{
/*
Get horizontal and vertical scale displacement geometry.
*/
(void) XSetFunction(display,windows->image.highlight_context,
GXcopy);
(void) MagickXDialogWidget(display,windows,"Displace",
"Enter the horizontal and vertical scale:",displacement_geometry);
(void) XSetFunction(display,windows->image.highlight_context,
GXinvert);
if (*displacement_geometry == '\0')
break;
compose=DisplaceCompositeOp;
break;
}
case CompositeHelpCommand:
{
(void) XSetFunction(display,windows->image.highlight_context,
GXcopy);
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Image Composite",
ImageCompositeHelp,
sizeof(ImageCompositeHelp));
(void) XSetFunction(display,windows->image.highlight_context,
GXinvert);
break;
}
case CompositeDismissCommand:
{
/*
Prematurely exit.
*/
state|=EscapeState;
state|=ExitState;
break;
}
default:
break;
}
continue;
}
switch (event.type)
{
case ButtonPress:
{
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),
"Button Press: 0x%lx %u +%d+%d",event.xbutton.window,
event.xbutton.button,event.xbutton.x,event.xbutton.y);
if (event.xbutton.button != Button1)
break;
if (event.xbutton.window != windows->image.id)
break;
/*
Change cursor.
*/
composite_info.width=composite_image->columns;
composite_info.height=composite_image->rows;
(void) XDefineCursor(display,windows->image.id,cursor);
composite_info.x=windows->image.x+event.xbutton.x;
composite_info.y=windows->image.y+event.xbutton.y;
break;
}
case ButtonRelease:
{
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),
"Button Release: 0x%lx %u +%d+%d",event.xbutton.window,
event.xbutton.button,event.xbutton.x,event.xbutton.y);
if (event.xbutton.button != Button1)
break;
if (event.xbutton.window != windows->image.id)
break;
if ((composite_info.width != 0) && (composite_info.height != 0))
{
/*
User has selected the location of the composite image.
*/
composite_info.x=windows->image.x+event.xbutton.x;
composite_info.y=windows->image.y+event.xbutton.y;
state|=ExitState;
}
break;
}
case Expose:
break;
case KeyPress:
{
char
command[MaxTextExtent];
KeySym
key_symbol;
int
length;
if (event.xkey.window != windows->image.id)
break;
/*
Respond to a user key press.
*/
length=XLookupString((XKeyEvent *) &event.xkey,command,sizeof(command),
&key_symbol,(XComposeStatus *) NULL);
*(command+length)='\0';
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),
"Key press: 0x%lx (%.1024s)",key_symbol,command);
switch ((int) key_symbol)
{
case XK_Escape:
case XK_F20:
{
/*
Prematurely exit.
*/
DestroyImage(composite_image);
state|=EscapeState;
state|=ExitState;
break;
}
case XK_F1:
case XK_Help:
{
(void) XSetFunction(display,windows->image.highlight_context,
GXcopy);
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Image Composite",
ImageCompositeHelp,
sizeof(ImageCompositeHelp));
(void) XSetFunction(display,windows->image.highlight_context,
GXinvert);
break;
}
default:
{
(void) XBell(display,0);
break;
}
}
break;
}
case MotionNotify:
{
/*
Map and unmap Info widget as text cursor crosses its boundaries.
*/
x=event.xmotion.x;
y=event.xmotion.y;
if (windows->info.mapped)
{
if ((x < (int) (windows->info.x+windows->info.width)) &&
(y < (int) (windows->info.y+windows->info.height)))
(void) XWithdrawWindow(display,windows->info.id,
windows->info.screen);
}
else
if ((x > (int) (windows->info.x+windows->info.width)) ||
(y > (int) (windows->info.y+windows->info.height)))
(void) XMapWindow(display,windows->info.id);
composite_info.x=windows->image.x+x;
composite_info.y=windows->image.y+y;
break;
}
default:
{
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),"Event type: %d",
event.type);
break;
}
}
} while (!(state & ExitState));
(void) XSelectInput(display,windows->image.id,
windows->image.attributes.event_mask);
(void) XSetFunction(display,windows->image.highlight_context,GXcopy);
MagickXSetCursorState(display,windows,False);
(void) XFreeCursor(display,cursor);
if (state & EscapeState)
return(True);
/*
Image compositing is relative to image configuration.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
width=(unsigned int) image->columns;
height=(unsigned int) image->rows;
x=0;
y=0;
if (windows->image.crop_geometry != (char *) NULL)
(void) XParseGeometry(windows->image.crop_geometry,&x,&y,&width,&height);
scale_factor=(double) width/windows->image.ximage->width;
composite_info.x+=x;
composite_info.x=(int) (scale_factor*composite_info.x+0.5);
composite_info.width=(unsigned int) (scale_factor*composite_info.width+0.5);
scale_factor=(double) height/windows->image.ximage->height;
composite_info.y+=y;
composite_info.y=(int) (scale_factor*composite_info.y+0.5);
composite_info.height=(unsigned int) (scale_factor*composite_info.height+0.5);
if ((composite_info.width != composite_image->columns) ||
(composite_info.height != composite_image->rows))
{
Image
*resize_image;
/*
Scale composite image.
*/
resize_image=ZoomImage(composite_image,composite_info.width,
composite_info.height,&image->exception);
DestroyImage(composite_image);
if (resize_image == (Image *) NULL)
{
MagickXSetCursorState(display,windows,False);
return(False);
}
composite_image=resize_image;
}
if (compose == DisplaceCompositeOp)
composite_image->geometry=displacement_geometry;
if (blend != 0.0)
{
int
y;
Quantum
opacity;
register int
x;
register PixelPacket
*q;
/*
Create mattes for blending.
*/
SetImageOpacity(composite_image,OpaqueOpacity);
opacity=(Quantum) (ScaleQuantumToChar(MaxRGB)-
((long) ScaleQuantumToChar(MaxRGB)*blend)/100);
(void) SetImageType(image,TrueColorMatteType);
for (y=0; y < (long) image->rows; y++)
{
q=GetImagePixels(image,0,y,image->columns,1);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (int) image->columns; x++)
{
q->opacity=opacity;
q++;
}
if (!SyncImagePixels(image))
break;
}
}
/*
Composite image with X Image window.
*/
(void) CompositeImage(image,compose,composite_image,composite_info.x,
composite_info.y);
DestroyImage(composite_image);
MagickXSetCursorState(display,windows,False);
/*
Update image configuration.
*/
MagickXConfigureImageColormap(display,resource_info,windows,image);
(void) MagickXConfigureImage(display,resource_info,windows,image);
return(True);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X C o n f i g u r e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXConfigureImage creates a new X image. It also notifies the
% window manager of the new image size and configures the transient widows.
%
% The format of the MagickXConfigureImage method is:
%
% unsigned int MagickXConfigureImage(Display *display,
% MagickXResourceInfo *resource_info,MagickXWindows *windows,Image *image)
%
% A description of each parameter follows:
%
% o status: Method MagickXConfigureImage returns True if the window is
% resized. False is returned is there is a memory shortage or if the
% window fails to resize.
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o resource_info: Specifies a pointer to a X11 MagickXResourceInfo structure.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
% o image: Specifies a pointer to an Image structure; returned from
% ReadImage.
%
%
*/
static unsigned int MagickXConfigureImage(Display *display,
MagickXResourceInfo *resource_info,MagickXWindows *windows,Image *image)
{
char
geometry[MaxTextExtent];
long
x,
y;
unsigned int
mask,
status;
unsigned long
height,
width;
XSizeHints
*size_hints;
XWindowChanges
window_changes;
/*
Dismiss if window dimensions are zero.
*/
width=windows->image.window_changes.width;
height=windows->image.window_changes.height;
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),
"Configure Image: %dx%d=>%lux%lu",windows->image.ximage->width,
windows->image.ximage->height,width,height);
if ((width*height) == 0)
return(True);
x=0;
y=0;
/*
Display hourglass cursor if progress indication enabled.
*/
if (resource_info->image_info->progress)
MagickXSetCursorState(display,windows,True);
/*
Resize image to fit Image window dimensions.
*/
(void) XFlush(display);
if (((int) width != windows->image.ximage->width) ||
((int) height != windows->image.ximage->height))
image->taint=True;
windows->magnify.x=(unsigned int)
width*windows->magnify.x/windows->image.ximage->width;
windows->magnify.y=(unsigned int)
height*windows->magnify.y/windows->image.ximage->height;
windows->image.x=(int) (width*windows->image.x/windows->image.ximage->width);
windows->image.y=(int)
(height*windows->image.y/windows->image.ximage->height);
status=MagickXMakeImage(display,resource_info,&windows->image,image,
(unsigned int) width,(unsigned int) height);
if (status == False)
MagickXNoticeWidget(display,windows,"Unable to configure X image:",
windows->image.name);
/*
Notify window manager of the new configuration.
*/
FormatString(geometry,"%ux%u+0+0>!",
XDisplayWidth(display,windows->image.screen),
XDisplayHeight(display,windows->image.screen));
(void) GetMagickGeometry(geometry,&x,&y,&width,&height);
window_changes.width=(unsigned int) width;
window_changes.height=(unsigned int) height;
mask=CWWidth | CWHeight;
if (resource_info->backdrop)
{
mask|=CWX | CWY;
window_changes.x=(int)
((XDisplayWidth(display,windows->image.screen)/2)-(width/2));
window_changes.y=(int)
((XDisplayHeight(display,windows->image.screen)/2)-(height/2));
}
(void) XReconfigureWMWindow(display,windows->image.id,windows->image.screen,
mask,&window_changes);
(void) XClearWindow(display,windows->image.id);
MagickXRefreshWindow(display,&windows->image,(XEvent *) NULL);
/*
Update Magnify window configuration.
*/
if (windows->magnify.mapped)
MagickXMakeMagnifyImage(display,windows);
/*
Update pan window configuration.
*/
windows->pan.crop_geometry=windows->image.crop_geometry;
MagickXBestIconSize(display,&windows->pan,image);
while ((windows->pan.width < MaxIconSize) &&
(windows->pan.height < MaxIconSize))
{
windows->pan.width<<=1;
windows->pan.height<<=1;
}
if (windows->pan.geometry != (char *) NULL)
(void) XParseGeometry(windows->pan.geometry,&windows->pan.x,&windows->pan.y,
&windows->pan.width,&windows->pan.height);
window_changes.width=windows->pan.width;
window_changes.height=windows->pan.height;
size_hints=XAllocSizeHints();
if (size_hints != (XSizeHints *) NULL)
{
/*
Set new size hints.
*/
size_hints->flags=PSize | PMinSize | PMaxSize;
size_hints->width=window_changes.width;
size_hints->height=window_changes.height;
size_hints->min_width=size_hints->width;
size_hints->min_height=size_hints->height;
size_hints->max_width=size_hints->width;
size_hints->max_height=size_hints->height;
(void) XSetNormalHints(display,windows->pan.id,size_hints);
(void) XFree((void *) size_hints);
}
(void) XReconfigureWMWindow(display,windows->pan.id,windows->pan.screen,
CWWidth | CWHeight,&window_changes);
if (windows->pan.mapped)
MagickXMakePanImage(display,resource_info,windows,image);
/*
Update icon window configuration.
*/
windows->icon.crop_geometry=windows->image.crop_geometry;
MagickXBestIconSize(display,&windows->icon,image);
window_changes.width=windows->icon.width;
window_changes.height=windows->icon.height;
(void) XReconfigureWMWindow(display,windows->icon.id,windows->icon.screen,
CWWidth | CWHeight,&window_changes);
MagickXSetCursorState(display,windows,False);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X C r o p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXCropImage allows the user to select a region of the image and
% crop, copy, or cut it. For copy or cut, the image can subsequently be
% composited onto the image with MagickXPasteImage.
%
% The format of the MagickXCropImage method is:
%
% unsigned int MagickXCropImage(Display *display,MagickXResourceInfo *resource_info,
% MagickXWindows *windows,Image *image,const ClipboardMode mode)
%
% A description of each parameter follows:
%
% o status: Method MagickXCropImage returns True if the image is
% copied. False is returned is there is a memory shortage or if the
% image fails to be copied.
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o resource_info: Specifies a pointer to a X11 MagickXResourceInfo structure.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
% o image: Specifies a pointer to an Image structure; returned from
% ReadImage.
%
% o mode: This unsigned value specified whether the image should be
% cropped, copied, or cut.
%
%
*/
static unsigned int MagickXCropImage(Display *display,MagickXResourceInfo *resource_info,
MagickXWindows *windows,Image *image,const ClipboardMode mode)
{
const char
* const CropModeMenu[]=
{
"Help",
"Dismiss",
(char *) NULL
},
* RectifyModeMenu[]=
{
"Crop",
"Help",
"Dismiss",
(char *) NULL
};
static const ModeType
CropCommands[]=
{
CropHelpCommand,
CropDismissCommand
},
RectifyCommands[]=
{
RectifyCopyCommand,
RectifyHelpCommand,
RectifyDismissCommand
};
char
command[MaxTextExtent],
text[MaxTextExtent];
Cursor
cursor;
double
scale_factor;
int
id,
x,
y;
KeySym
key_symbol;
Image
*crop_image;
RectangleInfo
crop_info,
highlight_info;
register PixelPacket
*q;
unsigned int
height,
width;
unsigned long
state;
XEvent
event;
/*
Map Command widget.
*/
switch (mode)
{
case CopyMode:
{
(void) CloneString(&windows->command.name,"Copy");
break;
}
case CropMode:
{
(void) CloneString(&windows->command.name,"Crop");
break;
}
case CutMode:
{
(void) CloneString(&windows->command.name,"Cut");
break;
}
}
RectifyModeMenu[0]=windows->command.name;
windows->command.data=0;
(void) MagickXCommandWidget(display,windows,CropModeMenu,(XEvent *) NULL);
(void) XMapRaised(display,windows->command.id);
MagickXClientMessage(display,windows->image.id,windows->im_protocols,
windows->im_update_widget,CurrentTime);
/*
Track pointer until button 1 is pressed.
*/
MagickXQueryPosition(display,windows->image.id,&x,&y);
(void) XSelectInput(display,windows->image.id,
windows->image.attributes.event_mask | PointerMotionMask);
crop_info.x=windows->image.x+x;
crop_info.y=windows->image.y+y;
crop_info.width=0;
crop_info.height=0;
cursor=XCreateFontCursor(display,XC_fleur);
state=DefaultState;
do
{
if (windows->info.mapped)
{
/*
Display pointer position.
*/
FormatString(text," %+ld%+ld ",crop_info.x,crop_info.y);
MagickXInfoWidget(display,windows,text);
}
/*
Wait for next event.
*/
MagickXScreenEvent(display,windows,&event);
if (event.xany.window == windows->command.id)
{
/*
Select a command from the Command widget.
*/
id=MagickXCommandWidget(display,windows,CropModeMenu,&event);
if (id < 0)
continue;
switch (CropCommands[id])
{
case CropHelpCommand:
{
switch (mode)
{
case CopyMode:
{
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Image Copy",
ImageCopyHelp,
sizeof(ImageCopyHelp));
break;
}
case CropMode:
{
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Image Crop",
ImageCropHelp,
sizeof(ImageCropHelp));
break;
}
case CutMode:
{
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Image Cut",
ImageCutHelp,
sizeof(ImageCutHelp));
break;
}
}
break;
}
case CropDismissCommand:
{
/*
Prematurely exit.
*/
state|=EscapeState;
state|=ExitState;
break;
}
default:
break;
}
continue;
}
switch (event.type)
{
case ButtonPress:
{
if (event.xbutton.button != Button1)
break;
if (event.xbutton.window != windows->image.id)
break;
/*
Note first corner of cropping rectangle-- exit loop.
*/
(void) XDefineCursor(display,windows->image.id,cursor);
crop_info.x=windows->image.x+event.xbutton.x;
crop_info.y=windows->image.y+event.xbutton.y;
state|=ExitState;
break;
}
case ButtonRelease:
break;
case Expose:
break;
case KeyPress:
{
if (event.xkey.window != windows->image.id)
break;
/*
Respond to a user key press.
*/
(void) XLookupString((XKeyEvent *) &event.xkey,command,sizeof(command),
&key_symbol,(XComposeStatus *) NULL);
switch ((int) key_symbol)
{
case XK_Escape:
case XK_F20:
{
/*
Prematurely exit.
*/
state|=EscapeState;
state|=ExitState;
break;
}
case XK_F1:
case XK_Help:
{
switch (mode)
{
case CopyMode:
{
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Image Copy",
ImageCopyHelp,
sizeof(ImageCopyHelp));
break;
}
case CropMode:
{
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Image Crop",
ImageCropHelp,
sizeof(ImageCropHelp));
break;
}
case CutMode:
{
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Image Cut",
ImageCutHelp,
sizeof(ImageCutHelp));
break;
}
}
break;
}
default:
{
(void) XBell(display,0);
break;
}
}
break;
}
case MotionNotify:
{
/*
Map and unmap Info widget as text cursor crosses its boundaries.
*/
x=event.xmotion.x;
y=event.xmotion.y;
if (windows->info.mapped)
{
if ((x < (int) (windows->info.x+windows->info.width)) &&
(y < (int) (windows->info.y+windows->info.height)))
(void) XWithdrawWindow(display,windows->info.id,
windows->info.screen);
}
else
if ((x > (int) (windows->info.x+windows->info.width)) ||
(y > (int) (windows->info.y+windows->info.height)))
(void) XMapWindow(display,windows->info.id);
crop_info.x=windows->image.x+x;
crop_info.y=windows->image.y+y;
break;
}
default:
break;
}
} while (!(state & ExitState));
(void) XSelectInput(display,windows->image.id,
windows->image.attributes.event_mask);
if (state & EscapeState)
{
/*
User want to exit without cropping.
*/
(void) XWithdrawWindow(display,windows->info.id,windows->info.screen);
(void) XFreeCursor(display,cursor);
return(True);
}
(void) XSetFunction(display,windows->image.highlight_context,GXinvert);
do
{
/*
Size rectangle as pointer moves until the mouse button is released.
*/
x=(int) crop_info.x;
y=(int) crop_info.y;
crop_info.width=0;
crop_info.height=0;
state=DefaultState;
do
{
highlight_info=crop_info;
highlight_info.x=crop_info.x-windows->image.x;
highlight_info.y=crop_info.y-windows->image.y;
if ((highlight_info.width > 3) && (highlight_info.height > 3))
{
/*
Display info and draw cropping rectangle.
*/
if (!windows->info.mapped)
(void) XMapWindow(display,windows->info.id);
FormatString(text," %lux%lu%+ld%+ld",crop_info.width,crop_info.height,
crop_info.x,crop_info.y);
MagickXInfoWidget(display,windows,text);
MagickXHighlightRectangle(display,windows->image.id,
windows->image.highlight_context,&highlight_info);
}
else
if (windows->info.mapped)
(void) XWithdrawWindow(display,windows->info.id,windows->info.screen);
/*
Wait for next event.
*/
MagickXScreenEvent(display,windows,&event);
if ((highlight_info.width > 3) && (highlight_info.height > 3))
MagickXHighlightRectangle(display,windows->image.id,
windows->image.highlight_context,&highlight_info);
switch (event.type)
{
case ButtonPress:
{
crop_info.x=windows->image.x+event.xbutton.x;
crop_info.y=windows->image.y+event.xbutton.y;
break;
}
case ButtonRelease:
{
/*
User has committed to cropping rectangle.
*/
crop_info.x=windows->image.x+event.xbutton.x;
crop_info.y=windows->image.y+event.xbutton.y;
MagickXSetCursorState(display,windows,False);
state|=ExitState;
if (LocaleCompare(windows->command.name,"Rectify") == 0)
break;
(void) CloneString(&windows->command.name,"Rectify");
windows->command.data=0;
(void) MagickXCommandWidget(display,windows,RectifyModeMenu,
(XEvent *) NULL);
break;
}
case Expose:
break;
case MotionNotify:
{
crop_info.x=windows->image.x+event.xmotion.x;
crop_info.y=windows->image.y+event.xmotion.y;
}
default:
break;
}
if ((((int) crop_info.x != x) && ((int) crop_info.y != y)) ||
(state & ExitState))
{
/*
Check boundary conditions.
*/
if (crop_info.x < 0)
crop_info.x=0;
else
if (crop_info.x > (int) windows->image.ximage->width)
crop_info.x=windows->image.ximage->width;
if ((int) crop_info.x < x)
crop_info.width=(unsigned int) (x-crop_info.x);
else
{
crop_info.width=(unsigned int) (crop_info.x-x);
crop_info.x=x;
}
if (crop_info.y < 0)
crop_info.y=0;
else
if (crop_info.y > (int) windows->image.ximage->height)
crop_info.y=windows->image.ximage->height;
if ((int) crop_info.y < y)
crop_info.height=(unsigned int) (y-crop_info.y);
else
{
crop_info.height=(unsigned int) (crop_info.y-y);
crop_info.y=y;
}
}
} while (!(state & ExitState));
/*
Wait for user to grab a corner of the rectangle or press return.
*/
state=DefaultState;
do
{
if (windows->info.mapped)
{
/*
Display pointer position.
*/
FormatString(text," %lux%lu%+ld%+ld",crop_info.width,crop_info.height,
crop_info.x,crop_info.y);
MagickXInfoWidget(display,windows,text);
}
highlight_info=crop_info;
highlight_info.x=crop_info.x-windows->image.x;
highlight_info.y=crop_info.y-windows->image.y;
if ((highlight_info.width <= 3) || (highlight_info.height <= 3))
{
state|=EscapeState;
state|=ExitState;
break;
}
MagickXHighlightRectangle(display,windows->image.id,
windows->image.highlight_context,&highlight_info);
MagickXScreenEvent(display,windows,&event);
if (event.xany.window == windows->command.id)
{
/*
Select a command from the Command widget.
*/
(void) XSetFunction(display,windows->image.highlight_context,GXcopy);
id=MagickXCommandWidget(display,windows,RectifyModeMenu,&event);
(void) XSetFunction(display,windows->image.highlight_context,
GXinvert);
MagickXHighlightRectangle(display,windows->image.id,
windows->image.highlight_context,&highlight_info);
if (id >= 0)
switch (RectifyCommands[id])
{
case RectifyCopyCommand:
{
state|=ExitState;
break;
}
case RectifyHelpCommand:
{
(void) XSetFunction(display,windows->image.highlight_context,
GXcopy);
switch (mode)
{
case CopyMode:
{
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Image Copy",
ImageCopyHelp,
sizeof(ImageCopyHelp));
break;
}
case CropMode:
{
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Image Crop",
ImageCropHelp,
sizeof(ImageCropHelp));
break;
}
case CutMode:
{
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Image Cut",
ImageCutHelp,
sizeof(ImageCutHelp));
break;
}
}
(void) XSetFunction(display,windows->image.highlight_context,
GXinvert);
break;
}
case RectifyDismissCommand:
{
/*
Prematurely exit.
*/
state|=EscapeState;
state|=ExitState;
break;
}
default:
break;
}
continue;
}
MagickXHighlightRectangle(display,windows->image.id,
windows->image.highlight_context,&highlight_info);
switch (event.type)
{
case ButtonPress:
{
if (event.xbutton.button != Button1)
break;
if (event.xbutton.window != windows->image.id)
break;
x=windows->image.x+event.xbutton.x;
y=windows->image.y+event.xbutton.y;
if ((x < (int) (crop_info.x+RoiDelta)) &&
(x > (int) (crop_info.x-RoiDelta)) &&
(y < (int) (crop_info.y+RoiDelta)) &&
(y > (int) (crop_info.y-RoiDelta)))
{
crop_info.x=(long) (crop_info.x+crop_info.width);
crop_info.y=(long) (crop_info.y+crop_info.height);
state|=UpdateConfigurationState;
break;
}
if ((x < (int) (crop_info.x+RoiDelta)) &&
(x > (int) (crop_info.x-RoiDelta)) &&
(y < (int) (crop_info.y+crop_info.height+RoiDelta)) &&
(y > (int) (crop_info.y+crop_info.height-RoiDelta)))
{
crop_info.x=(long) (crop_info.x+crop_info.width);
state|=UpdateConfigurationState;
break;
}
if ((x < (int) (crop_info.x+crop_info.width+RoiDelta)) &&
(x > (int) (crop_info.x+crop_info.width-RoiDelta)) &&
(y < (int) (crop_info.y+RoiDelta)) &&
(y > (int) (crop_info.y-RoiDelta)))
{
crop_info.y=(long) (crop_info.y+crop_info.height);
state|=UpdateConfigurationState;
break;
}
if ((x < (int) (crop_info.x+crop_info.width+RoiDelta)) &&
(x > (int) (crop_info.x+crop_info.width-RoiDelta)) &&
(y < (int) (crop_info.y+crop_info.height+RoiDelta)) &&
(y > (int) (crop_info.y+crop_info.height-RoiDelta)))
{
state|=UpdateConfigurationState;
break;
}
break;
}
case ButtonRelease:
{
if (event.xbutton.window == windows->pan.id)
if ((highlight_info.x != crop_info.x-windows->image.x) ||
(highlight_info.y != crop_info.y-windows->image.y))
MagickXHighlightRectangle(display,windows->image.id,
windows->image.highlight_context,&highlight_info);
break;
}
case Expose:
{
if (event.xexpose.window == windows->image.id)
if (event.xexpose.count == 0)
{
event.xexpose.x=(int) highlight_info.x;
event.xexpose.y=(int) highlight_info.y;
event.xexpose.width=(unsigned int) highlight_info.width;
event.xexpose.height=(unsigned int) highlight_info.height;
MagickXRefreshWindow(display,&windows->image,&event);
}
if (event.xexpose.window == windows->info.id)
if (event.xexpose.count == 0)
MagickXInfoWidget(display,windows,text);
break;
}
case KeyPress:
{
if (event.xkey.window != windows->image.id)
break;
/*
Respond to a user key press.
*/
(void) XLookupString((XKeyEvent *) &event.xkey,command,
sizeof(command),&key_symbol,(XComposeStatus *) NULL);
switch ((int) key_symbol)
{
case XK_Escape:
case XK_F20:
{
state|=EscapeState;
break;
}
case XK_Return:
{
state|=ExitState;
break;
}
case XK_F1:
case XK_Help:
{
(void) XSetFunction(display,windows->image.highlight_context,
GXcopy);
switch (mode)
{
case CopyMode:
{
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Image Copy",
ImageCopyHelp,
sizeof(ImageCopyHelp));
break;
}
case CropMode:
{
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Image Cropg",
ImageCropHelp,
sizeof(ImageCropHelp));
break;
}
case CutMode:
{
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Image Cutg",
ImageCutHelp,
sizeof(ImageCutHelp));
break;
}
}
(void) XSetFunction(display,windows->image.highlight_context,
GXinvert);
break;
}
default:
{
(void) XBell(display,0);
break;
}
}
break;
}
case KeyRelease:
break;
case MotionNotify:
{
/*
Map and unmap Info widget as text cursor crosses its boundaries.
*/
x=event.xmotion.x;
y=event.xmotion.y;
if (windows->info.mapped)
{
if ((x < (int) (windows->info.x+windows->info.width)) &&
(y < (int) (windows->info.y+windows->info.height)))
(void) XWithdrawWindow(display,windows->info.id,
windows->info.screen);
}
else
if ((x > (int) (windows->info.x+windows->info.width)) ||
(y > (int) (windows->info.y+windows->info.height)))
(void) XMapWindow(display,windows->info.id);
break;
}
default:
break;
}
if (state & UpdateConfigurationState)
{
(void) XPutBackEvent(display,&event);
(void) XDefineCursor(display,windows->image.id,cursor);
break;
}
} while (!(state & ExitState));
} while (!(state & ExitState));
(void) XSetFunction(display,windows->image.highlight_context,GXcopy);
MagickXSetCursorState(display,windows,False);
if (state & EscapeState)
return(True);
if (mode == CropMode)
if (((int) crop_info.width != windows->image.ximage->width) ||
((int) crop_info.height != windows->image.ximage->height))
{
/*
Reconfigure Image window as defined by cropping rectangle.
*/
MagickXSetCropGeometry(display,windows,&crop_info,image);
windows->image.window_changes.width=(unsigned int) crop_info.width;
windows->image.window_changes.height=(unsigned int) crop_info.height;
(void) MagickXConfigureImage(display,resource_info,windows,image);
return(True);
}
/*
Copy image before applying image transforms.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
width=(unsigned int) image->columns;
height=(unsigned int) image->rows;
x=0;
y=0;
if (windows->image.crop_geometry != (char *) NULL)
(void) XParseGeometry(windows->image.crop_geometry,&x,&y,&width,&height);
scale_factor=(double) width/windows->image.ximage->width;
crop_info.x+=x;
crop_info.x=(int) (scale_factor*crop_info.x+0.5);
crop_info.width=(unsigned int) (scale_factor*crop_info.width+0.5);
scale_factor=(double) height/windows->image.ximage->height;
crop_info.y+=y;
crop_info.y=(int) (scale_factor*crop_info.y+0.5);
crop_info.height=(unsigned int) (scale_factor*crop_info.height+0.5);
crop_image=CropImage(image,&crop_info,&image->exception);
MagickXSetCursorState(display,windows,False);
if (crop_image == (Image *) NULL)
return(False);
if (resource_info->copy_image != (Image *) NULL)
DestroyImage(resource_info->copy_image);
resource_info->copy_image=crop_image;
if (mode == CopyMode)
{
(void) MagickXConfigureImage(display,resource_info,windows,image);
return(True);
}
/*
Cut image.
*/
(void) SetImageType(image,TrueColorMatteType);
for (y=0; y < (long) crop_info.height; y++)
{
q=GetImagePixels(image,crop_info.x,y+crop_info.y,crop_info.width,1);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (int) crop_info.width; x++)
{
q->opacity=TransparentOpacity;
q++;
}
if (!SyncImagePixels(image))
break;
}
/*
Update image configuration.
*/
MagickXConfigureImageColormap(display,resource_info,windows,image);
(void) MagickXConfigureImage(display,resource_info,windows,image);
return(True);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X D r a w I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXDrawEditImage draws a graphic element (point, line, rectangle,
% etc.) on the image.
%
% The format of the MagickXDrawEditImage method is:
%
% unsigned int MagickXDrawEditImage(Display *display,
% MagickXResourceInfo *resource_info,MagickXWindows *windows,Image **image)
%
% A description of each parameter follows:
%
% o status: Method MagickXDrawEditImage return True if the image is drawn
% upon. False is returned is there is a memory shortage or if the
% image cannot be drawn on.
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o resource_info: Specifies a pointer to a X11 MagickXResourceInfo structure.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
% o image: Specifies a pointer to an Image structure; returned from
% ReadImage.
%
%
*/
static unsigned int MagickXDrawEditImage(Display *display,
MagickXResourceInfo *resource_info,MagickXWindows *windows,Image **image)
{
const char
* const DrawMenu[]=
{
"Element",
"Color",
"Stipple",
"Width",
"Undo",
"Help",
"Dismiss",
(char *) NULL
};
static ElementType
element = PointElement;
static const ModeType
DrawCommands[]=
{
DrawElementCommand,
DrawColorCommand,
DrawStippleCommand,
DrawWidthCommand,
DrawUndoCommand,
DrawHelpCommand,
DrawDismissCommand
};
static Pixmap
stipple = (Pixmap) NULL;
static unsigned int
pen_id = 0,
line_width = 1;
char
command[MaxTextExtent],
text[MaxTextExtent];
Cursor
cursor;
double
degrees;
int
entry,
id,
number_coordinates,
x,
y;
RectangleInfo
rectangle_info;
register int
i;
unsigned int
distance,
height,
max_coordinates,
status,
width;
unsigned long
state;
Window
root_window;
MagickXDrawInfo
draw_info;
XEvent
event;
XPoint
*coordinate_info;
XSegment
line_info;
/*
Allocate polygon info.
*/
max_coordinates=2048;
coordinate_info=MagickAllocateMemory(XPoint *,max_coordinates*sizeof(XPoint));
if (coordinate_info == (XPoint *) NULL)
{
MagickError3(ResourceLimitError,MemoryAllocationFailed,
UnableToDrawOnImage);
return(False);
}
/*
Map Command widget.
*/
(void) CloneString(&windows->command.name,"Draw");
windows->command.data=4;
(void) MagickXCommandWidget(display,windows,DrawMenu,(XEvent *) NULL);
(void) XMapRaised(display,windows->command.id);
MagickXClientMessage(display,windows->image.id,windows->im_protocols,
windows->im_update_widget,CurrentTime);
/*
Wait for first button press.
*/
root_window=XRootWindow(display,XDefaultScreen(display));
draw_info.stencil=OpaqueStencil;
status=True;
cursor=XCreateFontCursor(display,XC_tcross);
for ( ; ; )
{
MagickXQueryPosition(display,windows->image.id,&x,&y);
(void) XSelectInput(display,windows->image.id,
windows->image.attributes.event_mask | PointerMotionMask);
(void) XDefineCursor(display,windows->image.id,cursor);
state=DefaultState;
do
{
if (windows->info.mapped)
{
/*
Display pointer position.
*/
FormatString(text," %+d%+d ",x+windows->image.x,y+windows->image.y);
MagickXInfoWidget(display,windows,text);
}
/*
Wait for next event.
*/
MagickXScreenEvent(display,windows,&event);
if (event.xany.window == windows->command.id)
{
/*
Select a command from the Command widget.
*/
id=MagickXCommandWidget(display,windows,DrawMenu,&event);
if (id < 0)
continue;
switch (DrawCommands[id])
{
case DrawElementCommand:
{
const char
* const Elements[]=
{
"point",
"line",
"rectangle",
"fill rectangle",
"circle",
"fill circle",
"ellipse",
"fill ellipse",
"polygon",
"fill polygon",
(char *) NULL,
};
/*
Select a command from the pop-up menu.
*/
element=(ElementType) (MagickXMenuWidget(display,windows,
DrawMenu[id],Elements,command)+1);
break;
}
case DrawColorCommand:
{
char
*ColorMenu[MaxNumberPens+1];
int
pen_number;
unsigned int
transparent;
XColor
color;
/*
Initialize menu selections.
*/
for (i=0; i < (int) (MaxNumberPens-2); i++)
ColorMenu[i]=resource_info->pen_colors[i];
ColorMenu[MaxNumberPens-2]=(char *) "transparent";
ColorMenu[MaxNumberPens-1]=(char *) "Browser...";
ColorMenu[MaxNumberPens]=(char *) NULL;
/*
Select a pen color from the pop-up menu.
*/
pen_number=MagickXMenuWidget(display,windows,DrawMenu[id],
(const char **) ColorMenu,command);
if (pen_number < 0)
break;
transparent=pen_number == (MaxNumberPens-2);
if (transparent)
{
draw_info.stencil=TransparentStencil;
break;
}
if (pen_number == (MaxNumberPens-1))
{
static char
color_name[MaxTextExtent] = "gray";
/*
Select a pen color from a dialog.
*/
resource_info->pen_colors[pen_number]=color_name;
MagickXColorBrowserWidget(display,windows,"Select",color_name);
if (*color_name == '\0')
break;
}
/*
Set pen color.
*/
(void) XParseColor(display,windows->map_info->colormap,
resource_info->pen_colors[pen_number],&color);
MagickXBestPixel(display,windows->map_info->colormap,(XColor *) NULL,
(unsigned int) MaxColors,&color);
windows->pixel_info->pen_colors[pen_number]=color;
pen_id=pen_number;
draw_info.stencil=OpaqueStencil;
break;
}
case DrawStippleCommand:
{
Image
*stipple_image;
ImageInfo
*image_info;
static char
filename[MaxTextExtent] = "\0";
const char
* const StipplesMenu[]=
{
"Brick",
"Diagonal",
"Scales",
"Vertical",
"Wavy",
"Translucent",
"Opaque",
"Open...",
(char *) NULL,
};
/*
Select a command from the pop-up menu.
*/
entry=MagickXMenuWidget(display,windows,DrawMenu[id],StipplesMenu,
command);
if (entry < 0)
break;
if (stipple != (Pixmap) NULL)
(void) XFreePixmap(display,stipple);
stipple=(Pixmap) NULL;
if (entry == 6)
break;
if (entry != 7)
{
switch (entry)
{
case 0:
{
stipple=XCreateBitmapFromData(display,root_window,
(char *) BricksBitmap,BricksWidth,BricksHeight);
break;
}
case 1:
{
stipple=XCreateBitmapFromData(display,root_window,
(char *) DiagonalBitmap,DiagonalWidth,DiagonalHeight);
break;
}
case 2:
{
stipple=XCreateBitmapFromData(display,root_window,
(char *) ScalesBitmap,ScalesWidth,ScalesHeight);
break;
}
case 3:
{
stipple=XCreateBitmapFromData(display,root_window,
(char *) VerticalBitmap,VerticalWidth,VerticalHeight);
break;
}
case 4:
{
stipple=XCreateBitmapFromData(display,root_window,
(char *) WavyBitmap,WavyWidth,WavyHeight);
break;
}
case 5:
default:
{
stipple=XCreateBitmapFromData(display,root_window,
(char *) HighlightBitmap,HighlightWidth,
HighlightHeight);
break;
}
}
break;
}
MagickXFileBrowserWidget(display,windows,"Stipple",filename);
if (*filename == '\0')
break;
/*
Read image.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
image_info=CloneImageInfo((ImageInfo *) NULL);
(void) strlcpy(image_info->filename,filename,MaxTextExtent);
stipple_image=ReadImage(image_info,&(*image)->exception);
if ((*image)->exception.severity != UndefinedException)
MagickError2((*image)->exception.severity,
(*image)->exception.reason,(*image)->exception.description);
MagickXSetCursorState(display,windows,False);
if (stipple_image == (Image *) NULL)
break;
if (!AcquireTemporaryFileName(filename))
{
MagickXNoticeWidget(display,windows,
"Unable to open temporary file:",filename);
break;
}
FormatString(stipple_image->filename,"xbm:%.1024s",filename);
(void) WriteImage(image_info,stipple_image);
DestroyImage(stipple_image);
DestroyImageInfo(image_info);
status=XReadBitmapFile(display,root_window,filename,&width,
&height,&stipple,&x,&y);
(void) LiberateTemporaryFile(filename);
if (status != BitmapSuccess)
MagickXNoticeWidget(display,windows,"Unable to read X bitmap image:",
filename);
break;
}
case DrawWidthCommand:
{
static char
width[MaxTextExtent] = "0";
const char
* const WidthsMenu[]=
{
"1",
"2",
"4",
"8",
"16",
"Dialog...",
(char *) NULL,
};
/*
Select a command from the pop-up menu.
*/
entry=MagickXMenuWidget(display,windows,DrawMenu[id],WidthsMenu,
command);
if (entry < 0)
break;
if (entry != 5)
{
line_width=MagickAtoI(WidthsMenu[entry]);
break;
}
(void) MagickXDialogWidget(display,windows,"Ok","Enter line width:",
width);
if (*width == '\0')
break;
line_width=MagickAtoI(width);
break;
}
case DrawUndoCommand:
{
(void) MagickXMagickCommand(display,resource_info,windows,UndoCommand,
image);
break;
}
case DrawHelpCommand:
{
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Image Rotation",
ImageDrawHelp,
sizeof(ImageDrawHelp));
(void) XDefineCursor(display,windows->image.id,cursor);
break;
}
case DrawDismissCommand:
{
/*
Prematurely exit.
*/
state|=EscapeState;
state|=ExitState;
break;
}
default:
break;
}
(void) XDefineCursor(display,windows->image.id,cursor);
continue;
}
switch (event.type)
{
case ButtonPress:
{
if (event.xbutton.button != Button1)
break;
if (event.xbutton.window != windows->image.id)
break;
/*
Exit loop.
*/
x=event.xbutton.x;
y=event.xbutton.y;
state|=ExitState;
break;
}
case ButtonRelease:
break;
case Expose:
break;
case KeyPress:
{
KeySym
key_symbol;
if (event.xkey.window != windows->image.id)
break;
/*
Respond to a user key press.
*/
(void) XLookupString((XKeyEvent *) &event.xkey,command,
sizeof(command),&key_symbol,(XComposeStatus *) NULL);
switch ((int) key_symbol)
{
case XK_Escape:
case XK_F20:
{
/*
Prematurely exit.
*/
state|=EscapeState;
state|=ExitState;
break;
}
case XK_F1:
case XK_Help:
{
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Image Rotation",
ImageDrawHelp,
sizeof(ImageDrawHelp));
break;
}
default:
{
(void) XBell(display,0);
break;
}
}
break;
}
case MotionNotify:
{
/*
Map and unmap Info widget as text cursor crosses its boundaries.
*/
x=event.xmotion.x;
y=event.xmotion.y;
if (windows->info.mapped)
{
if ((x < (int) (windows->info.x+windows->info.width)) &&
(y < (int) (windows->info.y+windows->info.height)))
(void) XWithdrawWindow(display,windows->info.id,
windows->info.screen);
}
else
if ((x > (int) (windows->info.x+windows->info.width)) ||
(y > (int) (windows->info.y+windows->info.height)))
(void) XMapWindow(display,windows->info.id);
break;
}
}
} while (!(state & ExitState));
(void) XSelectInput(display,windows->image.id,
windows->image.attributes.event_mask);
(void) XWithdrawWindow(display,windows->info.id,windows->info.screen);
if (state & EscapeState)
break;
/*
Draw element as pointer moves until the button is released.
*/
distance=0;
degrees=0.0;
line_info.x1=x;
line_info.y1=y;
line_info.x2=x;
line_info.y2=y;
rectangle_info.x=x;
rectangle_info.y=y;
rectangle_info.width=0;
rectangle_info.height=0;
number_coordinates=1;
coordinate_info->x=x;
coordinate_info->y=y;
(void) XSetFunction(display,windows->image.highlight_context,GXinvert);
state=DefaultState;
do
{
switch (element)
{
case PointElement:
default:
{
if (number_coordinates > 1)
{
(void) XDrawLines(display,windows->image.id,
windows->image.highlight_context,coordinate_info,
number_coordinates,CoordModeOrigin);
FormatString(text," %+d%+d",
coordinate_info[number_coordinates-1].x,
coordinate_info[number_coordinates-1].y);
MagickXInfoWidget(display,windows,text);
}
break;
}
case LineElement:
{
if (distance > 9)
{
/*
Display angle of the line.
*/
degrees=RadiansToDegrees(-atan2((double) (line_info.y2-
line_info.y1),(double) (line_info.x2-line_info.x1)));
FormatString(text," %.2f",degrees);
MagickXInfoWidget(display,windows,text);
MagickXHighlightLine(display,windows->image.id,
windows->image.highlight_context,&line_info);
}
else
if (windows->info.mapped)
(void) XWithdrawWindow(display,windows->info.id,
windows->info.screen);
break;
}
case RectangleElement:
case FillRectangleElement:
{
if ((rectangle_info.width > 3) && (rectangle_info.height > 3))
{
/*
Display info and draw drawing rectangle.
*/
FormatString(text," %lux%lu%+ld%+ld",rectangle_info.width,
rectangle_info.height,rectangle_info.x,rectangle_info.y);
MagickXInfoWidget(display,windows,text);
MagickXHighlightRectangle(display,windows->image.id,
windows->image.highlight_context,&rectangle_info);
}
else
if (windows->info.mapped)
(void) XWithdrawWindow(display,windows->info.id,
windows->info.screen);
break;
}
case CircleElement:
case FillCircleElement:
case EllipseElement:
case FillEllipseElement:
{
if ((rectangle_info.width > 3) && (rectangle_info.height > 3))
{
/*
Display info and draw drawing rectangle.
*/
FormatString(text," %lux%lu%+ld%+ld",rectangle_info.width,
rectangle_info.height,rectangle_info.x,rectangle_info.y);
MagickXInfoWidget(display,windows,text);
MagickXHighlightEllipse(display,windows->image.id,
windows->image.highlight_context,&rectangle_info);
}
else
if (windows->info.mapped)
(void) XWithdrawWindow(display,windows->info.id,
windows->info.screen);
break;
}
case PolygonElement:
case FillPolygonElement:
{
if (number_coordinates > 1)
(void) XDrawLines(display,windows->image.id,
windows->image.highlight_context,coordinate_info,
number_coordinates,CoordModeOrigin);
if (distance > 9)
{
/*
Display angle of the line.
*/
degrees=RadiansToDegrees(-atan2((double) (line_info.y2-
line_info.y1),(double) (line_info.x2-line_info.x1)));
FormatString(text," %.2f",degrees);
MagickXInfoWidget(display,windows,text);
MagickXHighlightLine(display,windows->image.id,
windows->image.highlight_context,&line_info);
}
else
if (windows->info.mapped)
(void) XWithdrawWindow(display,windows->info.id,
windows->info.screen);
break;
}
}
/*
Wait for next event.
*/
MagickXScreenEvent(display,windows,&event);
switch (element)
{
case PointElement:
default:
{
if (number_coordinates > 1)
(void) XDrawLines(display,windows->image.id,
windows->image.highlight_context,coordinate_info,
number_coordinates,CoordModeOrigin);
break;
}
case LineElement:
{
if (distance > 9)
MagickXHighlightLine(display,windows->image.id,
windows->image.highlight_context,&line_info);
break;
}
case RectangleElement:
case FillRectangleElement:
{
if ((rectangle_info.width > 3) && (rectangle_info.height > 3))
MagickXHighlightRectangle(display,windows->image.id,
windows->image.highlight_context,&rectangle_info);
break;
}
case CircleElement:
case FillCircleElement:
case EllipseElement:
case FillEllipseElement:
{
if ((rectangle_info.width > 3) && (rectangle_info.height > 3))
MagickXHighlightEllipse(display,windows->image.id,
windows->image.highlight_context,&rectangle_info);
break;
}
case PolygonElement:
case FillPolygonElement:
{
if (number_coordinates > 1)
(void) XDrawLines(display,windows->image.id,
windows->image.highlight_context,coordinate_info,
number_coordinates,CoordModeOrigin);
if (distance > 9)
MagickXHighlightLine(display,windows->image.id,
windows->image.highlight_context,&line_info);
break;
}
}
switch (event.type)
{
case ButtonPress:
break;
case ButtonRelease:
{
/*
User has committed to element.
*/
line_info.x2=event.xbutton.x;
line_info.y2=event.xbutton.y;
rectangle_info.x=event.xbutton.x;
rectangle_info.y=event.xbutton.y;
coordinate_info[number_coordinates].x=event.xbutton.x;
coordinate_info[number_coordinates].y=event.xbutton.y;
if (((element != PolygonElement) &&
(element != FillPolygonElement)) || (distance <= 9))
{
state|=ExitState;
break;
}
number_coordinates++;
if (number_coordinates < (int) max_coordinates)
{
line_info.x1=event.xbutton.x;
line_info.y1=event.xbutton.y;
break;
}
max_coordinates<<=1;
MagickReallocMemory(XPoint *,coordinate_info,
max_coordinates*sizeof(XPoint));
if (coordinate_info == (XPoint *) NULL)
MagickError3(ResourceLimitError,MemoryAllocationFailed,
UnableToDrawOnImage);
break;
}
case Expose:
break;
case MotionNotify:
{
if (event.xmotion.window != windows->image.id)
break;
if (element != PointElement)
{
line_info.x2=event.xmotion.x;
line_info.y2=event.xmotion.y;
rectangle_info.x=event.xmotion.x;
rectangle_info.y=event.xmotion.y;
break;
}
coordinate_info[number_coordinates].x=event.xbutton.x;
coordinate_info[number_coordinates].y=event.xbutton.y;
number_coordinates++;
if (number_coordinates < (int) max_coordinates)
break;
max_coordinates<<=1;
MagickReallocMemory(XPoint *,coordinate_info,
max_coordinates*sizeof(XPoint));
if (coordinate_info == (XPoint *) NULL)
MagickError3(ResourceLimitError,MemoryAllocationFailed,
UnableToDrawOnImage);
break;
}
default:
break;
}
/*
Check boundary conditions.
*/
if (line_info.x2 < 0)
line_info.x2=0;
else
if (line_info.x2 > (int) windows->image.width)
line_info.x2=windows->image.width;
if (line_info.y2 < 0)
line_info.y2=0;
else
if (line_info.y2 > (int) windows->image.height)
line_info.y2=windows->image.height;
distance=
((line_info.x2-line_info.x1+1)*(line_info.x2-line_info.x1+1))+
((line_info.y2-line_info.y1+1)*(line_info.y2-line_info.y1+1));
if ((((int) rectangle_info.x != x) && ((int) rectangle_info.y != y)) ||
(state & ExitState))
{
if (rectangle_info.x < 0)
rectangle_info.x=0;
else
if (rectangle_info.x > (int) windows->image.width)
rectangle_info.x=(long) windows->image.width;
if ((int) rectangle_info.x < x)
rectangle_info.width=(unsigned int) (x-rectangle_info.x);
else
{
rectangle_info.width=(unsigned int) (rectangle_info.x-x);
rectangle_info.x=x;
}
if (rectangle_info.y < 0)
rectangle_info.y=0;
else
if (rectangle_info.y > (int) windows->image.height)
rectangle_info.y=(long) windows->image.height;
if ((int) rectangle_info.y < y)
rectangle_info.height=(unsigned int) (y-rectangle_info.y);
else
{
rectangle_info.height=(unsigned int) (rectangle_info.y-y);
rectangle_info.y=y;
}
}
} while (!(state & ExitState));
(void) XSetFunction(display,windows->image.highlight_context,GXcopy);
if ((element == PointElement) || (element == PolygonElement) ||
(element == FillPolygonElement))
{
/*
Determine polygon bounding box.
*/
rectangle_info.x=coordinate_info->x;
rectangle_info.y=coordinate_info->y;
x=coordinate_info->x;
y=coordinate_info->y;
for (i=1; i < number_coordinates; i++)
{
if (coordinate_info[i].x > x)
x=coordinate_info[i].x;
if (coordinate_info[i].y > y)
y=coordinate_info[i].y;
if (coordinate_info[i].x < rectangle_info.x)
rectangle_info.x=Max(coordinate_info[i].x,0);
if (coordinate_info[i].y < rectangle_info.y)
rectangle_info.y=Max(coordinate_info[i].y,0);
}
rectangle_info.width=x-rectangle_info.x;
rectangle_info.height=y-rectangle_info.y;
for (i=0; i < number_coordinates; i++)
{
coordinate_info[i].x-=rectangle_info.x;
coordinate_info[i].y-=rectangle_info.y;
}
}
else
if (distance <= 9)
continue;
else
if ((element == RectangleElement) ||
(element == CircleElement) || (element == EllipseElement))
{
rectangle_info.width--;
rectangle_info.height--;
}
/*
Drawing is relative to image configuration.
*/
draw_info.x=(int) rectangle_info.x;
draw_info.y=(int) rectangle_info.y;
(void) MagickXMagickCommand(display,resource_info,windows,SaveToUndoBufferCommand,
image);
width=(unsigned int) (*image)->columns;
height=(unsigned int) (*image)->rows;
x=0;
y=0;
if (windows->image.crop_geometry != (char *) NULL)
(void) XParseGeometry(windows->image.crop_geometry,&x,&y,&width,&height);
draw_info.x+=windows->image.x-(line_width/2);
if (draw_info.x < 0)
draw_info.x=0;
draw_info.x=width*draw_info.x/windows->image.ximage->width;
draw_info.y+=windows->image.y-(line_width/2);
if (draw_info.y < 0)
draw_info.y=0;
draw_info.y=height*draw_info.y/windows->image.ximage->height;
draw_info.width=(unsigned int) rectangle_info.width+(line_width << 1);
if (draw_info.width > (unsigned int) (*image)->columns)
draw_info.width=(unsigned int) (*image)->columns;
draw_info.height=(unsigned int) rectangle_info.height+(line_width << 1);
if (draw_info.height > (unsigned int) (*image)->rows)
draw_info.height=(unsigned int) (*image)->rows;
FormatString(draw_info.geometry,"%ux%u%+d%+d",
width*draw_info.width/windows->image.ximage->width,
height*draw_info.height/windows->image.ximage->height,
draw_info.x+x,draw_info.y+y);
/*
Initialize drawing attributes.
*/
draw_info.degrees=0.0;
draw_info.element=element;
draw_info.stipple=stipple;
draw_info.line_width=line_width;
draw_info.line_info=line_info;
if (line_info.x1 > (int) (line_width/2))
draw_info.line_info.x1=line_width/2;
if (line_info.y1 > (int) (line_width/2))
draw_info.line_info.y1=line_width/2;
draw_info.line_info.x2=line_info.x2-line_info.x1+(line_width/2);
draw_info.line_info.y2=line_info.y2-line_info.y1+(line_width/2);
if ((draw_info.line_info.x2 < 0) && (draw_info.line_info.y2 < 0))
{
draw_info.line_info.x2=(-draw_info.line_info.x2);
draw_info.line_info.y2=(-draw_info.line_info.y2);
}
if (draw_info.line_info.x2 < 0)
{
draw_info.line_info.x2=(-draw_info.line_info.x2);
Swap(draw_info.line_info.x1,draw_info.line_info.x2);
}
if (draw_info.line_info.y2 < 0)
{
draw_info.line_info.y2=(-draw_info.line_info.y2);
Swap(draw_info.line_info.y1,draw_info.line_info.y2);
}
draw_info.rectangle_info=rectangle_info;
if (draw_info.rectangle_info.x > (int) (line_width/2))
draw_info.rectangle_info.x=(long) line_width/2;
if (draw_info.rectangle_info.y > (int) (line_width/2))
draw_info.rectangle_info.y=(long) line_width/2;
draw_info.number_coordinates=number_coordinates;
draw_info.coordinate_info=coordinate_info;
windows->pixel_info->pen_color=windows->pixel_info->pen_colors[pen_id];
/*
Draw element on image.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
status=MagickXDrawImage(display,windows->pixel_info,&draw_info,*image);
MagickXSetCursorState(display,windows,False);
/*
Update image colormap and return to image drawing.
*/
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
}
MagickXSetCursorState(display,windows,False);
MagickFreeMemory(coordinate_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X D r a w P a n R e c t a n g l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXDrawPanRectangle draws a rectangle in the pan window. The pan
% window displays a zoom image and the rectangle shows which portion of
% the image is displayed in the Image window.
%
% The format of the MagickXDrawPanRectangle method is:
%
% MagickXDrawPanRectangle(Display *display,MagickXWindows *windows)
%
% A description of each parameter follows:
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
%
*/
static void MagickXDrawPanRectangle(Display *display,MagickXWindows *windows)
{
double
scale_factor;
RectangleInfo
highlight_info;
/*
Determine dimensions of the panning rectangle.
*/
scale_factor=(double) windows->pan.width/windows->image.ximage->width;
highlight_info.x=(int) (scale_factor*windows->image.x+0.5);
highlight_info.width=(unsigned int) (scale_factor*windows->image.width+0.5);
scale_factor=(double) windows->pan.height/windows->image.ximage->height;
highlight_info.y=(int) (scale_factor*windows->image.y+0.5);
highlight_info.height=(unsigned int) (scale_factor*windows->image.height+0.5);
/*
Display the panning rectangle.
*/
(void) XClearWindow(display,windows->pan.id);
MagickXHighlightRectangle(display,windows->pan.id,windows->pan.annotate_context,
&highlight_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X I m a g e C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXImageCache handles the creation, manipulation, and destruction of
% the image cache (undo and redo buffers).
%
% The format of the MagickXImageCache method is:
%
% void MagickXImageCache(Display *display,MagickXResourceInfo *resource_info,
% MagickXWindows *windows,const CommandType command,Image **image)
%
% A description of each parameter follows:
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o resource_info: Specifies a pointer to a X11 MagickXResourceInfo structure.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
% o command: Specifies a command to perform.
%
% o image: Specifies a pointer to an Image structure; MagickXImageCache
% may transform the image and return a new image pointer.
%
%
*/
static void MagickXImageCache(Display *display,MagickXResourceInfo *resource_info,
MagickXWindows *windows,const CommandType command,Image **image)
{
Image
*cache_image;
static Image
*redo_image = (Image *) NULL,
*undo_image = (Image *) NULL;
switch (command)
{
case FreeBuffersCommand:
{
/*
Free memory from the undo and redo cache.
*/
while (undo_image != (Image *) NULL)
{
cache_image=undo_image;
undo_image=undo_image->previous;
DestroyImage(cache_image->list);
DestroyImage(cache_image);
}
undo_image=(Image *) NULL;
if (redo_image != (Image *) NULL)
DestroyImage(redo_image);
redo_image=(Image *) NULL;
return;
}
case UndoCommand:
{
/*
Undo the last image transformation.
*/
if (undo_image == (Image *) NULL)
{
(void) XBell(display,0);
return;
}
cache_image=undo_image;
undo_image=undo_image->previous;
windows->image.window_changes.width=(unsigned int) cache_image->columns;
windows->image.window_changes.height=(unsigned int) cache_image->rows;
if (windows->image.crop_geometry != (char *) NULL)
MagickFreeMemory(windows->image.crop_geometry);
windows->image.crop_geometry=cache_image->geometry;
if (redo_image != (Image *) NULL)
DestroyImage(redo_image);
redo_image=(*image);
*image=cache_image->list;
DestroyImage(cache_image);
if (windows->image.orphan)
return;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
return;
}
case CutCommand:
case PasteCommand:
case ApplyCommand:
case HalfSizeCommand:
case OriginalSizeCommand:
case DoubleSizeCommand:
case ResizeCommand:
case TrimCommand:
case CropCommand:
case ChopCommand:
case FlipCommand:
case FlopCommand:
case RotateRightCommand:
case RotateLeftCommand:
case RotateCommand:
case ShearCommand:
case RollCommand:
case NegateCommand:
case EqualizeCommand:
case NormalizeCommand:
case HueCommand:
case SaturationCommand:
case BrightnessCommand:
case GammaCommand:
case SpiffCommand:
case DullCommand:
case GrayscaleCommand:
case MapCommand:
case QuantizeCommand:
case DespeckleCommand:
case EmbossCommand:
case ReduceNoiseCommand:
case AddNoiseCommand:
case SharpenCommand:
case BlurCommand:
case ThresholdCommand:
case EdgeDetectCommand:
case SpreadCommand:
case ShadeCommand:
case RaiseCommand:
case SegmentCommand:
case SolarizeCommand:
case SwirlCommand:
case ImplodeCommand:
case WaveCommand:
case OilPaintCommand:
case CharcoalDrawCommand:
case AnnotateCommand:
case AddBorderCommand:
case AddFrameCommand:
case CompositeCommand:
case CommentCommand:
case LaunchCommand:
case RegionofInterestCommand:
case SaveToUndoBufferCommand:
case RedoCommand:
{
Image
*previous_image;
long
bytes;
bytes=(long) ((*image)->columns*(*image)->rows*sizeof(PixelPacket));
if (undo_image != (Image *) NULL)
{
/*
Ensure the undo stash.has enough memory available.
*/
previous_image=undo_image;
while (previous_image != (Image *) NULL)
{
bytes+=previous_image->list->columns*previous_image->list->rows*
sizeof(PixelPacket);
if (bytes <= (long) (resource_info->undo_cache << 20))
{
previous_image=previous_image->previous;
continue;
}
bytes-=previous_image->list->columns*previous_image->list->rows*
sizeof(PixelPacket);
if (previous_image == undo_image)
undo_image=(Image *) NULL;
else
previous_image->next->previous=(Image *) NULL;
break;
}
while (previous_image != (Image *) NULL)
{
/*
Delete any excess memory from undo cache.
*/
cache_image=previous_image;
previous_image=previous_image->previous;
DestroyImage(cache_image->list);
DestroyImage(cache_image);
}
}
if (bytes > (long) (resource_info->undo_cache << 20))
break;
/*
Save image before transformations are applied.
*/
cache_image=AllocateImage((ImageInfo *) NULL);
if (cache_image == (Image *) NULL)
break;
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
cache_image->list=CloneImage(*image,0,0,True,&(*image)->exception);
MagickXSetCursorState(display,windows,False);
if (cache_image->list == (Image *) NULL)
{
DestroyImage(cache_image);
break;
}
cache_image->columns=windows->image.ximage->width;
cache_image->rows=windows->image.ximage->height;
cache_image->geometry=windows->image.crop_geometry;
if (windows->image.crop_geometry != (char *) NULL)
{
cache_image->geometry=AllocateString((char *) NULL);
(void) strlcpy(cache_image->geometry,windows->image.crop_geometry,
MaxTextExtent);
}
if (undo_image == (Image *) NULL)
{
undo_image=cache_image;
break;
}
undo_image->next=cache_image;
undo_image->next->previous=undo_image;
undo_image=undo_image->next;
break;
}
default:
break;
}
if (command == RedoCommand)
{
/*
Redo the last image transformation.
*/
if (redo_image == (Image *) NULL)
{
(void) XBell(display,0);
return;
}
windows->image.window_changes.width=(unsigned int) redo_image->columns;
windows->image.window_changes.height=(unsigned int) redo_image->rows;
if (windows->image.crop_geometry != (char *) NULL)
MagickFreeMemory(windows->image.crop_geometry);
windows->image.crop_geometry=redo_image->geometry;
DestroyImage(*image);
*image=redo_image;
redo_image=(Image *) NULL;
if (windows->image.orphan)
return;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
return;
}
if (command != InfoCommand)
return;
/*
Display image info.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
MagickXDisplayImageInfo(display,resource_info,windows,undo_image,*image);
MagickXSetCursorState(display,windows,False);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X I m a g e W i n d o w C o m m a n d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXImageWindowCommand makes a transform to the image or Image window
% as specified by a user menu button or keyboard command.
%
% The format of the MagickXMagickCommand method is:
%
% CommandType MagickXImageWindowCommand(Display *display,
% MagickXResourceInfo *resource_info,MagickXWindows *windows,
% const unsigned int state,KeySym key_symbol,Image **image)
%
% A description of each parameter follows:
%
% o nexus: Method MagickXImageWindowCommand returns an image when the
% user chooses 'Open Image' from the command menu. Otherwise a null
% image is returned.
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o resource_info: Specifies a pointer to a X11 MagickXResourceInfo structure.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
% o state: key mask.
%
% o key_symbol: Specifies a command to perform.
%
% o image: Specifies a pointer to an Image structure; XImageWIndowCommand
% may transform the image and return a new image pointer.
%
%
*/
static CommandType MagickXImageWindowCommand(Display *display,
MagickXResourceInfo *resource_info,MagickXWindows *windows,const unsigned int state,
KeySym key_symbol,Image **image)
{
static char
delta[MaxTextExtent] = "";
static const char
Digits[] = "01234567890";
static KeySym
last_symbol = XK_0;
if ((key_symbol >= XK_0) && (key_symbol <= XK_9))
{
if (!((last_symbol >= XK_0) && (last_symbol <= XK_9)))
{
*delta='\0';
resource_info->quantum=1;
}
last_symbol=key_symbol;
delta[strlen(delta)+1]='\0';
delta[strlen(delta)]=Digits[key_symbol-XK_0];
resource_info->quantum=MagickAtoI(delta);
return(NullCommand);
}
last_symbol=key_symbol;
if (resource_info->immutable)
{
/*
Immutable image window has a restricted command set.
*/
switch(key_symbol)
{
case XK_question:
return(InfoCommand);
case XK_p:
case XK_Print:
return(PrintCommand);
case XK_space:
return(NextCommand);
case XK_q:
{
if (!(state & ControlMask))
break;
return(QuitCommand);
}
default:
break;
}
return(NullCommand);
}
switch ((int) key_symbol)
{
case XK_o:
{
if (!(state & ControlMask))
break;
return(OpenCommand);
}
case XK_space:
return(NextCommand);
case XK_BackSpace:
return(FormerCommand);
case XK_s:
{
if (state & Mod1Mask)
return(SwirlCommand);
if (!(state & ControlMask))
return(ShearCommand);
return(SaveCommand);
}
case XK_p:
case XK_Print:
{
if (state & Mod1Mask)
return(OilPaintCommand);
if (state & Mod4Mask)
return(ColorCommand);
if (!(state & ControlMask))
return(NullCommand);
return(PrintCommand);
}
case XK_d:
{
if (state & Mod4Mask)
return(DrawCommand);
if (!(state & ControlMask))
return(NullCommand);
return(DeleteCommand);
}
case XK_Select:
{
if (!(state & ControlMask))
return(NullCommand);
return(SelectCommand);
}
case XK_n:
{
if (!(state & ControlMask))
return(NullCommand);
return(NewCommand);
}
case XK_q:
case XK_Cancel:
{
if (!(state & ControlMask))
return(NullCommand);
return(QuitCommand);
}
case XK_z:
case XK_Undo:
{
if (!(state & ControlMask))
return(NullCommand);
return(UndoCommand);
}
case XK_r:
case XK_Redo:
{
if (!(state & ControlMask))
return(RollCommand);
return(RedoCommand);
}
case XK_x:
{
if (!(state & ControlMask))
return(NullCommand);
return(CutCommand);
}
case XK_c:
{
if (state & Mod1Mask)
return(CharcoalDrawCommand);
if (!(state & ControlMask))
return(CropCommand);
return(CopyCommand);
}
case XK_v:
case XK_Insert:
{
if (state & Mod4Mask)
return(CompositeCommand);
if (!(state & ControlMask))
return(FlipCommand);
return(PasteCommand);
}
case XK_less:
return(HalfSizeCommand);
case XK_minus:
return(OriginalSizeCommand);
case XK_greater:
return(DoubleSizeCommand);
case XK_percent:
return(ResizeCommand);
case XK_at:
return(RefreshCommand);
case XK_bracketleft:
return(ChopCommand);
case XK_h:
return(FlopCommand);
case XK_slash:
return(RotateRightCommand);
case XK_backslash:
return(RotateLeftCommand);
case XK_asterisk:
return(RotateCommand);
case XK_t:
return(TrimCommand);
case XK_H:
return(HueCommand);
case XK_S:
return(SaturationCommand);
case XK_L:
return(BrightnessCommand);
case XK_G:
return(GammaCommand);
case XK_C:
return(SpiffCommand);
case XK_Z:
return(DullCommand);
case XK_equal:
return(EqualizeCommand);
case XK_N:
return(NormalizeCommand);
case XK_asciitilde:
return(NegateCommand);
case XK_period:
return(GrayscaleCommand);
case XK_numbersign:
return(QuantizeCommand);
case XK_F2:
return(DespeckleCommand);
case XK_F3:
return(EmbossCommand);
case XK_F4:
return(ReduceNoiseCommand);
case XK_F5:
return(AddNoiseCommand);
case XK_F6:
return(SharpenCommand);
case XK_F7:
return(BlurCommand);
case XK_F8:
return(ThresholdCommand);
case XK_F9:
return(EdgeDetectCommand);
case XK_F10:
return(SpreadCommand);
case XK_F11:
return(ShadeCommand);
case XK_F12:
return(RaiseCommand);
case XK_F13:
return(SegmentCommand);
case XK_i:
{
if (!(state & Mod1Mask))
return(NullCommand);
return(ImplodeCommand);
}
case XK_w:
{
if (!(state & Mod1Mask))
return(NullCommand);
return(WaveCommand);
}
case XK_m:
{
if (!(state & Mod4Mask))
return(NullCommand);
return(MatteCommand);
}
case XK_b:
{
if (!(state & Mod4Mask))
return(NullCommand);
return(AddBorderCommand);
}
case XK_f:
{
if (!(state & Mod4Mask))
return(NullCommand);
return(AddFrameCommand);
}
case XK_exclam:
{
if (!(state & Mod4Mask))
return(NullCommand);
return(CommentCommand);
}
case XK_a:
{
if (state & Mod1Mask)
return(ApplyCommand);
if (state & Mod4Mask)
return(AnnotateCommand);
if (!(state & ControlMask))
return(NullCommand);
return(RegionofInterestCommand);
}
case XK_question:
return(InfoCommand);
case XK_plus:
return(ZoomCommand);
case XK_P:
{
if (!(state & ShiftMask))
return(NullCommand);
return(ShowPreviewCommand);
}
case XK_Execute:
return(LaunchCommand);
case XK_F1:
return(HelpCommand);
case XK_Find:
return(BrowseDocumentationCommand);
case XK_Menu:
{
(void) XMapRaised(display,windows->command.id);
return(NullCommand);
}
case XK_Next:
case XK_Prior:
case XK_Home:
case XK_KP_Home:
{
MagickXTranslateImage(display,windows,*image,key_symbol);
return(NullCommand);
}
case XK_Up:
case XK_KP_Up:
case XK_Down:
case XK_KP_Down:
case XK_Left:
case XK_KP_Left:
case XK_Right:
case XK_KP_Right:
{
if (state & Mod1Mask)
{
RectangleInfo
crop_info;
/*
Trim one pixel from edge of image.
*/
crop_info.x=0;
crop_info.y=0;
crop_info.width=windows->image.ximage->width;
crop_info.height=windows->image.ximage->height;
if ((key_symbol == XK_Up) || (key_symbol == XK_KP_Up))
{
if (resource_info->quantum >= (int) crop_info.height)
resource_info->quantum=(unsigned int) crop_info.height-1;
crop_info.height-=resource_info->quantum;
}
if ((key_symbol == XK_Down) || (key_symbol == XK_KP_Down))
{
if (resource_info->quantum >= (int) (crop_info.height-crop_info.y))
resource_info->quantum=(unsigned int)
(crop_info.height-crop_info.y-1);
crop_info.y+=resource_info->quantum;
crop_info.height-=resource_info->quantum;
}
if ((key_symbol == XK_Left) || (key_symbol == XK_KP_Left))
{
if (resource_info->quantum >= (int) crop_info.width)
resource_info->quantum=(int) crop_info.width-1;
crop_info.width-=resource_info->quantum;
}
if ((key_symbol == XK_Right) || (key_symbol == XK_KP_Right))
{
if (resource_info->quantum >= (int) (crop_info.width-crop_info.x))
resource_info->quantum=(unsigned int)
(crop_info.width-crop_info.x-1);
crop_info.x+=resource_info->quantum;
crop_info.width-=resource_info->quantum;
}
if ((int) (windows->image.x+windows->image.width) >
(int) crop_info.width)
windows->image.x=(int) (crop_info.width-windows->image.width);
if ((int) (windows->image.y+windows->image.height) >
(int) crop_info.height)
windows->image.y=(int) (crop_info.height-windows->image.height);
MagickXSetCropGeometry(display,windows,&crop_info,*image);
windows->image.window_changes.width=(unsigned int) crop_info.width;
windows->image.window_changes.height=(unsigned int) crop_info.height;
(void) XSetWindowBackgroundPixmap(display,windows->image.id,None);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
return(NullCommand);
}
MagickXTranslateImage(display,windows,*image,key_symbol);
return(NullCommand);
}
default:
return(NullCommand);
}
return(NullCommand);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X M a g i c k C o m m a n d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXMagickCommand makes a transform to the image or Image window
% as specified by a user menu button or keyboard command.
%
% The format of the MagickXMagickCommand method is:
%
% Image *MagickXMagickCommand(Display *display,MagickXResourceInfo *resource_info,
% MagickXWindows *windows,const CommandType command,Image **image)
%
% A description of each parameter follows:
%
% o nexus: Method MagickXMagickCommand returns an image when the
% user chooses 'Load Image' from the command menu. Otherwise a null
% image is returned.
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o resource_info: Specifies a pointer to a X11 MagickXResourceInfo structure.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
% o command: Specifies a command to perform.
%
% o image: Specifies a pointer to an Image structure; MagickXMagickCommand
% may transform the image and return a new image pointer.
%
%
*/
#define ReplaceImage(oldimage,func) \
{ \
Image \
*temporary_image; \
\
temporary_image=func; \
if (temporary_image) \
{ \
DestroyImage(oldimage); \
oldimage=temporary_image; \
} \
}
static Image *MagickXMagickCommand(Display *display,MagickXResourceInfo *resource_info,
MagickXWindows *windows,const CommandType command,Image **image)
{
char
/* *argv[10], */
filename[MaxTextExtent],
geometry[MaxTextExtent],
modulate_factors[MaxTextExtent];
Image
*nexus;
ImageInfo
*image_info;
RectangleInfo
rectangle;
int
status,
x,
y;
static char
color[MaxTextExtent] = "gray";
unsigned int
height,
width;
/*
Process user command.
*/
MagickXCheckRefreshWindows(display,windows);
MagickXImageCache(display,resource_info,windows,command,image);
/* argv[0]=resource_info->client_name; */
nexus=(Image *) NULL;
windows->image.window_changes.width=windows->image.ximage->width;
windows->image.window_changes.height=windows->image.ximage->height;
image_info=CloneImageInfo((ImageInfo *) NULL);
switch (command)
{
case OpenCommand:
{
/*
Load image.
*/
nexus=MagickXOpenImage(display,resource_info,windows,False);
break;
}
case NextCommand:
{
/*
Display next image.
*/
MagickXClientMessage(display,windows->image.id,windows->im_protocols,
windows->im_next_image,CurrentTime);
break;
}
case FormerCommand:
{
/*
Display former image.
*/
MagickXClientMessage(display,windows->image.id,windows->im_protocols,
windows->im_former_image,CurrentTime);
break;
}
case SelectCommand:
{
/*
Select image.
*/
if ((strlen(resource_info->home_directory) > 0) &&
(chdir(resource_info->home_directory) != 0))
{
MagickXNoticeWidget(display,windows,"Unable to restore directory:",
resource_info->home_directory);
MagickFatalError(ConfigureFatalError,UnableToRestoreCurrentDirectory,
resource_info->home_directory);
}
nexus=MagickXOpenImage(display,resource_info,windows,True);
break;
}
case SaveCommand:
{
/*
Save image.
*/
status=MagickXSaveImage(display,resource_info,windows,*image);
if (status == MagickFail)
{
char reason[MaxTextExtent];
FormatString(reason,"%s \"%s\"",
(*image)->exception.reason ? (*image)->exception.reason : "",
(*image)->exception.description ? (*image)->exception.description : "");
MagickXNoticeWidget(display,windows,"Unable to save file:",reason);
break;
}
break;
}
case PrintCommand:
{
/*
Print image.
*/
status=MagickXPrintImage(display,resource_info,windows,*image);
if (status == False)
{
char reason[MaxTextExtent];
FormatString(reason,"%s \"%s\"",
(*image)->exception.reason ? (*image)->exception.reason : "",
(*image)->exception.description ? (*image)->exception.description : "");
MagickXNoticeWidget(display,windows,"Unable to print image:",reason);
break;
}
break;
}
case DeleteCommand:
{
static char
filename[MaxTextExtent] = "\0";
/*
Delete image file.
*/
MagickXFileBrowserWidget(display,windows,"Delete",filename);
if (*filename == '\0')
break;
status=remove(filename);
if (status != False)
MagickXNoticeWidget(display,windows,"Unable to delete image file:",filename);
break;
}
case NewCommand:
{
static char
*format = (char *) "gradient",
color[MaxTextExtent] = "gray",
geometry[MaxTextExtent] = "640x480";
/*
Query user for canvas geometry.
*/
status=MagickXDialogWidget(display,windows,"New","Enter image geometry:",
geometry);
if (*geometry == '\0')
break;
if (!status)
format=(char *) "xc";
MagickXColorBrowserWidget(display,windows,"Select",color);
if (*color == '\0')
break;
/*
Create canvas.
*/
FormatString(image_info->filename,"%.1024s:%.1024s",format,color);
(void) CloneString(&image_info->size,geometry);
nexus=ReadImage(image_info,&(*image)->exception);
if ((*image)->exception.severity != UndefinedException)
MagickError2((*image)->exception.severity,(*image)->exception.reason,
(*image)->exception.description);
MagickXClientMessage(display,windows->image.id,windows->im_protocols,
windows->im_next_image,CurrentTime);
break;
}
case VisualDirectoryCommand:
{
/*
Visual Image directory.
*/
nexus=MagickXVisualDirectoryImage(display,resource_info,windows);
break;
}
case QuitCommand:
{
/*
Exit program.
*/
if (!resource_info->confirm_exit)
MagickXClientMessage(display,windows->image.id,windows->im_protocols,
windows->im_exit,CurrentTime);
else
{
/*
Confirm program exit.
*/
status=MagickXConfirmWidget(display,windows,"Do you really want to exit",
resource_info->client_name);
if (status > 0)
MagickXClientMessage(display,windows->image.id,windows->im_protocols,
windows->im_exit,CurrentTime);
}
break;
}
case CutCommand:
{
/*
Cut image.
*/
(void) MagickXCropImage(display,resource_info,windows,*image,CutMode);
break;
}
case CopyCommand:
{
/*
Copy image.
*/
(void) MagickXCropImage(display,resource_info,windows,*image,CopyMode);
break;
}
case PasteCommand:
{
/*
Paste image.
*/
status=MagickXPasteImage(display,resource_info,windows,*image);
if (status == False)
{
MagickXNoticeWidget(display,windows,"Unable to paste X image",
(*image)->filename);
break;
}
break;
}
case HalfSizeCommand:
{
/*
Half image size.
*/
windows->image.window_changes.width=windows->image.ximage->width/2;
windows->image.window_changes.height=windows->image.ximage->height/2;
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case OriginalSizeCommand:
{
/*
Original image size.
*/
windows->image.window_changes.width=(unsigned int) (*image)->columns;
windows->image.window_changes.height=(unsigned int) (*image)->rows;
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case DoubleSizeCommand:
{
/*
Double the image size.
*/
windows->image.window_changes.width=windows->image.ximage->width << 1;
windows->image.window_changes.height=windows->image.ximage->height << 1;
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case ResizeCommand:
{
long
x,
y;
unsigned long
height,
width;
/*
Resize image.
*/
width=windows->image.ximage->width;
height=windows->image.ximage->height;
x=0;
y=0;
FormatString(geometry,"%lux%lu+0+0",width,height);
status=MagickXDialogWidget(display,windows,"Resize",
"Enter resize geometry (e.g. 640x480, 200%):",geometry);
if (*geometry == '\0')
break;
if (!status)
(void) strcat(geometry,"!");
(void) GetMagickGeometry(geometry,&x,&y,&width,&height);
windows->image.window_changes.width=(unsigned int) width;
windows->image.window_changes.height=(unsigned int) height;
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case ApplyCommand:
{
char
image_geometry[MaxTextExtent];
if ((windows->image.crop_geometry == (char *) NULL) &&
((int) (*image)->columns == windows->image.ximage->width) &&
((int) (*image)->rows == windows->image.ximage->height))
break;
/*
Apply size transforms to image.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
/*
Crop and/or scale displayed image.
*/
FormatString(image_geometry,"%dx%d!",windows->image.ximage->width,
windows->image.ximage->height);
TransformImage(image,windows->image.crop_geometry,image_geometry);
if (windows->image.crop_geometry != (char *) NULL)
{
MagickFreeMemory(windows->image.crop_geometry);
windows->image.crop_geometry=(char *) NULL;
}
windows->image.x=0;
windows->image.y=0;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case RefreshCommand:
{
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case RestoreCommand:
{
/*
Restore Image window to its original size.
*/
if ((windows->image.width == (unsigned int) (*image)->columns) &&
(windows->image.height == (unsigned int) (*image)->rows) &&
(windows->image.crop_geometry == (char *) NULL))
{
(void) XBell(display,0);
break;
}
windows->image.window_changes.width=(unsigned int) (*image)->columns;
windows->image.window_changes.height=(unsigned int) (*image)->rows;
if (windows->image.crop_geometry != (char *) NULL)
{
MagickFreeMemory(windows->image.crop_geometry);
windows->image.crop_geometry=(char *) NULL;
windows->image.x=0;
windows->image.y=0;
}
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case CropCommand:
{
/*
Crop image.
*/
(void) MagickXCropImage(display,resource_info,windows,*image,CropMode);
break;
}
case ChopCommand:
{
/*
Chop image.
*/
status=MagickXChopImage(display,resource_info,windows,image);
if (status == False)
{
MagickXNoticeWidget(display,windows,"Unable to cut X image",
(*image)->filename);
break;
}
break;
}
case FlopCommand:
{
/*
Flop image scanlines.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
ReplaceImage(*image,FlopImage(*image,&(*image)->exception));
MagickXSetCursorState(display,windows,False);
if (windows->image.crop_geometry != (char *) NULL)
{
/*
Flop crop geometry.
*/
width=(unsigned int) (*image)->columns;
height=(unsigned int) (*image)->rows;
(void) XParseGeometry(windows->image.crop_geometry,&x,&y,
&width,&height);
FormatString(windows->image.crop_geometry,"%ux%u%+d%+d",width,
height,(int) (*image)->columns-(int) width-x,y);
}
if (windows->image.orphan)
break;
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case FlipCommand:
{
/*
Flip image scanlines.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
ReplaceImage(*image,FlipImage(*image,&(*image)->exception));
MagickXSetCursorState(display,windows,False);
if (windows->image.crop_geometry != (char *) NULL)
{
/*
Flip crop geometry.
*/
width=(unsigned int) (*image)->columns;
height=(unsigned int) (*image)->rows;
(void) XParseGeometry(windows->image.crop_geometry,&x,&y,
&width,&height);
FormatString(windows->image.crop_geometry,"%ux%u%+d%+d",width,
height,x,(int) (*image)->rows-(int) height-y);
}
if (windows->image.orphan)
break;
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case RotateRightCommand:
{
/*
Rotate image 90 degrees clockwise.
*/
status=MagickXRotateImage(display,resource_info,windows,90.0,image);
if (status == False)
{
MagickXNoticeWidget(display,windows,"Unable to rotate X image",
(*image)->filename);
break;
}
break;
}
case RotateLeftCommand:
{
/*
Rotate image 90 degrees counter-clockwise.
*/
status=MagickXRotateImage(display,resource_info,windows,-90.0,image);
if (status == False)
{
MagickXNoticeWidget(display,windows,"Unable to rotate X image",
(*image)->filename);
break;
}
break;
}
case RotateCommand:
{
/*
Rotate image.
*/
status=MagickXRotateImage(display,resource_info,windows,0.0,image);
if (status == False)
{
MagickXNoticeWidget(display,windows,"Unable to rotate X image",
(*image)->filename);
break;
}
break;
}
case ShearCommand:
{
static char
geometry[MaxTextExtent] = "45.0x45.0";
double
x_shear,
y_shear;
/*
Query user for shear color and geometry.
*/
MagickXColorBrowserWidget(display,windows,"Select",color);
if (*color == '\0')
break;
(void) MagickXDialogWidget(display,windows,"Shear","Enter shear geometry:",
geometry);
if (*geometry == '\0')
break;
/*
Shear image.
*/
(void) MagickXMagickCommand(display,resource_info,windows,ApplyCommand,image);
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
(void) QueryColorDatabase(color,&(*image)->background_color,
&(*image)->exception);
x_shear=0.0;
y_shear=0.0;
(void) GetMagickDimension(geometry,&x_shear,&y_shear,NULL,NULL);
ReplaceImage(*image,ShearImage(*image,x_shear,y_shear,
&(*image)->exception));
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
windows->image.window_changes.width=(unsigned int) (*image)->columns;
windows->image.window_changes.height=(unsigned int) (*image)->rows;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case RollCommand:
{
static char
geometry[MaxTextExtent] = "+2+2";
/*
Query user for the roll geometry.
*/
(void) MagickXDialogWidget(display,windows,"Roll","Enter roll geometry:",
geometry);
if (*geometry == '\0')
break;
/*
Roll image.
*/
(void) MagickXMagickCommand(display,resource_info,windows,ApplyCommand,image);
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
(void) GetImageGeometry(*image,geometry,False,&rectangle);
ReplaceImage(*image,RollImage(*image,rectangle.x,rectangle.y,
&(*image)->exception));
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
windows->image.window_changes.width=(unsigned int) (*image)->columns;
windows->image.window_changes.height=(unsigned int) (*image)->rows;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case TrimCommand:
{
/*
Trim image.
*/
status=MagickXTrimImage(display,resource_info,windows,*image);
if (status == False)
{
MagickXNoticeWidget(display,windows,"Unable to trim X image",
(*image)->filename);
break;
}
break;
}
case HueCommand:
{
static char
hue_percent[MaxTextExtent] = "110";
/*
Query user for percent hue change.
*/
(void) MagickXDialogWidget(display,windows,"Apply",
"Enter percent change in image hue (0-200):",hue_percent);
if (*hue_percent == '\0')
break;
/*
Vary the image hue.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
(void) strlcpy(modulate_factors,"100.0/100.0/",MaxTextExtent);
(void) strlcat(modulate_factors,hue_percent,MaxTextExtent);
(void) ModulateImage(*image,modulate_factors);
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case SaturationCommand:
{
static char
saturation_percent[MaxTextExtent] = "110";
/*
Query user for percent saturation change.
*/
(void) MagickXDialogWidget(display,windows,"Apply",
"Enter percent change in color saturation (0-200):",saturation_percent);
if (*saturation_percent == '\0')
break;
/*
Vary color saturation.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
(void) strlcpy(modulate_factors,"100.0/",MaxTextExtent);
(void) strlcat(modulate_factors,saturation_percent,MaxTextExtent);
(void) ModulateImage(*image,modulate_factors);
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case BrightnessCommand:
{
static char
brightness_percent[MaxTextExtent] = "110";
/*
Query user for percent brightness change.
*/
(void) MagickXDialogWidget(display,windows,"Apply",
"Enter percent change in color brightness (0-200):",brightness_percent);
if (*brightness_percent == '\0')
break;
/*
Vary the color brightness.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
(void) strlcpy(modulate_factors,brightness_percent,MaxTextExtent);
(void) ModulateImage(*image,modulate_factors);
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case GammaCommand:
{
static char
factor[MaxTextExtent] = "1.6";
/*
Query user for gamma value.
*/
(void) MagickXDialogWidget(display,windows,"Gamma",
"Enter gamma value (e.g. 1.0/1.0/1.6):",factor);
if (*factor == '\0')
break;
/*
Gamma correct image.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
(void) GammaImage(*image,factor);
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case SpiffCommand:
{
/*
Sharpen the image contrast.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
(void) ContrastImage(*image,True);
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case DullCommand:
{
/*
Dull the image contrast.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
(void) ContrastImage(*image,False);
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case EqualizeCommand:
{
/*
Perform histogram equalization on the image.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
(void) EqualizeImage(*image);
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case NormalizeCommand:
{
/*
Perform histogram normalization on the image.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
(void) NormalizeImage(*image);
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case NegateCommand:
{
/*
Negate colors in image.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
(void) NegateImage(*image,False);
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case GrayscaleCommand:
{
/*
Convert image to grayscale.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
(void) TransformColorspace(*image,GRAYColorspace);
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case MapCommand:
{
static char
filename[MaxTextExtent] = "\0";
Image
*map_image;
/*
Request image file name from user.
*/
MagickXFileBrowserWidget(display,windows,"Map",filename);
if (*filename == '\0')
break;
/*
Map image.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
map_image=ReadImage(resource_info->image_info,&(*image)->exception);
if (map_image != (Image *) NULL)
{
(void) MapImage(*image,map_image,True);
DestroyImage(map_image);
}
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case QuantizeCommand:
{
static char
colors[MaxTextExtent] = "256";
QuantizeInfo
quantize_info;
/*
Query user for maximum number of colors.
*/
status=MagickXDialogWidget(display,windows,"Quantize",
"Maximum number of colors:",colors);
if (*colors == '\0')
break;
/*
Color reduce the image.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
GetQuantizeInfo(&quantize_info);
quantize_info.number_colors=MagickAtoL(colors);
quantize_info.dither=(status ? False : True);
quantize_info.colorspace=(*image)->colorspace;
(void) QuantizeImage(&quantize_info,*image);
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case DespeckleCommand:
{
/*
Despeckle image.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
ReplaceImage(*image,DespeckleImage(*image,&(*image)->exception));
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case EmbossCommand:
{
static char
emboss_argument[MaxTextExtent] = "0.0x1.0";
double
radius,
sigma;
/*
Query user for emboss radius.
*/
(void) MagickXDialogWidget(display,windows,"Emboss",
"Enter the emboss radius and standard deviation:",emboss_argument);
if (*emboss_argument == '\0')
break;
/*
Reduce noise in the image.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
radius=0.0;
sigma=1.0;
(void) GetMagickDimension(emboss_argument,&radius,&sigma,NULL,NULL);
ReplaceImage(*image,EmbossImage(*image,radius,sigma,
&(*image)->exception));
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case ReduceNoiseCommand:
{
static char
radius[MaxTextExtent] = "0";
/*
Query user for noise radius.
*/
(void) MagickXDialogWidget(display,windows,"Reduce Noise",
"Enter the noise radius:",radius);
if (*radius == '\0')
break;
/*
Reduce noise in the image.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
ReplaceImage(*image,ReduceNoiseImage(*image,MagickAtoL(radius),
&(*image)->exception));
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case AddNoiseCommand:
{
static char
option[MaxTextExtent] = "Gaussian";
const char
* const NoiseTypes[] =
{
"Uniform",
"Gaussian",
"Multiplicative",
"Impulse",
"Lapacian",
"Poisson",
(char *) NULL
};
NoiseType
noise_type;
/*
Add noise to the image.
*/
MagickXListBrowserWidget(display,windows,&windows->widget,NoiseTypes,
"Add Noise","Select a type of noise to add to your image:",
option);
if (*option == '\0')
break;
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
noise_type=UniformNoise;
if (LocaleCompare("Gaussian",option) == 0)
noise_type=GaussianNoise;
if (LocaleCompare("multiplicative",option) == 0)
noise_type=MultiplicativeGaussianNoise;
if (LocaleCompare("impulse",option) == 0)
noise_type=ImpulseNoise;
if (LocaleCompare("laplacian",option) == 0)
noise_type=LaplacianNoise;
if (LocaleCompare("Poisson",option) == 0)
noise_type=PoissonNoise;
ReplaceImage(*image,AddNoiseImage(*image,noise_type,
&(*image)->exception));
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case SharpenCommand:
{
static char
option[MaxTextExtent] = "0.0x1.0";
double
radius,
sigma;
/*
Query user for sharpen radius.
*/
(void) MagickXDialogWidget(display,windows,"Sharpen",
"Enter the sharpen radius and standard deviation:",option);
if (*option == '\0')
break;
/*
Sharpen image scanlines.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
radius=0.0;
sigma=1.0;
(void) GetMagickDimension(option,&radius,&sigma,NULL,NULL);
ReplaceImage(*image,SharpenImage(*image,radius,sigma,
&(*image)->exception));
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case BlurCommand:
{
static char
option[MaxTextExtent] = "0.0x1.0";
double
radius,
sigma;
/*
Query user for blur radius.
*/
(void) MagickXDialogWidget(display,windows,"Blur",
"Enter the blur radius and standard deviation:",option);
if (*option == '\0')
break;
/*
Blur an image.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
radius=0.0;
sigma=1.0;
(void) GetMagickDimension(option,&radius,&sigma,NULL,NULL);
ReplaceImage(*image,BlurImage(*image,radius,sigma,
&(*image)->exception));
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case ThresholdCommand:
{
static char
factor[MaxTextExtent];
/*
Query user for threshold value.
*/
(void) sprintf(factor,"%lu",(unsigned long)(MaxRGB+1)/2);
(void) MagickXDialogWidget(display,windows,"Threshold",
"Enter threshold value:",factor);
if (*factor == '\0')
break;
/*
Threshold image.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
(void) ChannelThresholdImage(*image,factor);
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case EdgeDetectCommand:
{
static char
radius[MaxTextExtent] = "0";
/*
Query user for edge factor.
*/
(void) MagickXDialogWidget(display,windows,"Detect Edges",
"Enter the edge detect radius:",radius);
if (*radius == '\0')
break;
/*
Detect edge in image.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
ReplaceImage(*image,EdgeImage(*image,MagickAtoF(radius),
&(*image)->exception));
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case SpreadCommand:
{
static char
amount[MaxTextExtent] = "2";
/*
Query user for spread amount.
*/
(void) MagickXDialogWidget(display,windows,"Spread",
"Enter the displacement amount:",amount);
if (*amount == '\0')
break;
/*
Displace image pixels by a random amount.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
ReplaceImage(*image,SpreadImage(*image,MagickAtoI(amount),
&(*image)->exception));
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case ShadeCommand:
{
static char
geometry[MaxTextExtent] = "30x30";
double
azimuth,
elevation;
/*
Query user for the shade geometry.
*/
status=MagickXDialogWidget(display,windows,"Shade",
"Enter the azimuth and elevation of the light source:",geometry);
if (*geometry == '\0')
break;
/*
Shade image pixels.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
azimuth=30.0;
elevation=30.0;
(void) GetMagickDimension(geometry,&azimuth,&elevation,NULL,NULL);
ReplaceImage(*image,ShadeImage(*image,(status ? True : False),
azimuth,elevation,&(*image)->exception));
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case RaiseCommand:
{
static char
bevel_width[MaxTextExtent] = "10";
/*
Query user for bevel width.
*/
(void) MagickXDialogWidget(display,windows,"Raise","Bevel width:",bevel_width);
if (*bevel_width == '\0')
break;
/*
Raise an image.
*/
(void) MagickXMagickCommand(display,resource_info,windows,ApplyCommand,image);
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
(void) GetImageGeometry(*image,bevel_width,False,&rectangle);
(void) RaiseImage(*image,&rectangle,True);
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case SegmentCommand:
{
static char
threshold[MaxTextExtent] = "1.0x1.5";
double
cluster_threshold,
smoothing_threshold;
/*
Query user for smoothing threshold.
*/
(void) MagickXDialogWidget(display,windows,"Segment","Smooth threshold:",
threshold);
if (*threshold == '\0')
break;
/*
Segment an image.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
cluster_threshold=1.0;
smoothing_threshold=1.5;
(void) GetMagickDimension(threshold,&cluster_threshold,
&smoothing_threshold,NULL,NULL);
(void) SegmentImage(*image,(*image)->colorspace,False,
cluster_threshold,smoothing_threshold);
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case SolarizeCommand:
{
static char
factor[MaxTextExtent] = "60";
/*
Query user for solarize factor.
*/
(void) MagickXDialogWidget(display,windows,"Solarize",
"Enter the solarize factor (0 - 99.9%):",factor);
if (*factor == '\0')
break;
/*
Solarize image pixels.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
(void) SolarizeImage(*image,StringToDouble(factor,MaxRGB));
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case SwirlCommand:
{
static char
degrees[MaxTextExtent] = "60";
/*
Query user for swirl angle.
*/
(void) MagickXDialogWidget(display,windows,"Swirl","Enter the swirl angle:",
degrees);
if (*degrees == '\0')
break;
/*
Swirl image pixels about the center.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
ReplaceImage(*image,SwirlImage(*image,MagickAtoF(degrees),
&(*image)->exception));
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case ImplodeCommand:
{
static char
factor[MaxTextExtent] = "0.3";
/*
Query user for implode factor.
*/
(void) MagickXDialogWidget(display,windows,"Implode",
"Enter the implosion/explosion factor (-1.0 - 1.0):",factor);
if (*factor == '\0')
break;
/*
Implode image pixels about the center.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
ReplaceImage(*image,ImplodeImage(*image,MagickAtoF(factor),
&(*image)->exception));
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case WaveCommand:
{
static char
geometry[MaxTextExtent] = "25x150";
double
amplitude,
wavelength;
/*
Query user for the shade geometry.
*/
(void) MagickXDialogWidget(display,windows,"Wave",
"Enter the amplitude and length of the wave:",geometry);
if (*geometry == '\0')
break;
/*
Shade image pixels.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
amplitude=25.0;
wavelength=150.0;
(void) GetMagickDimension(geometry,&litude,&wavelength,NULL,NULL);
ReplaceImage(*image,WaveImage(*image,amplitude,wavelength,
&(*image)->exception));
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case OilPaintCommand:
{
static char
radius[MaxTextExtent] = "0";
/*
Query user for circular neighborhood radius.
*/
(void) MagickXDialogWidget(display,windows,"Oil Paint",
"Enter the mask radius:",radius);
if (*radius == '\0')
break;
/*
OilPaint image scanlines.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
ReplaceImage(*image,OilPaintImage(*image,MagickAtoF(radius),
&(*image)->exception));
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case CharcoalDrawCommand:
{
static char
option[MaxTextExtent] = "0.0";
double
radius,
sigma;
/*
Query user for charcoal radius.
*/
(void) MagickXDialogWidget(display,windows,"Charcoal Draw",
"Enter the charcoal radius:",option);
if (*option == '\0')
break;
/*
Charcoal the image.
*/
(void) MagickXMagickCommand(display,resource_info,windows,ApplyCommand,image);
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
radius=0.0;
sigma=1.0;
(void) GetMagickDimension(option,&radius,&sigma,NULL,NULL);
ReplaceImage(*image,CharcoalImage(*image,radius,sigma,
&(*image)->exception));
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case AnnotateCommand:
{
/*
Annotate the image with text.
*/
status=MagickXAnnotateEditImage(display,resource_info,windows,*image);
if (status == False)
{
MagickXNoticeWidget(display,windows,"Unable to annotate X image",
(*image)->filename);
break;
}
break;
}
case DrawCommand:
{
/*
Draw image.
*/
status=MagickXDrawEditImage(display,resource_info,windows,image);
if (status == False)
{
MagickXNoticeWidget(display,windows,"Unable to draw on the X image",
(*image)->filename);
break;
}
break;
}
case ColorCommand:
{
/*
Color edit.
*/
status=MagickXColorEditImage(display,resource_info,windows,image);
if (status == False)
{
MagickXNoticeWidget(display,windows,"Unable to pixel edit X image",
(*image)->filename);
break;
}
break;
}
case MatteCommand:
{
/*
Matte edit.
*/
status=MagickXMatteEditImage(display,resource_info,windows,image);
if (status == False)
{
MagickXNoticeWidget(display,windows,"Unable to matte edit X image",
(*image)->filename);
break;
}
break;
}
case CompositeCommand:
{
/*
Composite image.
*/
status=MagickXCompositeImage(display,resource_info,windows,*image);
if (status == False)
{
MagickXNoticeWidget(display,windows,"Unable to composite X image",
(*image)->filename);
break;
}
break;
}
case AddBorderCommand:
{
static char
geometry[MaxTextExtent] = "6x6";
/*
Query user for border color and geometry.
*/
MagickXColorBrowserWidget(display,windows,"Select",color);
if (*color == '\0')
break;
(void) MagickXDialogWidget(display,windows,"Add Border",
"Enter border geometry:",geometry);
if (*geometry == '\0')
break;
/*
Add a border to the image.
*/
(void) MagickXMagickCommand(display,resource_info,windows,ApplyCommand,image);
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
(void) QueryColorDatabase(color,&(*image)->border_color,
&(*image)->exception);
(void) GetImageGeometry(*image,geometry,False,&rectangle);
ReplaceImage(*image,BorderImage(*image,&rectangle,
&(*image)->exception));
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
windows->image.window_changes.width=(unsigned int) (*image)->columns;
windows->image.window_changes.height=(unsigned int) (*image)->rows;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case AddFrameCommand:
{
static char
geometry[MaxTextExtent] = "6x6";
FrameInfo
frame_info;
/*
Query user for frame color and geometry.
*/
MagickXColorBrowserWidget(display,windows,"Select",color);
if (*color == '\0')
break;
(void) MagickXDialogWidget(display,windows,"Add Frame","Enter frame geometry:",
geometry);
if (*geometry == '\0')
break;
/*
Surround image with an ornamental border.
*/
(void) MagickXMagickCommand(display,resource_info,windows,ApplyCommand,image);
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
(void) QueryColorDatabase(color,&(*image)->matte_color,
&(*image)->exception);
(void) GetImageGeometry(*image,geometry,False,&rectangle);
frame_info.width=rectangle.width;
frame_info.height=rectangle.height;
frame_info.outer_bevel=rectangle.x;
frame_info.inner_bevel=rectangle.y;
frame_info.x=(long) frame_info.width;
frame_info.y=(long) frame_info.height;
frame_info.width=(*image)->columns+2*frame_info.width;
frame_info.height=(*image)->rows+2*frame_info.height;
ReplaceImage(*image,FrameImage(*image,&frame_info,&(*image)->exception));
MagickXSetCursorState(display,windows,False);
if (windows->image.orphan)
break;
windows->image.window_changes.width=(unsigned int) (*image)->columns;
windows->image.window_changes.height=(unsigned int) (*image)->rows;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
break;
}
case CommentCommand:
{
const ImageAttribute
*attribute;
FILE
*file;
/*
Edit image comment.
*/
if (!AcquireTemporaryFileName(image_info->filename))
{
MagickXNoticeWidget(display,windows,"Unable to open temporary file:",
image_info->filename);
break;
}
attribute=GetImageAttribute(*image,"comment");
if ((attribute != (const ImageAttribute *) NULL) &&
(attribute->value != (char *) NULL))
{
register char
*p;
file=fopen(image_info->filename,"w");
if (file == (FILE *) NULL)
{
(void) LiberateTemporaryFile(image_info->filename);
MagickXNoticeWidget(display,windows,"Unable to edit image comment",
image_info->filename);
break;
}
for (p=attribute->value; *p != '\0'; p++)
(void) fputc((int) *p,file);
(void) fputc('\n',file);
(void) fclose(file);
}
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
status=InvokeDelegate(image_info,*image,"edit",(char *) NULL,
&(*image)->exception);
if (status == False)
MagickXNoticeWidget(display,windows,"Unable to edit image comment",
(char *) NULL);
else
{
char
command[MaxTextExtent];
FormatString(command,"@%.1024s",image_info->filename);
(void) SetImageAttribute(*image,"comment",(char *) NULL);
(void) SetImageAttribute(*image,"comment",command);
(*image)->taint=True;
}
(void) LiberateTemporaryFile(image_info->filename);
MagickXSetCursorState(display,windows,False);
break;
}
case LaunchCommand:
{
/*
Launch program.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
if (!AcquireTemporaryFileName(filename))
{
MagickXNoticeWidget(display,windows,"Unable to open temporary file:",
filename);
break;
}
FormatString((*image)->filename,"launch:%s",filename);
status=WriteImage(image_info,*image);
if (status == False)
{
(void) LiberateTemporaryFile(filename);
MagickXNoticeWidget(display,windows,"Unable to launch image editor",
(char *) NULL);
}
else
{
nexus=ReadImage(resource_info->image_info,&(*image)->exception);
if ((*image)->exception.severity != UndefinedException)
MagickError2((*image)->exception.severity,
(*image)->exception.reason,(*image)->exception.description);
MagickXClientMessage(display,windows->image.id,windows->im_protocols,
windows->im_next_image,CurrentTime);
}
(void) LiberateTemporaryFile(filename);
MagickXSetCursorState(display,windows,False);
break;
}
case RegionofInterestCommand:
{
/*
Apply an image processing technique to a region of interest.
*/
(void) MagickXROIImage(display,resource_info,windows,image);
break;
}
case InfoCommand:
break;
case ZoomCommand:
{
/*
Zoom image.
*/
if (windows->magnify.mapped)
(void) XRaiseWindow(display,windows->magnify.id);
else
{
/*
Make magnify image.
*/
MagickXSetCursorState(display,windows,True);
(void) XMapRaised(display,windows->magnify.id);
MagickXSetCursorState(display,windows,False);
}
break;
}
case ShowPreviewCommand:
{
static char
preview_type[MaxTextExtent] = "Gamma";
const char
* const PreviewTypes[] =
{
"Rotate",
"Shear",
"Roll",
"Hue",
"Saturation",
"Brightness",
"Gamma",
"Spiff",
"Dull",
"Grayscale",
"Quantize",
"Despeckle",
"Reduce Noise",
"Add Noise",
"Sharpen",
"Blur",
"Threshold",
"Edge Detect",
"Spread",
"Solarize",
"Shade",
"Raise",
"Segment",
"Swirl",
"Implode",
"Wave",
"Oil Paint",
"Charcoal Drawing",
"JPEG",
(char *) NULL
};
register int
i;
/*
Select preview type from menu.
*/
MagickXListBrowserWidget(display,windows,&windows->widget,PreviewTypes,
"Preview","Select an enhancement, effect, or F/X:",preview_type);
if (*preview_type == '\0')
break;
for (i=0; PreviewTypes[i] != (char *) NULL; i++)
if (LocaleCompare(PreviewTypes[i],preview_type) == 0)
break;
if (PreviewTypes[i] == (char *) NULL)
{
MagickXNoticeWidget(display,windows,"unknown preview type",preview_type);
break;
}
/*
Show image preview.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
image_info->preview_type=(PreviewType) (i+1);
image_info->group=(long) windows->image.id;
(void) SetImageAttribute(*image,"label",(char *) NULL);
(void) SetImageAttribute(*image,"label","Preview");
if (!AcquireTemporaryFileName(filename))
{
MagickXNoticeWidget(display,windows,"Unable to open temporary file:",
filename);
break;
}
FormatString((*image)->filename,"preview:%s",filename);
status=WriteImage(image_info,*image);
FormatString((*image)->filename,"show:%s",filename);
status=WriteImage(image_info,*image);
if (status == False)
{
MagickXNoticeWidget(display,windows,"Unable to show image preview",
(*image)->filename);
}
MagickXDelay(display,1500);
MagickXSetCursorState(display,windows,False);
break;
}
case ShowHistogramCommand:
{
/*
Show image histogram.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
image_info->group=(long) windows->image.id;
(void) SetImageAttribute(*image,"label",(char *) NULL);
(void) SetImageAttribute(*image,"label","Histogram");
if (!AcquireTemporaryFileName(filename))
{
MagickXNoticeWidget(display,windows,"Unable to open temporary file:",
filename);
break;
}
FormatString((*image)->filename,"histogram:%s",filename);
status=WriteImage(image_info,*image);
FormatString((*image)->filename,"show:%s",filename);
status=WriteImage(image_info,*image);
if (status == False)
MagickXNoticeWidget(display,windows,"Unable to show histogram",
(*image)->filename);
MagickXDelay(display,1500);
MagickXSetCursorState(display,windows,False);
break;
}
case ShowMatteCommand:
{
if (!(*image)->matte)
{
MagickXNoticeWidget(display,windows,
"Image does not have any matte information",(*image)->filename);
break;
}
/*
Show image matte.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
image_info->group=(long) windows->image.id;
(void) SetImageAttribute(*image,"label",(char *) NULL);
(void) SetImageAttribute(*image,"label","Matte");
if (!AcquireTemporaryFileName(filename))
{
MagickXNoticeWidget(display,windows,"Unable to open temporary file:",
filename);
break;
}
FormatString((*image)->filename,"matte:%s",filename);
status=WriteImage(image_info,*image);
FormatString((*image)->filename,"show:%s",filename);
status=WriteImage(image_info,*image);
if (status == False)
MagickXNoticeWidget(display,windows,"Unable to show matte",
(*image)->filename);
MagickXDelay(display,1500);
MagickXSetCursorState(display,windows,False);
break;
}
case BackgroundCommand:
{
/*
Background image.
*/
status=MagickXBackgroundImage(display,resource_info,windows,image);
if (status == False)
break;
nexus=CloneImage(*image,0,0,True,&(*image)->exception);
if (nexus != (Image *) NULL)
MagickXClientMessage(display,windows->image.id,windows->im_protocols,
windows->im_next_image,CurrentTime);
break;
}
case SlideShowCommand:
{
static char
delay[MaxTextExtent] = "5";
/*
Display next image after pausing.
*/
(void) MagickXDialogWidget(display,windows,"Slide Show",
"Pause how many 1/100ths of a second between images:",delay);
if (*delay == '\0')
break;
resource_info->delay=MagickAtoI(delay);
MagickXClientMessage(display,windows->image.id,windows->im_protocols,
windows->im_next_image,CurrentTime);
break;
}
case PreferencesCommand:
{
/*
Set user preferences.
*/
status=MagickXPreferencesWidget(display,resource_info,windows);
if (status == False)
break;
nexus=CloneImage(*image,0,0,True,&(*image)->exception);
if (nexus != (Image *) NULL)
MagickXClientMessage(display,windows->image.id,windows->im_protocols,
windows->im_next_image,CurrentTime);
break;
}
case HelpCommand:
{
/*
User requested help.
*/
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Display",
DisplayHelp,
sizeof(DisplayHelp));
break;
}
case BrowseDocumentationCommand:
{
Atom
mozilla_atom;
Window
mozilla_window,
root_window;
/*
Browse the GraphicsMagick documentation.
*/
root_window=XRootWindow(display,XDefaultScreen(display));
mozilla_atom=XInternAtom(display,"_MOZILLA_VERSION",False);
mozilla_window=MagickXWindowByProperty(display,root_window,mozilla_atom);
if (mozilla_window != (Window) NULL)
{
char
command[MaxTextExtent];
/*
Display documentation using Netscape remote control.
*/
FormatString(command,"openURL(%.1024s,new-window,noraise)",
"http://www.graphicsmagick.org/");
mozilla_atom=XInternAtom(display,"_MOZILLA_COMMAND",False);
(void) XChangeProperty(display,mozilla_window,mozilla_atom,XA_STRING,
8,PropModeReplace,(unsigned char *) command,(int) strlen(command));
MagickXSetCursorState(display,windows,False);
break;
}
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
status=InvokeDelegate(image_info,*image,"browse",(char *) NULL,
&(*image)->exception);
if (status == False)
MagickXNoticeWidget(display,windows,"Unable to browse documentation",
(char *) NULL);
MagickXDelay(display,1500);
MagickXSetCursorState(display,windows,False);
break;
}
case VersionCommand:
{
MagickXNoticeWidget(display,windows,GetMagickVersion((unsigned long *) NULL),
GetMagickCopyright());
break;
}
case SaveToUndoBufferCommand:
break;
default:
{
(void) XBell(display,0);
break;
}
}
DestroyImageInfo(image_info);
return(nexus);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X M a g n i f y I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXMagnifyImage magnifies portions of the image as indicated
% by the pointer. The magnified portion is displayed in a separate window.
%
% The format of the MagickXMagnifyImage method is:
%
% void MagickXMagnifyImage(Display *display,MagickXWindows *windows,XEvent *event)
%
% A description of each parameter follows:
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
% o event: Specifies a pointer to a XEvent structure. If it is NULL,
% the entire image is refreshed.
%
%
*/
static void MagickXMagnifyImage(Display *display,MagickXWindows *windows,XEvent *event)
{
char
text[MaxTextExtent];
register int
x,
y;
unsigned long
state;
/*
Update magnified image until the mouse button is released.
*/
(void) XDefineCursor(display,windows->image.id,windows->magnify.cursor);
state=DefaultState;
x=event->xbutton.x;
y=event->xbutton.y;
windows->magnify.x=windows->image.x+x;
windows->magnify.y=windows->image.y+y;
do
{
/*
Map and unmap Info widget as text cursor crosses its boundaries.
*/
if (windows->info.mapped)
{
if ((x < (int) (windows->info.x+windows->info.width)) &&
(y < (int) (windows->info.y+windows->info.height)))
(void) XWithdrawWindow(display,windows->info.id,windows->info.screen);
}
else
if ((x > (int) (windows->info.x+windows->info.width)) ||
(y > (int) (windows->info.y+windows->info.height)))
(void) XMapWindow(display,windows->info.id);
if (windows->info.mapped)
{
/*
Display pointer position.
*/
FormatString(text," %+d%+d ",windows->magnify.x,windows->magnify.y);
MagickXInfoWidget(display,windows,text);
}
/*
Wait for next event.
*/
MagickXScreenEvent(display,windows,event);
switch (event->type)
{
case ButtonPress:
break;
case ButtonRelease:
{
/*
User has finished magnifying image.
*/
x=event->xbutton.x;
y=event->xbutton.y;
state|=ExitState;
break;
}
case Expose:
break;
case MotionNotify:
{
x=event->xmotion.x;
y=event->xmotion.y;
break;
}
default:
break;
}
/*
Check boundary conditions.
*/
if (x < 0)
x=0;
else
if (x >= (int) windows->image.width)
x=windows->image.width-1;
if (y < 0)
y=0;
else
if (y >= (int) windows->image.height)
y=windows->image.height-1;
} while (!(state & ExitState));
/*
Display magnified image.
*/
MagickXSetCursorState(display,windows,False);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X M a g n i f y W i n d o w C o m m a n d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXMagnifyWindowCommand moves the image within an Magnify window by
% one pixel as specified by the key symbol.
%
% The format of the MagickXMagnifyWindowCommand method is:
%
% void MagickXMagnifyWindowCommand(Display *display,MagickXWindows *windows,
% const unsigned int state,const KeySym key_symbol)
%
% A description of each parameter follows:
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
% o state: key mask.
%
% o key_symbol: Specifies a KeySym which indicates which side of the image
% to trim.
%
%
*/
static void MagickXMagnifyWindowCommand(Display *display,MagickXWindows *windows,
const unsigned int state,const KeySym key_symbol)
{
unsigned int
quantum;
/*
User specified a magnify factor or position.
*/
quantum=1;
if (state & Mod1Mask)
quantum=10;
switch ((int) key_symbol)
{
case QuitCommand:
{
(void) XWithdrawWindow(display,windows->magnify.id,
windows->magnify.screen);
break;
}
case XK_Home:
case XK_KP_Home:
{
windows->magnify.x=windows->image.width/2;
windows->magnify.y=windows->image.height/2;
break;
}
case XK_Left:
case XK_KP_Left:
{
if (windows->magnify.x > 0)
windows->magnify.x-=quantum;
break;
}
case XK_Up:
case XK_KP_Up:
{
if (windows->magnify.y > 0)
windows->magnify.y-=quantum;
break;
}
case XK_Right:
case XK_KP_Right:
{
if (windows->magnify.x < (int) (windows->image.ximage->width-1))
windows->magnify.x+=quantum;
break;
}
case XK_Down:
case XK_KP_Down:
{
if (windows->magnify.y < (int) (windows->image.ximage->height-1))
windows->magnify.y+=quantum;
break;
}
case XK_0:
case XK_1:
case XK_2:
case XK_3:
case XK_4:
case XK_5:
case XK_6:
case XK_7:
case XK_8:
case XK_9:
{
windows->magnify.data=(key_symbol-XK_0);
break;
}
case XK_KP_0:
case XK_KP_1:
case XK_KP_2:
case XK_KP_3:
case XK_KP_4:
case XK_KP_5:
case XK_KP_6:
case XK_KP_7:
case XK_KP_8:
case XK_KP_9:
{
windows->magnify.data=(key_symbol-XK_KP_0);
break;
}
default:
break;
}
MagickXMakeMagnifyImage(display,windows);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X M a k e P a n I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXMakePanImage creates a thumbnail of the image and displays it in
% the Pan icon window.
%
% The format of the MagickXMakePanImage method is:
%
% void MagickXMakePanImage(Display *display,MagickXResourceInfo *resource_info,
% MagickXWindows *windows,Image *image)
%
% A description of each parameter follows:
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o resource_info: Specifies a pointer to a X11 MagickXResourceInfo structure.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
% o image: Specifies a pointer to an Image structure; returned from
% ReadImage.
%
%
*/
static void MagickXMakePanImage(Display *display,MagickXResourceInfo *resource_info,
MagickXWindows *windows,Image *image)
{
unsigned int
status;
/*
Display hourglass cursor if progress indication enabled.
*/
if (resource_info->image_info->progress)
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
windows->pan.x=windows->image.x;
windows->pan.y=windows->image.y;
/*
Create and display image for panning icon.
*/
status=MagickXMakeImage(display,resource_info,&windows->pan,image,
windows->pan.width,windows->pan.height);
if (status == False)
MagickError2(XServerError,image->exception.reason,(char *) NULL);
(void) XSetWindowBackgroundPixmap(display,windows->pan.id,
windows->pan.pixmap);
(void) XClearWindow(display,windows->pan.id);
MagickXDrawPanRectangle(display,windows);
MagickXSetCursorState(display,windows,False);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X M a t t a E d i t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXMatteEditImage allows the user to interactively change
% the Matte channel of an image. If the image is PseudoClass it is promoted
% to DirectClass before the matte information is stored.
%
% The format of the MagickXMatteEditImage method is:
%
% unsigned int MagickXMatteEditImage(Display *display,
% MagickXResourceInfo *resource_info,MagickXWindows *windows,Image **image)
%
% A description of each parameter follows:
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o resource_info: Specifies a pointer to a X11 MagickXResourceInfo structure.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
% o image: Specifies a pointer to an Image structure; returned from
% ReadImage.
%
*/
static unsigned int MagickXMatteEditImage(Display *display,
MagickXResourceInfo *resource_info,MagickXWindows *windows,Image **image)
{
static char
matte[MaxTextExtent] = "0";
const char
* const MatteEditMenu[]=
{
"Method",
"Border Color",
"Fuzz",
"Matte Value",
"Undo",
"Help",
"Dismiss",
(char *) NULL
};
static const ModeType
MatteEditCommands[]=
{
MatteEditMethod,
MatteEditBorderCommand,
MatteEditFuzzCommand,
MatteEditValueCommand,
MatteEditUndoCommand,
MatteEditHelpCommand,
MatteEditDismissCommand
};
static PaintMethod
method = PointMethod;
static XColor
border_color = { 0, 0, 0, 0, 0, 0 }; /* Also fill 'pad' field */
char
command[MaxTextExtent],
text[MaxTextExtent];
Cursor
cursor;
int
entry,
id,
x,
x_offset,
y,
y_offset;
register int
i;
register PixelPacket
*q;
unsigned int
height,
width;
unsigned long
state;
XEvent
event;
/*
Map Command widget.
*/
(void) CloneString(&windows->command.name,"Matte Edit");
windows->command.data=4;
(void) MagickXCommandWidget(display,windows,MatteEditMenu,(XEvent *) NULL);
(void) XMapRaised(display,windows->command.id);
MagickXClientMessage(display,windows->image.id,windows->im_protocols,
windows->im_update_widget,CurrentTime);
/*
Make cursor.
*/
cursor=MagickXMakeCursor(display,windows->image.id,windows->map_info->colormap,
resource_info->background_color,resource_info->foreground_color);
(void) XDefineCursor(display,windows->image.id,cursor);
/*
Track pointer until button 1 is pressed.
*/
MagickXQueryPosition(display,windows->image.id,&x,&y);
(void) XSelectInput(display,windows->image.id,
windows->image.attributes.event_mask | PointerMotionMask);
state=DefaultState;
do
{
if (windows->info.mapped)
{
/*
Display pointer position.
*/
FormatString(text," %+d%+d ",x+windows->image.x,y+windows->image.y);
MagickXInfoWidget(display,windows,text);
}
/*
Wait for next event.
*/
MagickXScreenEvent(display,windows,&event);
if (event.xany.window == windows->command.id)
{
/*
Select a command from the Command widget.
*/
id=MagickXCommandWidget(display,windows,MatteEditMenu,&event);
if (id < 0)
{
(void) XDefineCursor(display,windows->image.id,cursor);
continue;
}
switch (MatteEditCommands[id])
{
case MatteEditMethod:
{
const char
* const MethodMenu[]=
{
"point",
"replace",
"floodfill",
"filltoborder",
"reset",
(char *) NULL,
};
/*
Select a method from the pop-up menu.
*/
entry=
MagickXMenuWidget(display,windows,MatteEditMenu[id],MethodMenu,command);
if (entry >= 0)
method=(PaintMethod) entry;
break;
}
case MatteEditBorderCommand:
{
char
*ColorMenu[MaxNumberPens];
int
pen_number;
/*
Initialize menu selections.
*/
for (i=0; i < (int) (MaxNumberPens-2); i++)
ColorMenu[i]=resource_info->pen_colors[i];
ColorMenu[MaxNumberPens-2]=(char *) "Browser...";
ColorMenu[MaxNumberPens-1]=(char *) NULL;
/*
Select a pen color from the pop-up menu.
*/
pen_number=MagickXMenuWidget(display,windows,MatteEditMenu[id],
(const char **) ColorMenu,command);
if (pen_number < 0)
break;
if (pen_number == (MaxNumberPens-2))
{
static char
color_name[MaxTextExtent] = "gray";
/*
Select a pen color from a dialog.
*/
resource_info->pen_colors[pen_number]=color_name;
MagickXColorBrowserWidget(display,windows,"Select",color_name);
if (*color_name == '\0')
break;
}
/*
Set border color.
*/
(void) XParseColor(display,windows->map_info->colormap,
resource_info->pen_colors[pen_number],&border_color);
break;
}
case MatteEditFuzzCommand:
{
static char
fuzz[MaxTextExtent];
const char
* const FuzzMenu[]=
{
"0%",
"2%",
"5%",
"10%",
"15%",
"Dialog...",
(char *) NULL,
};
/*
Select a command from the pop-up menu.
*/
entry=MagickXMenuWidget(display,windows,MatteEditMenu[id],FuzzMenu,
command);
if (entry < 0)
break;
if (entry != 5)
{
(*image)->fuzz=StringToDouble(FuzzMenu[entry],MaxRGB);
break;
}
(void) strcpy(fuzz,"20%");
(void) MagickXDialogWidget(display,windows,"Ok",
"Enter fuzz factor (0.0 - 99.9%):",fuzz);
if (*fuzz == '\0')
break;
(void) strcat(fuzz,"%");
(*image)->fuzz=StringToDouble(fuzz,MaxRGB);
break;
}
case MatteEditValueCommand:
{
static char
message[MaxTextExtent];
const char
* const MatteMenu[]=
{
"Opaque",
"Transparent",
"Dialog...",
(char *) NULL,
};
/*
Select a command from the pop-up menu.
*/
entry=MagickXMenuWidget(display,windows,MatteEditMenu[id],MatteMenu,
command);
if (entry < 0)
break;
if (entry != 2)
{
FormatString(matte,"%lu",(unsigned long) OpaqueOpacity);
if (LocaleCompare(MatteMenu[entry],"Transparent") == 0)
FormatString(matte,"%lu",(unsigned long) TransparentOpacity);
break;
}
FormatString(message,"Enter matte value (0 - %lu):",(unsigned long) MaxRGB);
(void) MagickXDialogWidget(display,windows,"Matte",message,matte);
if (*matte == '\0')
break;
break;
}
case MatteEditUndoCommand:
{
(void) MagickXMagickCommand(display,resource_info,windows,UndoCommand,
image);
break;
}
case MatteEditHelpCommand:
{
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Matte Edit",
ImageMatteEditHelp,
sizeof(ImageMatteEditHelp));
break;
}
case MatteEditDismissCommand:
{
/*
Prematurely exit.
*/
state|=EscapeState;
state|=ExitState;
break;
}
default:
break;
}
(void) XDefineCursor(display,windows->image.id,cursor);
continue;
}
switch (event.type)
{
case ButtonPress:
{
if (event.xbutton.button != Button1)
break;
if ((event.xbutton.window != windows->image.id) &&
(event.xbutton.window != windows->magnify.id))
break;
/*
Update matte data.
*/
x=event.xbutton.x;
y=event.xbutton.y;
(void) MagickXMagickCommand(display,resource_info,windows,
SaveToUndoBufferCommand,image);
state|=UpdateConfigurationState;
break;
}
case ButtonRelease:
{
if (event.xbutton.button != Button1)
break;
if ((event.xbutton.window != windows->image.id) &&
(event.xbutton.window != windows->magnify.id))
break;
/*
Update colormap information.
*/
x=event.xbutton.x;
y=event.xbutton.y;
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
MagickXInfoWidget(display,windows,text);
(void) XDefineCursor(display,windows->image.id,cursor);
state&=(~UpdateConfigurationState);
break;
}
case Expose:
break;
case KeyPress:
{
char
command[MaxTextExtent];
KeySym
key_symbol;
if (event.xkey.window == windows->magnify.id)
{
Window
window;
window=windows->magnify.id;
while (XCheckWindowEvent(display,window,KeyPressMask,&event));
}
if (event.xkey.window != windows->image.id)
break;
/*
Respond to a user key press.
*/
(void) XLookupString((XKeyEvent *) &event.xkey,command,sizeof(command),
&key_symbol,(XComposeStatus *) NULL);
switch ((int) key_symbol)
{
case XK_Escape:
case XK_F20:
{
/*
Prematurely exit.
*/
state|=ExitState;
break;
}
case XK_F1:
case XK_Help:
{
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Matte Edit",
ImageMatteEditHelp,
sizeof(ImageMatteEditHelp));
break;
}
default:
{
(void) XBell(display,0);
break;
}
}
break;
}
case MotionNotify:
{
/*
Map and unmap Info widget as cursor crosses its boundaries.
*/
x=event.xmotion.x;
y=event.xmotion.y;
if (windows->info.mapped)
{
if ((x < (int) (windows->info.x+windows->info.width)) &&
(y < (int) (windows->info.y+windows->info.height)))
(void) XWithdrawWindow(display,windows->info.id,
windows->info.screen);
}
else
if ((x > (int) (windows->info.x+windows->info.width)) ||
(y > (int) (windows->info.y+windows->info.height)))
(void) XMapWindow(display,windows->info.id);
break;
}
default:
break;
}
if (event.xany.window == windows->magnify.id)
{
x=windows->magnify.x-windows->image.x;
y=windows->magnify.y-windows->image.y;
}
x_offset=x;
y_offset=y;
if (state & UpdateConfigurationState)
{
int
x,
y;
/*
Matte edit is relative to image configuration.
*/
(void) XClearArea(display,windows->image.id,x_offset,y_offset,1,1,True);
XPutPixel(windows->image.ximage,x_offset,y_offset,
windows->pixel_info->background_color.pixel);
width=(unsigned int) (*image)->columns;
height=(unsigned int) (*image)->rows;
x=0;
y=0;
if (windows->image.crop_geometry != (char *) NULL)
(void) XParseGeometry(windows->image.crop_geometry,&x,&y,
&width,&height);
x_offset=
width*(windows->image.x+x_offset)/windows->image.ximage->width+x;
y_offset=
height*(windows->image.y+y_offset)/windows->image.ximage->height+y;
if ((x_offset < 0) || (y_offset < 0))
continue;
if ((x_offset >= (int) (*image)->columns) ||
(y_offset >= (int) (*image)->rows))
continue;
(void) SetImageType(*image,TrueColorMatteType);
switch (method)
{
case PointMethod:
default:
{
/*
Update matte information using point algorithm.
*/
q=GetImagePixels(*image,x_offset,y_offset,1,1);
if (q == (PixelPacket *) NULL)
break;
q->opacity=(Quantum) MagickAtoL(matte);
(void) SyncImagePixels(*image);
break;
}
case ReplaceMethod:
{
PixelPacket
target;
/*
Update matte information using replace algorithm.
*/
(void) AcquireOnePixelByReference(*image,&target,x_offset,y_offset,&((*image)->exception));
for (y=0; y < (long) (*image)->rows; y++)
{
q=GetImagePixels(*image,0,y,(*image)->columns,1);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (int) (*image)->columns; x++)
{
if (FuzzyColorMatch(q,&target,(*image)->fuzz))
q->opacity=(Quantum) MagickAtoL(matte);
q++;
}
if (!SyncImagePixels(*image))
break;
}
break;
}
case FloodfillMethod:
case FillToBorderMethod:
{
PixelPacket
target;
/*
Update matte information using floodfill algorithm.
*/
(void) AcquireOnePixelByReference(*image,&target,x_offset,y_offset,&((*image)->exception));
if (method == FillToBorderMethod)
{
target.red=ScaleShortToQuantum(border_color.red);
target.green=ScaleShortToQuantum(border_color.green);
target.blue=ScaleShortToQuantum(border_color.blue);
}
(void) MatteFloodfillImage(*image,target,MagickAtoI(matte),x_offset,
y_offset,method);
break;
}
case ResetMethod:
{
/*
Update matte information using reset algorithm.
*/
(void) SetImageType(*image,TrueColorType);
for (y=0; y < (long) (*image)->rows; y++)
{
q=SetImagePixels(*image,0,y,(*image)->columns,1);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (int) (*image)->columns; x++)
{
q->opacity=(Quantum) MagickAtoL(matte);
q++;
}
if (!SyncImagePixels(*image))
break;
}
if (MagickAtoL(matte) == OpaqueOpacity)
(*image)->matte=False;
break;
}
}
state&=(~UpdateConfigurationState);
}
} while (!(state & ExitState));
(void) XSelectInput(display,windows->image.id,
windows->image.attributes.event_mask);
MagickXSetCursorState(display,windows,False);
(void) XFreeCursor(display,cursor);
return(True);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X O p e n I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXOpenImage loads an image from a file.
%
% The format of the MagickXOpenImage method is:
%
% Image *MagickXOpenImage(Display *display,MagickXResourceInfo *resource_info,
% MagickXWindows *windows,const unsigned int command)
%
% A description of each parameter follows:
%
% o nexus: Method MagickXOpenImage returns an image if can be loaded
% successfully. Otherwise a null image is returned.
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o resource_info: Specifies a pointer to a X11 MagickXResourceInfo structure.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
% o command: A value other than zero indicates that the file is selected
% from the command line argument list.
%
%
*/
static Image *MagickXOpenImage(Display *display,MagickXResourceInfo *resource_info,
MagickXWindows *windows,const unsigned int command)
{
ExceptionInfo
exception;
Image
*nexus;
ImageInfo
*image_info;
MonitorHandler
handler;
static char
filename[MaxTextExtent] = "\0";
/*
Request file name from user.
*/
if (!command)
MagickXFileBrowserWidget(display,windows,"Open",filename);
else
{
char
**filelist,
**files;
int
count,
status;
register int
i,
j;
/*
Select next image from the command line.
*/
status=XGetCommand(display,windows->image.id,&files,&count);
if (!status)
{
MagickError(XServerError,UnableToGetProperty,
MagickMsg(ResourceLimitError,UnableToSelectImage));
return((Image *) NULL);
}
filelist=MagickAllocateMemory(char **,count*sizeof(char *));
if (filelist == (char **) NULL)
{
MagickError3(ResourceLimitError,MemoryAllocationFailed,
UnableToSelectImage);
(void) XFreeStringList(files);
return((Image *) NULL);
}
j=0;
for (i=1; i < count; i++)
if (*files[i] != '-')
filelist[j++]=files[i];
filelist[j]=(char *) NULL;
MagickXListBrowserWidget(display,windows,&windows->widget,
(const char **) filelist,"Load","Select Image to Load:",filename);
MagickFreeMemory(filelist);
(void) XFreeStringList(files);
}
if (*filename == '\0')
return((Image *) NULL);
image_info=CloneImageInfo(resource_info->image_info);
(void) strlcpy(image_info->filename,filename,MaxTextExtent);
GetExceptionInfo(&exception);
(void) SetImageInfo(image_info,SETMAGICK_READ,&exception);
if (LocaleCompare(image_info->magick,"X") == 0)
{
char
seconds[MaxTextExtent];
/*
User may want to delay the X server screen grab.
*/
(void) strcpy(seconds,"0");
(void) MagickXDialogWidget(display,windows,"Grab","Enter any delay in seconds:",
seconds);
if (*seconds == '\0')
return((Image *) NULL);
MagickXDelay(display,1000*MagickAtoL(seconds));
}
if ((LocaleCompare(image_info->magick,"CMYK") == 0) ||
(LocaleCompare(image_info->magick,"GRAY") == 0) ||
(LocaleCompare(image_info->magick,"MAP") == 0) ||
(LocaleCompare(image_info->magick,"Matte") == 0) ||
(LocaleCompare(image_info->magick,"RGB") == 0) ||
(LocaleCompare(image_info->magick,"RGBA") == 0) ||
(LocaleCompare(image_info->magick,"TEXT") == 0) ||
(LocaleCompare(image_info->magick,"TILE") == 0) ||
(LocaleCompare(image_info->magick,"UYVY") == 0) ||
(LocaleCompare(image_info->magick,"XC") == 0) ||
(LocaleCompare(image_info->magick,"YUV") == 0))
{
char
geometry[MaxTextExtent];
/*
Request image size from the user.
*/
(void) strcpy(geometry,"512x512");
if (image_info->size != (char *) NULL)
(void) strlcpy(geometry,image_info->size,MaxTextExtent);
(void) MagickXDialogWidget(display,windows,"Load","Enter the image geometry:",
geometry);
(void) CloneString(&image_info->size,geometry);
}
/*
Load the image.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
(void) strlcpy(image_info->filename,filename,MaxTextExtent);
handler=(MonitorHandler) NULL;
if (LocaleCompare(image_info->magick,"X") == 0)
handler=SetMonitorHandler((MonitorHandler) NULL);
DestroyExceptionInfo(&exception);
GetExceptionInfo(&exception);
nexus=ReadImage(image_info,&exception);
if (exception.severity != UndefinedException)
CatchException(&exception);
if (LocaleCompare(image_info->magick,"X") == 0)
(void) SetMonitorHandler(handler);
MagickXSetCursorState(display,windows,False);
if (nexus != (Image *) NULL)
MagickXClientMessage(display,windows->image.id,windows->im_protocols,
windows->im_next_image,CurrentTime);
else
{
char
*text,
**textlist;
size_t
length;
/*
Unknown image format.
*/
text=(char *) FileToBlob(filename,&length,&exception);
if (text == (char *) NULL)
return((Image *) NULL);
textlist=StringToList(text);
if (textlist != (char **) NULL)
{
char
title[MaxTextExtent];
register int
i;
FormatString(title,"Unknown format: %.1024s",filename);
MagickXTextViewWidget(display,resource_info,windows,True,title,
(const char **) textlist);
for (i=0; textlist[i] != (char *) NULL; i++)
MagickFreeMemory(textlist[i]);
MagickFreeMemory(textlist);
}
MagickFreeMemory(text);
}
DestroyExceptionInfo(&exception);
DestroyImageInfo(image_info);
return(nexus);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X P a n I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXPanImage pans the image until the mouse button is released.
%
% The format of the MagickXPanImage method is:
%
% void MagickXPanImage(Display *display,MagickXWindows *windows,XEvent *event)
%
% A description of each parameter follows:
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
% o event: Specifies a pointer to a XEvent structure. If it is NULL,
% the entire image is refreshed.
%
*/
static void MagickXPanImage(Display *display,MagickXWindows *windows,XEvent *event)
{
char
text[MaxTextExtent];
Cursor
cursor;
double
x_factor,
y_factor;
RectangleInfo
pan_info;
unsigned long
state;
/*
Define cursor.
*/
if ((windows->image.ximage->width > (int) windows->image.width) &&
(windows->image.ximage->height > (int) windows->image.height))
cursor=XCreateFontCursor(display,XC_fleur);
else
if (windows->image.ximage->width > (int) windows->image.width)
cursor=XCreateFontCursor(display,XC_sb_h_double_arrow);
else
if (windows->image.ximage->height > (int) windows->image.height)
cursor=XCreateFontCursor(display,XC_sb_v_double_arrow);
else
cursor=XCreateFontCursor(display,XC_arrow);
(void) XDefineCursor(display,windows->pan.id,cursor);
/*
Pan image as pointer moves until the mouse button is released.
*/
x_factor=(double) windows->image.ximage->width/windows->pan.width;
y_factor=(double) windows->image.ximage->height/windows->pan.height;
pan_info.x=0;
pan_info.y=0;
pan_info.width=
windows->pan.width*windows->image.width/windows->image.ximage->width;
pan_info.height=
windows->pan.height*windows->image.height/windows->image.ximage->height;
state=UpdateConfigurationState;
do
{
switch (event->type)
{
case ButtonPress:
{
/*
User choose an initial pan location.
*/
pan_info.x=event->xbutton.x;
pan_info.y=event->xbutton.y;
state|=UpdateConfigurationState;
break;
}
case ButtonRelease:
{
/*
User has finished panning the image.
*/
pan_info.x=event->xbutton.x;
pan_info.y=event->xbutton.y;
state|=UpdateConfigurationState | ExitState;
break;
}
case MotionNotify:
{
pan_info.x=event->xmotion.x;
pan_info.y=event->xmotion.y;
state|=UpdateConfigurationState;
}
default:
break;
}
if (state & UpdateConfigurationState)
{
/*
Check boundary conditions.
*/
if (pan_info.x < (int) (pan_info.width/2))
pan_info.x=0;
else
pan_info.x=(int) (x_factor*(pan_info.x-(pan_info.width/2)));
if (pan_info.x < 0)
pan_info.x=0;
else
if ((int) (pan_info.x+windows->image.width) >
windows->image.ximage->width)
pan_info.x=(long)
(windows->image.ximage->width-windows->image.width);
if (pan_info.y < (long) (pan_info.height/2))
pan_info.y=0;
else
pan_info.y=(long) (y_factor*(pan_info.y-(pan_info.height/2)));
if (pan_info.y < 0)
pan_info.y=0;
else
if ((int) (pan_info.y+windows->image.height) >
windows->image.ximage->height)
pan_info.y=(long)
(windows->image.ximage->height-windows->image.height);
if ((windows->image.x != (int) pan_info.x) ||
(windows->image.y != (int) pan_info.y))
{
/*
Display image pan offset.
*/
windows->image.x=(int) pan_info.x;
windows->image.y=(int) pan_info.y;
FormatString(text," %ux%u%+d%+d ",windows->image.width,
windows->image.height,windows->image.x,windows->image.y);
MagickXInfoWidget(display,windows,text);
/*
Refresh Image window.
*/
MagickXDrawPanRectangle(display,windows);
MagickXRefreshWindow(display,&windows->image,(XEvent *) NULL);
}
state&=(~UpdateConfigurationState);
}
/*
Wait for next event.
*/
if (!(state & ExitState))
MagickXScreenEvent(display,windows,event);
} while (!(state & ExitState));
/*
Restore cursor.
*/
(void) XDefineCursor(display,windows->pan.id,windows->pan.cursor);
(void) XFreeCursor(display,cursor);
(void) XWithdrawWindow(display,windows->info.id,windows->info.screen);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X P a s t e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXPasteImage pastes an image previously saved with MagickXCropImage
% in the X window image at a location the user chooses with the pointer.
%
% The format of the MagickXPasteImage method is:
%
% unsigned int MagickXPasteImage(Display *display,MagickXResourceInfo *resource_info,
% MagickXWindows *windows,Image *image)
%
% A description of each parameter follows:
%
% o status: Method MagickXPasteImage returns True if the image is
% pasted. False is returned is there is a memory shortage or if the
% image fails to be pasted.
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o resource_info: Specifies a pointer to a X11 MagickXResourceInfo structure.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
% o image: Specifies a pointer to an Image structure; returned from
% ReadImage.
%
*/
static unsigned int MagickXPasteImage(Display *display,MagickXResourceInfo *resource_info,
MagickXWindows *windows,Image *image)
{
const char
* const PasteMenu[]=
{
"Operator",
"Help",
"Dismiss",
(char *) NULL
};
static const ModeType
PasteCommands[]=
{
PasteOperatorsCommand,
PasteHelpCommand,
PasteDismissCommand
};
static CompositeOperator
operation = CopyCompositeOp;
char
text[MaxTextExtent];
Cursor
cursor;
double
scale_factor;
Image
*paste_image;
int
id,
x,
y;
RectangleInfo
highlight_info,
paste_info;
unsigned int
height,
width;
unsigned long
state;
XEvent
event;
/*
Copy image.
*/
if (resource_info->copy_image == (Image *) NULL)
return(False);
paste_image=CloneImage(resource_info->copy_image,0,0,True,&image->exception);
/*
Map Command widget.
*/
(void) CloneString(&windows->command.name,"Paste");
windows->command.data=1;
(void) MagickXCommandWidget(display,windows,PasteMenu,(XEvent *) NULL);
(void) XMapRaised(display,windows->command.id);
MagickXClientMessage(display,windows->image.id,windows->im_protocols,
windows->im_update_widget,CurrentTime);
/*
Track pointer until button 1 is pressed.
*/
MagickXSetCursorState(display,windows,False);
MagickXQueryPosition(display,windows->image.id,&x,&y);
(void) XSelectInput(display,windows->image.id,
windows->image.attributes.event_mask | PointerMotionMask);
paste_info.x=windows->image.x+x;
paste_info.y=windows->image.y+y;
paste_info.width=0;
paste_info.height=0;
cursor=XCreateFontCursor(display,XC_ul_angle);
(void) XSetFunction(display,windows->image.highlight_context,GXinvert);
state=DefaultState;
do
{
if (windows->info.mapped)
{
/*
Display pointer position.
*/
FormatString(text," %+ld%+ld ",paste_info.x,paste_info.y);
MagickXInfoWidget(display,windows,text);
}
highlight_info=paste_info;
highlight_info.x=paste_info.x-windows->image.x;
highlight_info.y=paste_info.y-windows->image.y;
MagickXHighlightRectangle(display,windows->image.id,
windows->image.highlight_context,&highlight_info);
/*
Wait for next event.
*/
MagickXScreenEvent(display,windows,&event);
MagickXHighlightRectangle(display,windows->image.id,
windows->image.highlight_context,&highlight_info);
if (event.xany.window == windows->command.id)
{
/*
Select a command from the Command widget.
*/
id=MagickXCommandWidget(display,windows,PasteMenu,&event);
if (id < 0)
continue;
switch (PasteCommands[id])
{
case PasteOperatorsCommand:
{
char
command[MaxTextExtent];
const char
* const OperatorMenu[]=
{
"Over",
"In",
"Out",
"Atop",
"Xor",
"Plus",
"Minus",
"Add",
"Subtract",
"Difference",
"Multiply",
"Bumpmap",
"Copy",
"CopyRed",
"CopyGreen",
"CopyBlue",
"CopyOpacity",
"Clear",
(char *) NULL,
};
/*
Select a command from the pop-up menu.
*/
operation=(CompositeOperator) (MagickXMenuWidget(display,windows,
PasteMenu[id],OperatorMenu,command)+1);
break;
}
case PasteHelpCommand:
{
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Image Composite",
ImagePasteHelp,
sizeof(ImagePasteHelp));
break;
}
case PasteDismissCommand:
{
/*
Prematurely exit.
*/
state|=EscapeState;
state|=ExitState;
break;
}
default:
break;
}
continue;
}
switch (event.type)
{
case ButtonPress:
{
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),
"Button Press: 0x%lx %u +%d+%d",event.xbutton.window,
event.xbutton.button,event.xbutton.x,event.xbutton.y);
if (event.xbutton.button != Button1)
break;
if (event.xbutton.window != windows->image.id)
break;
/*
Paste rectangle is relative to image configuration.
*/
width=(unsigned int) image->columns;
height=(unsigned int) image->rows;
x=0;
y=0;
if (windows->image.crop_geometry != (char *) NULL)
(void) XParseGeometry(windows->image.crop_geometry,&x,&y,
&width,&height);
scale_factor=(double) windows->image.ximage->width/width;
paste_info.width=(unsigned int) (scale_factor*paste_image->columns+0.5);
scale_factor=(double) windows->image.ximage->height/height;
paste_info.height=(unsigned int) (scale_factor*paste_image->rows+0.5);
(void) XDefineCursor(display,windows->image.id,cursor);
paste_info.x=windows->image.x+event.xbutton.x;
paste_info.y=windows->image.y+event.xbutton.y;
break;
}
case ButtonRelease:
{
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),
"Button Release: 0x%lx %u +%d+%d",event.xbutton.window,
event.xbutton.button,event.xbutton.x,event.xbutton.y);
if (event.xbutton.button != Button1)
break;
if (event.xbutton.window != windows->image.id)
break;
if ((paste_info.width != 0) && (paste_info.height != 0))
{
/*
User has selected the location of the paste image.
*/
paste_info.x=windows->image.x+event.xbutton.x;
paste_info.y=windows->image.y+event.xbutton.y;
state|=ExitState;
}
break;
}
case Expose:
break;
case KeyPress:
{
char
command[MaxTextExtent];
KeySym
key_symbol;
int
length;
if (event.xkey.window != windows->image.id)
break;
/*
Respond to a user key press.
*/
length=XLookupString((XKeyEvent *) &event.xkey,command,sizeof(command),
&key_symbol,(XComposeStatus *) NULL);
*(command+length)='\0';
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),
"Key press: 0x%lx (%.1024s)",key_symbol,command);
switch ((int) key_symbol)
{
case XK_Escape:
case XK_F20:
{
/*
Prematurely exit.
*/
DestroyImage(paste_image);
state|=EscapeState;
state|=ExitState;
break;
}
case XK_F1:
case XK_Help:
{
(void) XSetFunction(display,windows->image.highlight_context,
GXcopy);
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Image Composite",
ImagePasteHelp,
sizeof(ImagePasteHelp));
(void) XSetFunction(display,windows->image.highlight_context,
GXinvert);
break;
}
default:
{
(void) XBell(display,0);
break;
}
}
break;
}
case MotionNotify:
{
/*
Map and unmap Info widget as text cursor crosses its boundaries.
*/
x=event.xmotion.x;
y=event.xmotion.y;
if (windows->info.mapped)
{
if ((x < (int) (windows->info.x+windows->info.width)) &&
(y < (int) (windows->info.y+windows->info.height)))
(void) XWithdrawWindow(display,windows->info.id,
windows->info.screen);
}
else
if ((x > (int) (windows->info.x+windows->info.width)) ||
(y > (int) (windows->info.y+windows->info.height)))
(void) XMapWindow(display,windows->info.id);
paste_info.x=windows->image.x+x;
paste_info.y=windows->image.y+y;
break;
}
default:
{
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),"Event type: %d",
event.type);
break;
}
}
} while (!(state & ExitState));
(void) XSelectInput(display,windows->image.id,
windows->image.attributes.event_mask);
(void) XSetFunction(display,windows->image.highlight_context,GXcopy);
MagickXSetCursorState(display,windows,False);
(void) XFreeCursor(display,cursor);
if (state & EscapeState)
return(True);
/*
Image pasting is relative to image configuration.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
width=(unsigned int) image->columns;
height=(unsigned int) image->rows;
x=0;
y=0;
if (windows->image.crop_geometry != (char *) NULL)
(void) XParseGeometry(windows->image.crop_geometry,&x,&y,&width,&height);
scale_factor=(double) width/windows->image.ximage->width;
paste_info.x+=x;
paste_info.x=(int) (scale_factor*paste_info.x+0.5);
paste_info.width=(unsigned int) (scale_factor*paste_info.width+0.5);
scale_factor=(double) height/windows->image.ximage->height;
paste_info.y+=y;
paste_info.y=(int) (scale_factor*paste_info.y*scale_factor+0.5);
paste_info.height=(unsigned int) (scale_factor*paste_info.height+0.5);
/*
Paste image with X Image window.
*/
(void) CompositeImage(image,operation,paste_image,paste_info.x,paste_info.y);
DestroyImage(paste_image);
MagickXSetCursorState(display,windows,False);
/*
Update image colormap.
*/
MagickXConfigureImageColormap(display,resource_info,windows,image);
(void) MagickXConfigureImage(display,resource_info,windows,image);
return(True);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X P r i n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXPrintImage prints an image to a Postscript printer.
%
% The format of the MagickXPrintImage method is:
%
% unsigned int MagickXPrintImage(Display *display,MagickXResourceInfo *resource_info,
% MagickXWindows *windows,Image *image)
%
% A description of each parameter follows:
%
% o status: Method MagickXPrintImage return True if the image is
% printed. False is returned is there is a memory shortage or if the
% image fails to print.
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o resource_info: Specifies a pointer to a X11 MagickXResourceInfo structure.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
% o image: Specifies a pointer to an Image structure; returned from
% ReadImage.
%
%
*/
static unsigned int MagickXPrintImage(Display *display,MagickXResourceInfo *resource_info,
MagickXWindows *windows,Image *image)
{
char
filename[MaxTextExtent],
geometry[MaxTextExtent];
Image
*print_image;
ImageInfo
*image_info;
unsigned int
status=True;
const char
* const PageSizes[]=
{
PAGE_SIZES
};
/*
Request Postscript page geometry from user.
*/
image_info=CloneImageInfo(resource_info->image_info);
FormatString(geometry,"Letter");
if (image_info->page != (char *) NULL)
(void) strlcpy(geometry,image_info->page,MaxTextExtent);
MagickXListBrowserWidget(display,windows,&windows->widget,PageSizes,"Select",
"Select Postscript Page Geometry:",geometry);
if (*geometry == '\0')
return(True);
image_info->page=GetPageGeometry(geometry);
/*
Apply image transforms.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
print_image=CloneImage(image,0,0,True,&image->exception);
if (print_image == (Image *) NULL)
return(False);
FormatString(geometry,"%dx%d!",windows->image.ximage->width,
windows->image.ximage->height);
TransformImage(&print_image,windows->image.crop_geometry,geometry);
/*
Print image.
*/
if (!AcquireTemporaryFileName(print_image->magick_filename))
{
MagickXNoticeWidget(display,windows,"Unable to open temporary file:",
print_image->magick_filename);
status=False;
goto error_return;
}
if (!AcquireTemporaryFileName(filename))
{
MagickXNoticeWidget(display,windows,"Unable to open temporary file:",
filename);
status=False;
goto error_return;
}
FormatString(print_image->filename,"print:%s",filename);
status=WriteImage(image_info,print_image);
error_return:
if (MagickFail == status)
CopyException(&image->exception,&print_image->exception);
DestroyImage(print_image);
DestroyImageInfo(image_info);
MagickXSetCursorState(display,windows,False);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X R O I I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXROIImage applies an image processing technique to a region
% of interest.
%
% The format of the MagickXROIImage method is:
%
% unsigned int MagickXROIImage(Display *display,MagickXResourceInfo *resource_info,
% MagickXWindows *windows,Image **image)
%
% A description of each parameter follows:
%
% o status: Method MagickXROIImage returns True if the image is
% cropped. False is returned is there is a memory shortage or if the
% image fails to be cropped.
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o resource_info: Specifies a pointer to a X11 MagickXResourceInfo structure.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
% o image: Specifies a pointer to an Image structure; returned from
% ReadImage.
%
%
*/
static unsigned int MagickXROIImage(Display *display,MagickXResourceInfo *resource_info,
MagickXWindows *windows,Image **image)
{
#define ApplyMenus 7
const char
* const ROIMenu[]=
{
"Help",
"Dismiss",
(char *) NULL
},
* const ApplyMenu[]=
{
"File",
"Edit",
"Transform",
"Enhance",
"Effects",
"F/X",
"Miscellany",
"Help",
"Dismiss",
(char *) NULL
},
* const FileMenu[]=
{
"Save...",
"Print...",
(char *) NULL
},
* const EditMenu[]=
{
"Undo",
"Redo",
(char *) NULL
},
* const TransformMenu[]=
{
"Flop",
"Flip",
"Rotate Right",
"Rotate Left",
(char *) NULL
},
* const EnhanceMenu[]=
{
"Hue...",
"Saturation...",
"Brightness...",
"Gamma...",
"Spiff",
"Dull",
"Equalize",
"Normalize",
"Negate",
"Grayscale",
"Map...",
"Quantize...",
(char *) NULL
},
* const EffectsMenu[]=
{
"Despeckle",
"Emboss",
"Reduce Noise",
"Add Noise",
"Sharpen...",
"Blur...",
"Threshold...",
"Edge Detect...",
"Spread...",
"Shade...",
"Raise...",
"Segment...",
(char *) NULL
},
* const FXMenu[]=
{
"Solarize...",
"Swirl...",
"Implode...",
"Wave...",
"Oil Paint...",
"Charcoal Draw...",
(char *) NULL
},
* const MiscellanyMenu[]=
{
"Image Info",
"Zoom Image",
"Show Preview...",
"Show Histogram",
"Show Matte",
(char *) NULL
};
const char
* const *Menus[ApplyMenus]=
{
FileMenu,
EditMenu,
TransformMenu,
EnhanceMenu,
EffectsMenu,
FXMenu,
MiscellanyMenu
};
static const CommandType
ApplyCommands[]=
{
NullCommand,
NullCommand,
NullCommand,
NullCommand,
NullCommand,
NullCommand,
NullCommand,
HelpCommand,
QuitCommand
},
FileCommands[]=
{
SaveCommand,
PrintCommand
},
EditCommands[]=
{
UndoCommand,
RedoCommand
},
TransformCommands[]=
{
FlopCommand,
FlipCommand,
RotateRightCommand,
RotateLeftCommand
},
EnhanceCommands[]=
{
HueCommand,
SaturationCommand,
BrightnessCommand,
GammaCommand,
SpiffCommand,
DullCommand,
EqualizeCommand,
NormalizeCommand,
NegateCommand,
GrayscaleCommand,
MapCommand,
QuantizeCommand
},
EffectsCommands[]=
{
DespeckleCommand,
EmbossCommand,
ReduceNoiseCommand,
AddNoiseCommand,
SharpenCommand,
BlurCommand,
EdgeDetectCommand,
SpreadCommand,
ShadeCommand,
RaiseCommand,
SegmentCommand
},
FXCommands[]=
{
SolarizeCommand,
SwirlCommand,
ImplodeCommand,
WaveCommand,
OilPaintCommand,
CharcoalDrawCommand
},
MiscellanyCommands[]=
{
InfoCommand,
ZoomCommand,
ShowPreviewCommand,
ShowHistogramCommand,
ShowMatteCommand
},
ROICommands[]=
{
ROIHelpCommand,
ROIDismissCommand
};
const CommandType
*Commands[ApplyMenus]=
{
FileCommands,
EditCommands,
TransformCommands,
EnhanceCommands,
EffectsCommands,
FXCommands,
MiscellanyCommands
};
char
command[MaxTextExtent],
text[MaxTextExtent];
CommandType
command_type;
Cursor
cursor;
double
scale_factor;
Image
*roi_image;
int
entry,
id,
x,
y;
MonitorHandler
handler;
RectangleInfo
crop_info,
highlight_info,
roi_info;
unsigned int
height,
width;
unsigned long
state;
XEvent
event;
/*
Map Command widget.
*/
(void) CloneString(&windows->command.name,"ROI");
windows->command.data=0;
(void) MagickXCommandWidget(display,windows,ROIMenu,(XEvent *) NULL);
(void) XMapRaised(display,windows->command.id);
MagickXClientMessage(display,windows->image.id,windows->im_protocols,
windows->im_update_widget,CurrentTime);
/*
Track pointer until button 1 is pressed.
*/
MagickXQueryPosition(display,windows->image.id,&x,&y);
(void) XSelectInput(display,windows->image.id,
windows->image.attributes.event_mask | PointerMotionMask);
roi_info.x=windows->image.x+x;
roi_info.y=windows->image.y+y;
roi_info.width=0;
roi_info.height=0;
cursor=XCreateFontCursor(display,XC_fleur);
state=DefaultState;
do
{
if (windows->info.mapped)
{
/*
Display pointer position.
*/
FormatString(text," %+ld%+ld ",roi_info.x,roi_info.y);
MagickXInfoWidget(display,windows,text);
}
/*
Wait for next event.
*/
MagickXScreenEvent(display,windows,&event);
if (event.xany.window == windows->command.id)
{
/*
Select a command from the Command widget.
*/
id=MagickXCommandWidget(display,windows,ROIMenu,&event);
if (id < 0)
continue;
switch (ROICommands[id])
{
case ROIHelpCommand:
{
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Region of Interest",
ImageROIHelp,
sizeof(ImageROIHelp));
break;
}
case ROIDismissCommand:
{
/*
Prematurely exit.
*/
state|=EscapeState;
state|=ExitState;
break;
}
default:
break;
}
continue;
}
switch (event.type)
{
case ButtonPress:
{
if (event.xbutton.button != Button1)
break;
if (event.xbutton.window != windows->image.id)
break;
/*
Note first corner of region of interest rectangle-- exit loop.
*/
(void) XDefineCursor(display,windows->image.id,cursor);
roi_info.x=windows->image.x+event.xbutton.x;
roi_info.y=windows->image.y+event.xbutton.y;
state|=ExitState;
break;
}
case ButtonRelease:
break;
case Expose:
break;
case KeyPress:
{
KeySym
key_symbol;
if (event.xkey.window != windows->image.id)
break;
/*
Respond to a user key press.
*/
(void) XLookupString((XKeyEvent *) &event.xkey,command,sizeof(command),
&key_symbol,(XComposeStatus *) NULL);
switch ((int) key_symbol)
{
case XK_Escape:
case XK_F20:
{
/*
Prematurely exit.
*/
state|=EscapeState;
state|=ExitState;
break;
}
case XK_F1:
case XK_Help:
{
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Region of Interest",
ImageROIHelp,
sizeof(ImageROIHelp));
break;
}
default:
{
(void) XBell(display,0);
break;
}
}
break;
}
case MotionNotify:
{
/*
Map and unmap Info widget as text cursor crosses its boundaries.
*/
x=event.xmotion.x;
y=event.xmotion.y;
if (windows->info.mapped)
{
if ((x < (int) (windows->info.x+windows->info.width)) &&
(y < (int) (windows->info.y+windows->info.height)))
(void) XWithdrawWindow(display,windows->info.id,
windows->info.screen);
}
else
if ((x > (int) (windows->info.x+windows->info.width)) ||
(y > (int) (windows->info.y+windows->info.height)))
(void) XMapWindow(display,windows->info.id);
roi_info.x=windows->image.x+x;
roi_info.y=windows->image.y+y;
break;
}
default:
break;
}
} while (!(state & ExitState));
(void) XSelectInput(display,windows->image.id,
windows->image.attributes.event_mask);
if (state & EscapeState)
{
/*
User want to exit without region of interest.
*/
(void) XWithdrawWindow(display,windows->info.id,windows->info.screen);
(void) XFreeCursor(display,cursor);
return(True);
}
(void) XSetFunction(display,windows->image.highlight_context,GXinvert);
do
{
/*
Size rectangle as pointer moves until the mouse button is released.
*/
x=(int) roi_info.x;
y=(int) roi_info.y;
roi_info.width=0;
roi_info.height=0;
state=DefaultState;
do
{
highlight_info=roi_info;
highlight_info.x=roi_info.x-windows->image.x;
highlight_info.y=roi_info.y-windows->image.y;
if ((highlight_info.width > 3) && (highlight_info.height > 3))
{
/*
Display info and draw region of interest rectangle.
*/
if (!windows->info.mapped)
(void) XMapWindow(display,windows->info.id);
FormatString(text," %lux%lu%+ld%+ld",roi_info.width,roi_info.height,
roi_info.x,roi_info.y);
MagickXInfoWidget(display,windows,text);
MagickXHighlightRectangle(display,windows->image.id,
windows->image.highlight_context,&highlight_info);
}
else
if (windows->info.mapped)
(void) XWithdrawWindow(display,windows->info.id,windows->info.screen);
/*
Wait for next event.
*/
MagickXScreenEvent(display,windows,&event);
if ((highlight_info.width > 3) && (highlight_info.height > 3))
MagickXHighlightRectangle(display,windows->image.id,
windows->image.highlight_context,&highlight_info);
switch (event.type)
{
case ButtonPress:
{
roi_info.x=windows->image.x+event.xbutton.x;
roi_info.y=windows->image.y+event.xbutton.y;
break;
}
case ButtonRelease:
{
/*
User has committed to region of interest rectangle.
*/
roi_info.x=windows->image.x+event.xbutton.x;
roi_info.y=windows->image.y+event.xbutton.y;
MagickXSetCursorState(display,windows,False);
state|=ExitState;
if (LocaleCompare(windows->command.name,"Apply") == 0)
break;
(void) CloneString(&windows->command.name,"Apply");
windows->command.data=ApplyMenus;
(void) MagickXCommandWidget(display,windows,ApplyMenu,(XEvent *) NULL);
break;
}
case Expose:
break;
case MotionNotify:
{
roi_info.x=windows->image.x+event.xmotion.x;
roi_info.y=windows->image.y+event.xmotion.y;
}
default:
break;
}
if ((((int) roi_info.x != x) && ((int) roi_info.y != y)) ||
(state & ExitState))
{
/*
Check boundary conditions.
*/
if (roi_info.x < 0)
roi_info.x=0;
else
if (roi_info.x > (int) windows->image.ximage->width)
roi_info.x=windows->image.ximage->width;
if ((int) roi_info.x < x)
roi_info.width=(unsigned int) (x-roi_info.x);
else
{
roi_info.width=(unsigned int) (roi_info.x-x);
roi_info.x=x;
}
if (roi_info.y < 0)
roi_info.y=0;
else
if (roi_info.y > (int) windows->image.ximage->height)
roi_info.y=windows->image.ximage->height;
if ((int) roi_info.y < y)
roi_info.height=(unsigned int) (y-roi_info.y);
else
{
roi_info.height=(unsigned int) (roi_info.y-y);
roi_info.y=y;
}
}
} while (!(state & ExitState));
/*
Wait for user to grab a corner of the rectangle or press return.
*/
state=DefaultState;
command_type=NullCommand;
do
{
if (windows->info.mapped)
{
/*
Display pointer position.
*/
FormatString(text," %lux%lu%+ld%+ld",roi_info.width,roi_info.height,
roi_info.x,roi_info.y);
MagickXInfoWidget(display,windows,text);
}
highlight_info=roi_info;
highlight_info.x=roi_info.x-windows->image.x;
highlight_info.y=roi_info.y-windows->image.y;
if ((highlight_info.width <= 3) || (highlight_info.height <= 3))
{
state|=EscapeState;
state|=ExitState;
break;
}
if (state & UpdateRegionState)
{
(void) XSetFunction(display,windows->image.highlight_context,GXcopy);
switch (command_type)
{
case UndoCommand:
case RedoCommand:
{
(void) MagickXMagickCommand(display,resource_info,windows,command_type,
image);
break;
}
default:
{
/*
Region of interest is relative to image configuration.
*/
handler=SetMonitorHandler((MonitorHandler) NULL);
crop_info=roi_info;
width=(unsigned int) (*image)->columns;
height=(unsigned int) (*image)->rows;
x=0;
y=0;
if (windows->image.crop_geometry != (char *) NULL)
(void) XParseGeometry(windows->image.crop_geometry,&x,&y,
&width,&height);
scale_factor=(double) width/windows->image.ximage->width;
crop_info.x+=x;
crop_info.x=(int) (scale_factor*crop_info.x+0.5);
crop_info.width=(unsigned int) (scale_factor*crop_info.width+0.5);
scale_factor=(double) height/windows->image.ximage->height;
crop_info.y+=y;
crop_info.y=(int) (scale_factor*crop_info.y+0.5);
crop_info.height=(unsigned int)
(scale_factor*crop_info.height+0.5);
roi_image=CropImage(*image,&crop_info,&(*image)->exception);
(void) SetMonitorHandler(handler);
if (roi_image == (Image *) NULL)
continue;
/*
Apply image processing technique to the region of interest.
*/
windows->image.orphan=True;
(void) MagickXMagickCommand(display,resource_info,windows,command_type,
&roi_image);
handler=SetMonitorHandler((MonitorHandler) NULL);
(void) MagickXMagickCommand(display,resource_info,windows,
SaveToUndoBufferCommand,image);
windows->image.orphan=False;
(void) CompositeImage(*image,CopyCompositeOp,roi_image,
crop_info.x,crop_info.y);
DestroyImage(roi_image);
(void) SetMonitorHandler(handler);
break;
}
}
if (command_type != InfoCommand)
{
MagickXConfigureImageColormap(display,resource_info,windows,*image);
(void) MagickXConfigureImage(display,resource_info,windows,*image);
}
MagickXCheckRefreshWindows(display,windows);
MagickXInfoWidget(display,windows,text);
(void) XSetFunction(display,windows->image.highlight_context,
GXinvert);
state&=(~UpdateRegionState);
}
MagickXHighlightRectangle(display,windows->image.id,
windows->image.highlight_context,&highlight_info);
MagickXScreenEvent(display,windows,&event);
if (event.xany.window == windows->command.id)
{
/*
Select a command from the Command widget.
*/
(void) XSetFunction(display,windows->image.highlight_context,GXcopy);
command_type=NullCommand;
id=MagickXCommandWidget(display,windows,ApplyMenu,&event);
if (id >= 0)
{
(void) strlcpy(command,ApplyMenu[id],MaxTextExtent);
command_type=ApplyCommands[id];
if (id < ApplyMenus)
{
/*
Select a command from a pop-up menu.
*/
entry=MagickXMenuWidget(display,windows,ApplyMenu[id],
(const char **) Menus[id],command);
if (entry >= 0)
{
(void) strlcpy(command,Menus[id][entry],MaxTextExtent);
command_type=Commands[id][entry];
}
}
}
(void) XSetFunction(display,windows->image.highlight_context,
GXinvert);
MagickXHighlightRectangle(display,windows->image.id,
windows->image.highlight_context,&highlight_info);
if (command_type == HelpCommand)
{
(void) XSetFunction(display,windows->image.highlight_context,
GXcopy);
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Region of Interest",
ImageROIHelp,
sizeof(ImageROIHelp));
(void) XSetFunction(display,windows->image.highlight_context,
GXinvert);
continue;
}
if (command_type == QuitCommand)
{
/*
Exit.
*/
state|=EscapeState;
state|=ExitState;
continue;
}
if (command_type != NullCommand)
state|=UpdateRegionState;
continue;
}
MagickXHighlightRectangle(display,windows->image.id,
windows->image.highlight_context,&highlight_info);
switch (event.type)
{
case ButtonPress:
{
x=windows->image.x;
y=windows->image.y;
if (event.xbutton.button != Button1)
break;
if (event.xbutton.window != windows->image.id)
break;
x=windows->image.x+event.xbutton.x;
y=windows->image.y+event.xbutton.y;
if ((x < (int) (roi_info.x+RoiDelta)) &&
(x > (int) (roi_info.x-RoiDelta)) &&
(y < (int) (roi_info.y+RoiDelta)) &&
(y > (int) (roi_info.y-RoiDelta)))
{
roi_info.x=(long) (roi_info.x+roi_info.width);
roi_info.y=(long) (roi_info.y+roi_info.height);
state|=UpdateConfigurationState;
break;
}
if ((x < (int) (roi_info.x+RoiDelta)) &&
(x > (int) (roi_info.x-RoiDelta)) &&
(y < (int) (roi_info.y+roi_info.height+RoiDelta)) &&
(y > (int) (roi_info.y+roi_info.height-RoiDelta)))
{
roi_info.x=(long) (roi_info.x+roi_info.width);
state|=UpdateConfigurationState;
break;
}
if ((x < (int) (roi_info.x+roi_info.width+RoiDelta)) &&
(x > (int) (roi_info.x+roi_info.width-RoiDelta)) &&
(y < (int) (roi_info.y+RoiDelta)) &&
(y > (int) (roi_info.y-RoiDelta)))
{
roi_info.y=(long) (roi_info.y+roi_info.height);
state|=UpdateConfigurationState;
break;
}
if ((x < (int) (roi_info.x+roi_info.width+RoiDelta)) &&
(x > (int) (roi_info.x+roi_info.width-RoiDelta)) &&
(y < (int) (roi_info.y+roi_info.height+RoiDelta)) &&
(y > (int) (roi_info.y+roi_info.height-RoiDelta)))
{
state|=UpdateConfigurationState;
break;
}
break;
}
case ButtonRelease:
{
if (event.xbutton.window == windows->pan.id)
if ((highlight_info.x != crop_info.x-windows->image.x) ||
(highlight_info.y != crop_info.y-windows->image.y))
MagickXHighlightRectangle(display,windows->image.id,
windows->image.highlight_context,&highlight_info);
break;
}
case Expose:
{
if (event.xexpose.window == windows->image.id)
if (event.xexpose.count == 0)
{
event.xexpose.x=(int) highlight_info.x;
event.xexpose.y=(int) highlight_info.y;
event.xexpose.width=(unsigned int) highlight_info.width;
event.xexpose.height=(unsigned int) highlight_info.height;
MagickXRefreshWindow(display,&windows->image,&event);
}
if (event.xexpose.window == windows->info.id)
if (event.xexpose.count == 0)
MagickXInfoWidget(display,windows,text);
break;
}
case KeyPress:
{
KeySym
key_symbol;
if (event.xkey.window != windows->image.id)
break;
/*
Respond to a user key press.
*/
(void) XLookupString((XKeyEvent *) &event.xkey,command,
sizeof(command),&key_symbol,(XComposeStatus *) NULL);
switch ((int) key_symbol)
{
case XK_Shift_L:
case XK_Shift_R:
break;
case XK_Escape:
case XK_F20:
{
state|=EscapeState;
break;
}
case XK_Return:
{
state|=ExitState;
break;
}
case XK_F1:
case XK_Help:
{
(void) XSetFunction(display,windows->image.highlight_context,
GXcopy);
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Region of Interest",
ImageROIHelp,
sizeof(ImageROIHelp));
(void) XSetFunction(display,windows->image.highlight_context,
GXinvert);
break;
}
default:
{
command_type=MagickXImageWindowCommand(display,resource_info,windows,
event.xkey.state,key_symbol,image);
if (command_type != NullCommand)
state|=UpdateRegionState;
break;
}
}
break;
}
case KeyRelease:
break;
case MotionNotify:
{
if (event.xbutton.window != windows->image.id)
break;
/*
Map and unmap Info widget as text cursor crosses its boundaries.
*/
x=event.xmotion.x;
y=event.xmotion.y;
if (windows->info.mapped)
{
if ((x < (int) (windows->info.x+windows->info.width)) &&
(y < (int) (windows->info.y+windows->info.height)))
(void) XWithdrawWindow(display,windows->info.id,
windows->info.screen);
}
else
if ((x > (int) (windows->info.x+windows->info.width)) ||
(y > (int) (windows->info.y+windows->info.height)))
(void) XMapWindow(display,windows->info.id);
break;
}
default:
break;
}
if (state & UpdateConfigurationState)
{
(void) XPutBackEvent(display,&event);
(void) XDefineCursor(display,windows->image.id,cursor);
break;
}
} while (!(state & ExitState));
} while (!(state & ExitState));
(void) XSetFunction(display,windows->image.highlight_context,GXcopy);
MagickXSetCursorState(display,windows,False);
if (state & EscapeState)
return(True);
return(True);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X R o t a t e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXRotateImage rotates the X image. If the degrees parameter
% if zero, the rotation angle is computed from the slope of a line drawn by
% the user.
%
% The format of the MagickXRotateImage method is:
%
% unsigned int MagickXRotateImage(Display *display,MagickXResourceInfo *resource_info,
% MagickXWindows *windows,double degrees,Image **image)
%
% A description of each parameter follows:
%
% o status: Method MagickXRotateImage return True if the image is
% rotate. False is returned is there is a memory shortage or if the
% image fails to rotate.
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o resource_info: Specifies a pointer to a X11 MagickXResourceInfo structure.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
% o degrees: Specifies the number of degrees to rotate the image.
%
% o image: Specifies a pointer to an Image structure; returned from
% ReadImage.
%
%
*/
static unsigned int MagickXRotateImage(Display *display,MagickXResourceInfo *resource_info,
MagickXWindows *windows,double degrees,Image **image)
{
const char
* const RotateMenu[]=
{
"Pixel Color",
"Direction",
"Help",
"Dismiss",
(char *) NULL
};
static ModeType
direction = HorizontalRotateCommand;
static const ModeType
DirectionCommands[]=
{
HorizontalRotateCommand,
VerticalRotateCommand
},
RotateCommands[]=
{
RotateColorCommand,
RotateDirectionCommand,
RotateHelpCommand,
RotateDismissCommand
};
static unsigned int
pen_id = 0;
char
command[MaxTextExtent],
text[MaxTextExtent];
double
normalized_degrees;
Image
*rotate_image;
int
id,
x,
y;
register int
i;
unsigned int
height,
rotations,
width;
if (degrees == 0.0)
{
unsigned int
distance;
unsigned long
state;
XEvent
event;
XSegment
rotate_info;
/*
Map Command widget.
*/
(void) CloneString(&windows->command.name,"Rotate");
windows->command.data=2;
(void) MagickXCommandWidget(display,windows,RotateMenu,(XEvent *) NULL);
(void) XMapRaised(display,windows->command.id);
MagickXClientMessage(display,windows->image.id,windows->im_protocols,
windows->im_update_widget,CurrentTime);
/*
Wait for first button press.
*/
(void) XSetFunction(display,windows->image.highlight_context,GXinvert);
MagickXQueryPosition(display,windows->image.id,&x,&y);
rotate_info.x1=x;
rotate_info.y1=y;
rotate_info.x2=x;
rotate_info.y2=y;
state=DefaultState;
do
{
MagickXHighlightLine(display,windows->image.id,
windows->image.highlight_context,&rotate_info);
/*
Wait for next event.
*/
MagickXScreenEvent(display,windows,&event);
MagickXHighlightLine(display,windows->image.id,
windows->image.highlight_context,&rotate_info);
if (event.xany.window == windows->command.id)
{
/*
Select a command from the Command widget.
*/
id=MagickXCommandWidget(display,windows,RotateMenu,&event);
if (id < 0)
continue;
(void) XSetFunction(display,windows->image.highlight_context,
GXcopy);
switch (RotateCommands[id])
{
case RotateColorCommand:
{
char
*ColorMenu[MaxNumberPens];
int
pen_number;
XColor
color;
/*
Initialize menu selections.
*/
for (i=0; i < (int) (MaxNumberPens-2); i++)
ColorMenu[i]=resource_info->pen_colors[i];
ColorMenu[MaxNumberPens-2]=(char *) "Browser...";
ColorMenu[MaxNumberPens-1]=(char *) NULL;
/*
Select a pen color from the pop-up menu.
*/
pen_number=MagickXMenuWidget(display,windows,RotateMenu[id],
(const char **) ColorMenu,command);
if (pen_number < 0)
break;
if (pen_number == (MaxNumberPens-2))
{
static char
color_name[MaxTextExtent] = "gray";
/*
Select a pen color from a dialog.
*/
resource_info->pen_colors[pen_number]=color_name;
MagickXColorBrowserWidget(display,windows,"Select",color_name);
if (*color_name == '\0')
break;
}
/*
Set pen color.
*/
(void) XParseColor(display,windows->map_info->colormap,
resource_info->pen_colors[pen_number],&color);
MagickXBestPixel(display,windows->map_info->colormap,(XColor *) NULL,
(unsigned int) MaxColors,&color);
windows->pixel_info->pen_colors[pen_number]=color;
pen_id=pen_number;
break;
}
case RotateDirectionCommand:
{
const char
* const Directions[]=
{
"horizontal",
"vertical",
(char *) NULL,
};
/*
Select a command from the pop-up menu.
*/
id=MagickXMenuWidget(display,windows,RotateMenu[id],
Directions,command);
if (id >= 0)
direction=DirectionCommands[id];
break;
}
case RotateHelpCommand:
{
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Image Rotation",
ImageRotateHelp,
sizeof(ImageRotateHelp));
break;
}
case RotateDismissCommand:
{
/*
Prematurely exit.
*/
state|=EscapeState;
state|=ExitState;
break;
}
default:
break;
}
(void) XSetFunction(display,windows->image.highlight_context,
GXinvert);
continue;
}
switch (event.type)
{
case ButtonPress:
{
if (event.xbutton.button != Button1)
break;
if (event.xbutton.window != windows->image.id)
break;
/*
Exit loop.
*/
(void) XSetFunction(display,windows->image.highlight_context,
GXcopy);
rotate_info.x1=event.xbutton.x;
rotate_info.y1=event.xbutton.y;
state|=ExitState;
break;
}
case ButtonRelease:
break;
case Expose:
break;
case KeyPress:
{
char
command[MaxTextExtent];
KeySym
key_symbol;
if (event.xkey.window != windows->image.id)
break;
/*
Respond to a user key press.
*/
(void) XLookupString((XKeyEvent *) &event.xkey,command,
sizeof(command),&key_symbol,(XComposeStatus *) NULL);
switch ((int) key_symbol)
{
case XK_Escape:
case XK_F20:
{
/*
Prematurely exit.
*/
state|=EscapeState;
state|=ExitState;
break;
}
case XK_F1:
case XK_Help:
{
(void) XSetFunction(display,windows->image.highlight_context,
GXcopy);
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Image Rotation",
ImageRotateHelp,
sizeof(ImageRotateHelp));
(void) XSetFunction(display,windows->image.highlight_context,
GXinvert);
break;
}
default:
{
(void) XBell(display,0);
break;
}
}
break;
}
case MotionNotify:
{
rotate_info.x1=event.xmotion.x;
rotate_info.y1=event.xmotion.y;
}
}
rotate_info.x2=rotate_info.x1;
rotate_info.y2=rotate_info.y1;
if (direction == HorizontalRotateCommand)
rotate_info.x2+=32;
else
rotate_info.y2-=32;
} while (!(state & ExitState));
(void) XSetFunction(display,windows->image.highlight_context,GXcopy);
(void) XWithdrawWindow(display,windows->info.id,windows->info.screen);
if (state & EscapeState)
return(True);
/*
Draw line as pointer moves until the mouse button is released.
*/
distance=0;
(void) XSetFunction(display,windows->image.highlight_context,GXinvert);
state=DefaultState;
do
{
if (distance > 9)
{
/*
Display info and draw rotation line.
*/
if (!windows->info.mapped)
(void) XMapWindow(display,windows->info.id);
FormatString(text," %.2f",
direction == VerticalRotateCommand ? degrees-90.0 : degrees);
MagickXInfoWidget(display,windows,text);
MagickXHighlightLine(display,windows->image.id,
windows->image.highlight_context,&rotate_info);
}
else
if (windows->info.mapped)
(void) XWithdrawWindow(display,windows->info.id,
windows->info.screen);
/*
Wait for next event.
*/
MagickXScreenEvent(display,windows,&event);
if (distance > 9)
MagickXHighlightLine(display,windows->image.id,
windows->image.highlight_context,&rotate_info);
switch (event.type)
{
case ButtonPress:
break;
case ButtonRelease:
{
/*
User has committed to rotation line.
*/
rotate_info.x2=event.xbutton.x;
rotate_info.y2=event.xbutton.y;
state|=ExitState;
break;
}
case Expose:
break;
case MotionNotify:
{
rotate_info.x2=event.xmotion.x;
rotate_info.y2=event.xmotion.y;
}
default:
break;
}
/*
Check boundary conditions.
*/
if (rotate_info.x2 < 0)
rotate_info.x2=0;
else
if (rotate_info.x2 > (int) windows->image.width)
rotate_info.x2=windows->image.width;
if (rotate_info.y2 < 0)
rotate_info.y2=0;
else
if (rotate_info.y2 > (int) windows->image.height)
rotate_info.y2=windows->image.height;
/*
Compute rotation angle from the slope of the line.
*/
degrees=0.0;
distance=
((rotate_info.x2-rotate_info.x1+1)*(rotate_info.x2-rotate_info.x1+1))+
((rotate_info.y2-rotate_info.y1+1)*(rotate_info.y2-rotate_info.y1+1));
if (distance > 9)
degrees=RadiansToDegrees(-atan2((double) (rotate_info.y2-
rotate_info.y1),(double) (rotate_info.x2-rotate_info.x1)));
} while (!(state & ExitState));
(void) XSetFunction(display,windows->image.highlight_context,GXcopy);
(void) XWithdrawWindow(display,windows->info.id,windows->info.screen);
if (distance <= 9)
return(True);
}
if (direction == VerticalRotateCommand)
degrees-=90.0;
if (degrees == 0.0)
return(True);
/*
Rotate image.
*/
normalized_degrees=degrees;
while (normalized_degrees < -45.0)
normalized_degrees+=360.0;
for (rotations=0; normalized_degrees > 45.0; rotations++)
normalized_degrees-=90.0;
if (normalized_degrees != 0.0)
(void) MagickXMagickCommand(display,resource_info,windows,ApplyCommand,image);
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
(*image)->background_color.red=
ScaleShortToQuantum(windows->pixel_info->pen_colors[pen_id].red);
(*image)->background_color.green=
ScaleShortToQuantum(windows->pixel_info->pen_colors[pen_id].green);
(*image)->background_color.blue=
ScaleShortToQuantum(windows->pixel_info->pen_colors[pen_id].blue);
rotate_image=RotateImage(*image,degrees,&(*image)->exception);
MagickXSetCursorState(display,windows,False);
if (rotate_image == (Image *) NULL)
return(False);
DestroyImage(*image);
*image=rotate_image;
if (windows->image.crop_geometry != (char *) NULL)
{
/*
Rotate crop geometry.
*/
width=(unsigned int) (*image)->columns;
height=(unsigned int) (*image)->rows;
(void) XParseGeometry(windows->image.crop_geometry,&x,&y,&width,&height);
switch (rotations % 4)
{
default:
case 0:
break;
case 1:
{
/*
Rotate 90 degrees.
*/
FormatString(windows->image.crop_geometry,"%ux%u%+d%+d",
height,width,(int) (*image)->columns-(int) height-y,x);
break;
}
case 2:
{
/*
Rotate 180 degrees.
*/
FormatString(windows->image.crop_geometry,"%ux%u%+d%+d",
width,height,(int) width-x,(int) height-y);
break;
}
case 3:
{
/*
Rotate 270 degrees.
*/
FormatString(windows->image.crop_geometry,"%ux%u%+d%+d",
height,width,y,(int) (*image)->rows-(int) width-x);
break;
}
}
}
if (windows->image.orphan)
return(True);
if (normalized_degrees != 0.0)
{
/*
Update image colormap.
*/
windows->image.window_changes.width=(unsigned int) (*image)->columns;
windows->image.window_changes.height=(unsigned int) (*image)->rows;
if (windows->image.crop_geometry != (char *) NULL)
{
/*
Obtain dimensions of image from crop geometry.
*/
(void) XParseGeometry(windows->image.crop_geometry,&x,&y,
&width,&height);
windows->image.window_changes.width=width;
windows->image.window_changes.height=height;
}
MagickXConfigureImageColormap(display,resource_info,windows,*image);
}
else
if (((rotations % 4) == 1) || ((rotations % 4) == 3))
{
windows->image.window_changes.width=windows->image.ximage->height;
windows->image.window_changes.height=windows->image.ximage->width;
}
/*
Update image configuration.
*/
(void) MagickXConfigureImage(display,resource_info,windows,*image);
return(True);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X S a v e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXSaveImage saves an image to a file.
%
% The format of the MagickXSaveImage method is:
%
% unsigned int MagickXSaveImage(Display *display,MagickXResourceInfo *resource_info,
% MagickXWindows *windows,Image *image)
%
% A description of each parameter follows:
%
% o status: Method MagickXSaveImage return True if the image is
% written. False is returned is there is a memory shortage or if the
% image fails to write.
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o resource_info: Specifies a pointer to a X11 MagickXResourceInfo structure.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
% o image: Specifies a pointer to an Image structure; returned from
% ReadImage.
%
%
*/
static unsigned int MagickXSaveImage(Display *display,MagickXResourceInfo *resource_info,
MagickXWindows *windows,Image *image)
{
char
filename[MaxTextExtent],
geometry[MaxTextExtent];
Image
*save_image;
ImageInfo
*image_info;
int
status;
/*
Request file name from user.
*/
if (resource_info->write_filename != (char *) NULL)
(void) strlcpy(filename,resource_info->write_filename,MaxTextExtent);
else
{
char
path[MaxTextExtent];
GetPathComponent(image->filename,HeadPath,path);
GetPathComponent(image->filename,TailPath,filename);
if ((strlen(path) > 0) && (chdir(path) != 0))
MagickXNoticeWidget(display,windows,"Unable to change to directory:",
path);
}
MagickXFileBrowserWidget(display,windows,"Save",filename);
if (*filename == '\0')
return(True);
if (IsAccessible(filename))
{
/*
File exists-- seek user's permission before overwriting.
*/
status=MagickXConfirmWidget(display,windows,"Overwrite",filename);
if (status <= 0)
return(True);
}
image_info=CloneImageInfo(resource_info->image_info);
(void) strlcpy(image_info->filename,filename,MaxTextExtent);
(void) SetImageInfo(image_info,SETMAGICK_WRITE,&image->exception);
if ((LocaleCompare(image_info->magick,"JPEG") == 0) ||
(LocaleCompare(image_info->magick,"JPG") == 0))
{
char
quality[MaxTextExtent];
/*
Request JPEG quality from user.
*/
FormatString(quality,"%lu",image_info->quality);
status=MagickXDialogWidget(display,windows,"Save","Enter JPEG quality:",
quality);
if (*quality == '\0')
return(True);
image_info->quality=MagickAtoL(quality);
image_info->interlace=status ? NoInterlace : PlaneInterlace;
}
if ((LocaleCompare(image_info->magick,"EPS") == 0) ||
(LocaleCompare(image_info->magick,"PDF") == 0) ||
(LocaleCompare(image_info->magick,"PS") == 0) ||
(LocaleCompare(image_info->magick,"PS2") == 0))
{
const char
* const PageSizes[]=
{
PAGE_SIZES
};
char
geometry[MaxTextExtent];
/*
Request page geometry from user.
*/
FormatString(geometry,"%.1024s",PSPageGeometry);
if (LocaleCompare(image_info->magick,"PDF") == 0)
FormatString(geometry,"%.1024s",PSPageGeometry);
if (image_info->page != (char *) NULL)
(void) strlcpy(geometry,image_info->page,MaxTextExtent);
MagickXListBrowserWidget(display,windows,&windows->widget,PageSizes,"Select",
"Select page geometry:",geometry);
if (*geometry != '\0')
image_info->page=GetPageGeometry(geometry);
}
/*
Apply image transforms.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
save_image=CloneImage(image,0,0,True,&image->exception);
if (save_image == (Image *) NULL)
return(False);
FormatString(geometry,"%dx%d!",windows->image.ximage->width,
windows->image.ximage->height);
TransformImage(&save_image,windows->image.crop_geometry,geometry);
/*
Write image.
*/
(void) strlcpy(save_image->filename,filename,MaxTextExtent);
status=WriteImage(image_info,save_image);
if (status != MagickFail)
image->taint=False;
else
CopyException(&image->exception,&save_image->exception);
DestroyImage(save_image);
DestroyImageInfo(image_info);
MagickXSetCursorState(display,windows,False);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X S c r e e n E v e n t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXScreenEvent handles global events associated with the Pan and
% Magnify windows.
%
% The format of the MagickXScreenEvent function is:
%
% void MagickXScreenEvent(Display *display,MagickXWindows *windows,XEvent *event)
%
% A description of each parameter follows:
%
% o display: Specifies a pointer to the Display structure; returned from
% XOpenDisplay.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
% o event: Specifies a pointer to a X11 XEvent structure.
%
%
*/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static int MagickXPredicate(Display *display,XEvent *event,char *data)
{
register MagickXWindows
*windows;
ARG_NOT_USED(display);
windows=(MagickXWindows *) data;
if ((event->type == ClientMessage) &&
(event->xclient.window == windows->image.id))
return(False);
return(True);
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
static void MagickXScreenEvent(Display *display,MagickXWindows *windows,XEvent *event)
{
MonitorHandler
handler;
register int
x,
y;
(void) XIfEvent(display,event,MagickXPredicate,(char *) windows);
if (event->xany.window == windows->command.id)
return;
switch (event->type)
{
case ButtonPress:
case ButtonRelease:
{
if ((event->xbutton.button == Button3) &&
(event->xbutton.state & Mod1Mask))
{
/*
Convert Alt-Button3 to Button2.
*/
event->xbutton.button=Button2;
event->xbutton.state&=(~Mod1Mask);
}
if (event->xbutton.window == windows->backdrop.id)
{
(void) XSetInputFocus(display,event->xbutton.window,RevertToParent,
event->xbutton.time);
break;
}
if (event->xbutton.window == windows->pan.id)
{
MagickXPanImage(display,windows,event);
break;
}
if (event->xbutton.window == windows->image.id)
if (event->xbutton.button == Button2)
{
/*
Update magnified image.
*/
x=event->xbutton.x;
y=event->xbutton.y;
if (x < 0)
x=0;
else
if (x >= (int) windows->image.width)
x=windows->image.width-1;
windows->magnify.x=windows->image.x+x;
if (y < 0)
y=0;
else
if (y >= (int) windows->image.height)
y=windows->image.height-1;
windows->magnify.y=windows->image.y+y;
if (!windows->magnify.mapped)
(void) XMapRaised(display,windows->magnify.id);
handler=SetMonitorHandler((MonitorHandler) NULL);
MagickXMakeMagnifyImage(display,windows);
(void) SetMonitorHandler(handler);
if (event->type == ButtonRelease)
(void) XWithdrawWindow(display,windows->info.id,
windows->info.screen);
break;
}
break;
}
case ClientMessage:
{
/*
If client window delete message, exit.
*/
if (event->xclient.message_type != windows->wm_protocols)
break;
if (*event->xclient.data.l != (long) windows->wm_delete_window)
break;
if (event->xclient.window == windows->magnify.id)
{
(void) XWithdrawWindow(display,windows->magnify.id,
windows->magnify.screen);
break;
}
break;
}
case ConfigureNotify:
{
if (event->xconfigure.window == windows->magnify.id)
{
unsigned int
magnify;
/*
Magnify window has a new configuration.
*/
windows->magnify.width=event->xconfigure.width;
windows->magnify.height=event->xconfigure.height;
if (!windows->magnify.mapped)
break;
magnify=1;
while ((int) magnify <= event->xconfigure.width)
magnify<<=1;
while ((int) magnify <= event->xconfigure.height)
magnify<<=1;
magnify>>=1;
if (((int) magnify != event->xconfigure.width) ||
((int) magnify != event->xconfigure.height))
{
XWindowChanges
window_changes;
window_changes.width=magnify;
window_changes.height=magnify;
(void) XReconfigureWMWindow(display,windows->magnify.id,
windows->magnify.screen,CWWidth | CWHeight,&window_changes);
break;
}
MagickXMakeMagnifyImage(display,windows);
break;
}
break;
}
case Expose:
{
if (event->xexpose.window == windows->image.id)
{
MagickXRefreshWindow(display,&windows->image,event);
break;
}
if (event->xexpose.window == windows->pan.id)
if (event->xexpose.count == 0)
{
MagickXDrawPanRectangle(display,windows);
break;
}
if (event->xexpose.window == windows->magnify.id)
if (event->xexpose.count == 0)
{
MagickXMakeMagnifyImage(display,windows);
break;
}
break;
}
case KeyPress:
{
char
command[MaxTextExtent];
KeySym
key_symbol;
if (event->xkey.window != windows->magnify.id)
break;
/*
Respond to a user key press.
*/
(void) XLookupString((XKeyEvent *) &event->xkey,command,sizeof(command),
&key_symbol,(XComposeStatus *) NULL);
MagickXMagnifyWindowCommand(display,windows,event->xkey.state,key_symbol);
break;
}
case MapNotify:
{
if (event->xmap.window == windows->magnify.id)
{
windows->magnify.mapped=True;
(void) XWithdrawWindow(display,windows->info.id,windows->info.screen);
break;
}
if (event->xmap.window == windows->info.id)
{
windows->info.mapped=True;
break;
}
break;
}
case MotionNotify:
{
while (XCheckMaskEvent(display,ButtonMotionMask,event));
if (event->xmotion.window == windows->image.id)
if (windows->magnify.mapped)
{
/*
Update magnified image.
*/
x=event->xmotion.x;
y=event->xmotion.y;
if (x < 0)
x=0;
else
if (x >= (int) windows->image.width)
x=windows->image.width-1;
windows->magnify.x=windows->image.x+x;
if (y < 0)
y=0;
else
if (y >= (int) windows->image.height)
y=windows->image.height-1;
windows->magnify.y=windows->image.y+y;
MagickXMakeMagnifyImage(display,windows);
}
break;
}
case UnmapNotify:
{
if (event->xunmap.window == windows->magnify.id)
{
windows->magnify.mapped=False;
break;
}
if (event->xunmap.window == windows->info.id)
{
windows->info.mapped=False;
break;
}
break;
}
default:
break;
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X S e t C r o p G e o m e t r y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXSetCropGeometry accepts a cropping geometry relative to the
% Image window and translates it to a cropping geometry relative to the
% image.
%
% The format of the MagickXSetCropGeometry method is:
%
% void MagickXSetCropGeometry(Display *display,MagickXWindows *windows,
% RectangleInfo *crop_info,Image *image)
%
% A description of each parameter follows:
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
% o crop_info: A pointer to a RectangleInfo that defines a region of the
% Image window to crop.
%
% o image: Specifies a pointer to an Image structure.
%
%
*/
static void MagickXSetCropGeometry(Display *display,MagickXWindows *windows,
RectangleInfo *crop_info,Image *image)
{
char
text[MaxTextExtent];
double
scale_factor;
int
x,
y;
unsigned int
height,
width;
if (windows->info.mapped)
{
/*
Display info on cropping rectangle.
*/
FormatString(text," %lux%lu%+ld%+ld",crop_info->width,crop_info->height,
crop_info->x,crop_info->y);
MagickXInfoWidget(display,windows,text);
}
/*
Cropping geometry is relative to any previous crop geometry.
*/
x=0;
y=0;
width=(unsigned int) image->columns;
height=(unsigned int) image->rows;
if (windows->image.crop_geometry != (char *) NULL)
(void) XParseGeometry(windows->image.crop_geometry,&x,&y,&width,&height);
else
windows->image.crop_geometry=AllocateString((char *) NULL);
/*
Define the crop geometry string from the cropping rectangle.
*/
scale_factor=(double) width/windows->image.ximage->width;
if (crop_info->x > 0)
x+=(int) (scale_factor*crop_info->x+0.5);
width=(unsigned int) (scale_factor*crop_info->width+0.5);
if (width == 0)
width=1;
scale_factor=(double) height/windows->image.ximage->height;
if (crop_info->y > 0)
y+=(int) (scale_factor*crop_info->y+0.5);
height=(unsigned int) (scale_factor*crop_info->height+0.5);
if (height == 0)
height=1;
FormatString(windows->image.crop_geometry,"%ux%u%+d%+d",width,height,x,y);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X T i l e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXTileImage loads or deletes a selected tile from a visual
% image directory. The load or delete command is chosen from a menu.
%
% The format of the MagickXTileImage method is:
%
% Image *MagickXTileImage(Display *display,MagickXResourceInfo *resource_info,
% MagickXWindows *windows,Image *image,XEvent *event)
%
% A description of each parameter follows:
%
% o tile_image: MagickXTileImage reads or deletes the tile image
% and returns it. A null image is returned if an error occurs.
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o resource_info: Specifies a pointer to a X11 MagickXResourceInfo structure.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
% o image: Specifies a pointer to an Image structure; returned from
% ReadImage.
%
% o event: Specifies a pointer to a XEvent structure. If it is NULL,
% the entire image is refreshed.
%
%
*/
static Image *MagickXTileImage(Display *display,MagickXResourceInfo *resource_info,
MagickXWindows *windows,Image *image,XEvent *event)
{
const char
* const VerbMenu[]=
{
"Load",
"Next",
"Former",
"Delete",
"Update",
(char *) NULL,
};
static const ModeType
TileCommands[]=
{
TileLoadCommand,
TileNextCommand,
TileFormerCommand,
TileDeleteCommand,
TileUpdateCommand
};
char
command[MaxTextExtent],
filename[MaxTextExtent];
double
scale_factor;
Image
*tile_image;
int
id,
status,
tile,
x,
y;
register char
*p,
*q;
register int
i;
unsigned int
height,
width;
/*
Tile image is relative to montage image configuration.
*/
x=0;
y=0;
width=(unsigned int) image->columns;
height=(unsigned int) image->rows;
if (windows->image.crop_geometry != (char *) NULL)
(void) XParseGeometry(windows->image.crop_geometry,&x,&y,&width,&height);
scale_factor=(double) width/windows->image.ximage->width;
event->xbutton.x+=windows->image.x;
event->xbutton.x=(int) (scale_factor*event->xbutton.x+x+0.5);
scale_factor=(double) height/windows->image.ximage->height;
event->xbutton.y+=windows->image.y;
event->xbutton.y=(int) (scale_factor*event->xbutton.y+y+0.5);
/*
Determine size and location of each tile in the visual image directory.
*/
width=(unsigned int) image->columns;
height=(unsigned int) image->rows;
x=0;
y=0;
(void) XParseGeometry(image->montage,&x,&y,&width,&height);
tile=((event->xbutton.y-y)/height)*(((int) image->columns-x)/width)+
(event->xbutton.x-x)/width;
if (tile < 0)
{
/*
Button press is outside any tile.
*/
(void) XBell(display,0);
return((Image *) NULL);
}
/*
Determine file name from the tile directory.
*/
p=image->directory;
for (i=tile; (i != 0) && (*p != '\0'); )
{
if (*p == '\n')
i--;
p++;
}
if (*p == '\0')
{
/*
Button press is outside any tile.
*/
(void) XBell(display,0);
return((Image *) NULL);
}
/*
Select a command from the pop-up menu.
*/
id=MagickXMenuWidget(display,windows,"Tile Verb",VerbMenu,command);
if (id < 0)
return((Image *) NULL);
q=p;
while ((*q != '\n') && (*q != '\0'))
q++;
(void) strncpy(filename,p,q-p);
filename[q-p]='\0';
/*
Perform command for the selected tile.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
tile_image=(Image *) NULL;
switch (TileCommands[id])
{
case TileLoadCommand:
{
/*
Load tile image.
*/
MagickXCheckRefreshWindows(display,windows);
(void) strcpy(resource_info->image_info->magick,"MIFF");
(void) strlcpy(resource_info->image_info->filename,filename,
MaxTextExtent);
tile_image=ReadImage(resource_info->image_info,&image->exception);
if (image->exception.severity != UndefinedException)
MagickError2(image->exception.severity,image->exception.reason,
image->exception.description);
(void) XWithdrawWindow(display,windows->info.id,windows->info.screen);
break;
}
case TileNextCommand:
{
/*
Display next image.
*/
MagickXClientMessage(display,windows->image.id,windows->im_protocols,
windows->im_next_image,CurrentTime);
break;
}
case TileFormerCommand:
{
/*
Display former image.
*/
MagickXClientMessage(display,windows->image.id,windows->im_protocols,
windows->im_former_image,CurrentTime);
break;
}
case TileDeleteCommand:
{
/*
Delete tile image.
*/
if (!IsAccessible(filename))
{
MagickXNoticeWidget(display,windows,"Image file does not exist:",filename);
break;
}
status=MagickXConfirmWidget(display,windows,"Really delete tile",filename);
if (status <= 0)
break;
status=remove(filename);
if (status != False)
{
MagickXNoticeWidget(display,windows,"Unable to delete image file:",
filename);
}
break;
}
case TileUpdateCommand:
{
int
x_offset,
y_offset;
PixelPacket
pixel;
register int
j;
register PixelPacket
*s;
/*
Ensure all the images exist.
*/
tile=0;
for (p=image->directory; *p != '\0'; p++)
{
q=p;
while ((*q != '\n') && (*q != '\0'))
q++;
(void) strncpy(filename,p,q-p);
filename[q-p]='\0';
p=q;
if (IsAccessible(filename))
{
tile++;
continue;
}
/*
Overwrite tile with background color.
*/
x_offset=width*(tile % (((int) image->columns-x)/width))+x;
y_offset=height*(tile/(((int) image->columns-x)/width))+y;
(void) AcquireOnePixelByReference(image,&pixel,0,0,&image->exception);
for (i=0; i < (int) height; i++)
{
s=GetImagePixels(image,x_offset,y_offset+i,width,1);
if (s == (PixelPacket *) NULL)
break;
for (j=0; j < (int) width; j++)
*s++=pixel;
if (!SyncImagePixels(image))
break;
}
tile++;
}
windows->image.window_changes.width=(unsigned int) image->columns;
windows->image.window_changes.height=(unsigned int) image->rows;
MagickXConfigureImageColormap(display,resource_info,windows,image);
(void) MagickXConfigureImage(display,resource_info,windows,image);
break;
}
default:
break;
}
MagickXSetCursorState(display,windows,False);
return(tile_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X T r a n s l a t e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXTranslateImage translates the image within an Image window
% by one pixel as specified by the key symbol. If the image has a `montage'
% string the translation is respect to the width and height contained within
% the string.
%
% The format of the MagickXTranslateImage method is:
%
% void MagickXTranslateImage(Display *display,MagickXWindows *windows,
% Image *image,const KeySym key_symbol)
%
% A description of each parameter follows:
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
% o image: Specifies a pointer to an Image structure; returned from
% ReadImage.
%
% o key_symbol: Specifies a KeySym which indicates which side of the image
% to trim.
%
%
*/
static void MagickXTranslateImage(Display *display,MagickXWindows *windows,
Image *image,const KeySym key_symbol)
{
char
text[MaxTextExtent];
int
x,
y;
unsigned int
x_offset,
y_offset;
/*
User specified a pan position offset.
*/
x_offset=windows->image.width;
y_offset=windows->image.height;
if (image->montage != (char *) NULL)
(void) XParseGeometry(image->montage,&x,&y,&x_offset,&y_offset);
switch ((int) key_symbol)
{
case XK_Home:
case XK_KP_Home:
{
windows->image.x=windows->image.width/2;
windows->image.y=windows->image.height/2;
break;
}
case XK_Left:
case XK_KP_Left:
{
windows->image.x-=x_offset;
break;
}
case XK_Next:
case XK_Up:
case XK_KP_Up:
{
windows->image.y-=y_offset;
break;
}
case XK_Right:
case XK_KP_Right:
{
windows->image.x+=x_offset;
break;
}
case XK_Prior:
case XK_Down:
case XK_KP_Down:
{
windows->image.y+=y_offset;
break;
}
default:
return;
}
/*
Check boundary conditions.
*/
if (windows->image.x < 0)
windows->image.x=0;
else
if ((int) (windows->image.x+windows->image.width) >
windows->image.ximage->width)
windows->image.x=windows->image.ximage->width-windows->image.width;
if (windows->image.y < 0)
windows->image.y=0;
else
if ((int) (windows->image.y+windows->image.height) >
windows->image.ximage->height)
windows->image.y=windows->image.ximage->height-windows->image.height;
/*
Refresh Image window.
*/
FormatString(text," %ux%u%+d%+d ",windows->image.width,
windows->image.height,windows->image.x,windows->image.y);
MagickXInfoWidget(display,windows,text);
MagickXCheckRefreshWindows(display,windows);
MagickXDrawPanRectangle(display,windows);
MagickXRefreshWindow(display,&windows->image,(XEvent *) NULL);
(void) XWithdrawWindow(display,windows->info.id,windows->info.screen);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X T r i m I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXTrimImage trims the edges from the Image window.
%
% The format of the MagickXTrimImage method is:
%
% unsigned int MagickXTrimImage(Display *display,MagickXResourceInfo *resource_info,
% MagickXWindows *windows,Image *image)
%
% A description of each parameter follows:
%
% o status: Method MagickXTrimImage returns True if the image is
% cropped. False is returned is there is a memory shortage or if the
% image fails to be cropped.
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o resource_info: Specifies a pointer to a X11 MagickXResourceInfo structure.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
% o image: Specifies a pointer to an Image structure.
%
%
*/
static unsigned int MagickXTrimImage(Display *display,MagickXResourceInfo *resource_info,
MagickXWindows *windows,Image *image)
{
RectangleInfo
trim_info;
register int
x,
y;
unsigned long
background,
pixel;
/*
Trim edges from image.
*/
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
/*
Crop the left edge.
*/
background=XGetPixel(windows->image.ximage,0,0);
trim_info.width=windows->image.ximage->width;
for (x=0; x < windows->image.ximage->width; x++)
{
for (y=0; y < windows->image.ximage->height; y++)
{
pixel=XGetPixel(windows->image.ximage,x,y);
if (pixel != background)
break;
}
if (y < windows->image.ximage->height)
break;
}
trim_info.x=x;
if (trim_info.x == (int) windows->image.ximage->width)
{
MagickXSetCursorState(display,windows,False);
return(False);
}
/*
Crop the right edge.
*/
background=XGetPixel(windows->image.ximage,windows->image.ximage->width-1,0);
for (x=windows->image.ximage->width-1; x > 0; x--)
{
for (y=0; y < windows->image.ximage->height; y++)
{
pixel=XGetPixel(windows->image.ximage,x,y);
if (pixel != background)
break;
}
if (y < windows->image.ximage->height)
break;
}
trim_info.width=x-trim_info.x+1;
/*
Crop the top edge.
*/
background=XGetPixel(windows->image.ximage,0,0);
trim_info.height=windows->image.ximage->height;
for (y=0; y < windows->image.ximage->height; y++)
{
for (x=0; x < windows->image.ximage->width; x++)
{
pixel=XGetPixel(windows->image.ximage,x,y);
if (pixel != background)
break;
}
if (x < windows->image.ximage->width)
break;
}
trim_info.y=y;
/*
Crop the bottom edge.
*/
background=XGetPixel(windows->image.ximage,0,windows->image.ximage->height-1);
for (y=windows->image.ximage->height-1; y > 0; y--)
{
for (x=0; x < windows->image.ximage->width; x++)
{
pixel=XGetPixel(windows->image.ximage,x,y);
if (pixel != background)
break;
}
if (x < windows->image.ximage->width)
break;
}
trim_info.height=y-trim_info.y+1;
if (((unsigned int) trim_info.width != windows->image.width) ||
((unsigned int) trim_info.height != windows->image.height))
{
/*
Reconfigure Image window as defined by the trimming rectangle.
*/
MagickXSetCropGeometry(display,windows,&trim_info,image);
windows->image.window_changes.width=(unsigned int) trim_info.width;
windows->image.window_changes.height=(unsigned int) trim_info.height;
(void) MagickXConfigureImage(display,resource_info,windows,image);
}
MagickXSetCursorState(display,windows,False);
return(True);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k X V i s u a l D i r e c t o r y I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method MagickXVisualDirectoryImage creates a Visual Image Directory.
%
% The format of the MagickXVisualDirectoryImage method is:
%
% Image *MagickXVisualDirectoryImage(Display *display,
% MagickXResourceInfo *resource_info,MagickXWindows *windows)
%
% A description of each parameter follows:
%
% o nexus: Method MagickXVisualDirectoryImage returns a visual image
% directory if it can be created successfully. Otherwise a null image
% is returned.
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o resource_info: Specifies a pointer to a X11 MagickXResourceInfo structure.
%
% o windows: Specifies a pointer to a MagickXWindows structure.
%
%
*/
static Image *MagickXVisualDirectoryImage(Display *display,
MagickXResourceInfo *resource_info,MagickXWindows *windows)
{
#define TileImageText " Scale image tiles... "
#define XClientName "montage"
char
**filelist,
window_id[MaxTextExtent];
ExceptionInfo
exception;
Image
*image,
*montage_image,
*next_image,
*thumbnail_image;
ImageInfo
*clone_info;
int
number_files;
MonitorHandler
handler;
MontageInfo
*montage_info;
RectangleInfo
geometry;
register int
i;
static char
filename[MaxTextExtent] = "\0",
filenames[MaxTextExtent] = "*";
unsigned int
backdrop,
status;
MagickXResourceInfo
background_resources;
/*
Request file name from user.
*/
MagickXFileBrowserWidget(display,windows,"Directory",filenames);
if (*filenames == '\0')
return((Image *) NULL);
/*
Expand the filenames.
*/
filelist=MagickAllocateMemory(char **,sizeof(char *));
if (filelist == (char **) NULL)
{
MagickError(ResourceLimitError,MemoryAllocationFailed,(char *) NULL);
return((Image *) NULL);
}
number_files=1;
filelist[0]=filenames;
status=ExpandFilenames(&number_files,&filelist);
if ((status == False) || (number_files == 0))
{
if (number_files == 0)
MagickError(ImageError,NoImagesWereFound,filenames);
else
MagickError(ResourceLimitError,MemoryAllocationFailed,filenames);
for (i=0; i < number_files; i++)
if (filelist[i] != filenames)
MagickFreeMemory(filelist[i]);
MagickFreeMemory(filelist);
return((Image *) NULL);
}
/*
Set image background resources.
*/
background_resources=(*resource_info);
background_resources.window_id=window_id;
FormatString(background_resources.window_id,"0x%lx",windows->image.id);
background_resources.backdrop=True;
/*
Read each image and convert them to a tile.
*/
backdrop=(windows->visual_info->class == TrueColor) ||
(windows->visual_info->class == DirectColor);
clone_info=CloneImageInfo(resource_info->image_info);
if (clone_info == (ImageInfo *) NULL)
return((Image *) NULL);
image=(Image *) NULL;
GetExceptionInfo(&exception);
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
for (i=0; i < number_files; i++)
{
handler=SetMonitorHandler((MonitorHandler) NULL);
(void) strlcpy(clone_info->filename,filelist[i],MaxTextExtent);
*clone_info->magick='\0';
(void) CloneString(&clone_info->size,DefaultTileGeometry);
DestroyExceptionInfo(&exception);
GetExceptionInfo(&exception);
next_image=ReadImage(clone_info,&exception);
if (exception.severity != UndefinedException)
CatchException(&exception);
if (filelist[i] != filenames)
MagickFreeMemory(filelist[i]);
if (next_image != (Image *) NULL)
{
(void) SetImageAttribute(next_image,"label",(char *) NULL);
(void) SetImageAttribute(next_image,"label",DefaultTileLabel);
SetGeometry(next_image,&geometry);
(void) GetMagickGeometry(clone_info->size,&geometry.x,&geometry.y,
&geometry.width,&geometry.height);
thumbnail_image=ThumbnailImage(next_image,geometry.width,
geometry.height,&exception);
if (thumbnail_image != (Image *) NULL)
{
DestroyImage(next_image);
next_image=thumbnail_image;
}
if (backdrop)
{
(void) MagickXDisplayBackgroundImage(display,&background_resources,
next_image);
MagickXSetCursorState(display,windows,True);
}
if (image == (Image *) NULL)
image=next_image;
else
{
image->next=next_image;
image->next->previous=image;
image=image->next;
}
}
(void) SetMonitorHandler(handler);
if (!MagickMonitorFormatted(i,number_files,&image->exception,
LoadImagesText,image->filename))
break;
}
DestroyImageInfo(clone_info);
MagickFreeMemory(filelist);
if (image == (Image *) NULL)
{
MagickXSetCursorState(display,windows,False);
MagickError(ImageError,NoImagesWereLoaded,filenames);
return((Image *) NULL);
}
while (image->previous != (Image *) NULL)
image=image->previous;
/*
Create the Visual Image Directory.
*/
montage_info=CloneMontageInfo(resource_info->image_info,(MontageInfo *) NULL);
if (resource_info->font != (char *) NULL)
(void) CloneString(&montage_info->font,resource_info->font);
(void) strlcpy(montage_info->filename,filename,MaxTextExtent);
montage_image=MontageImages(image,montage_info,&image->exception);
DestroyMontageInfo(montage_info);
DestroyImageList(image);
MagickXSetCursorState(display,windows,False);
if (montage_image == (Image *) NULL)
return(montage_image);
MagickXClientMessage(display,windows->image.id,windows->im_protocols,
windows->im_next_image,CurrentTime);
return(montage_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M a g i c k X D i s p l a y B a c k g r o u n d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% MagickXDisplayBackgroundImage() displays an image in the background of a window.
%
% The format of the MagickXDisplayBackgroundImage method is:
%
% unsigned int MagickXDisplayBackgroundImage(Display *display,
% MagickXResourceInfo *resource_info,Image *image)
%
% A description of each parameter follows:
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o resource_info: Specifies a pointer to a X11 MagickXResourceInfo structure.
%
% o image: Specifies a pointer to an Image structure; returned from
% ReadImage.
%
%
*/
MagickExport unsigned int MagickXDisplayBackgroundImage(Display *display,
MagickXResourceInfo *resource_info,Image *image)
{
char
geometry[MaxTextExtent],
visual_type[MaxTextExtent];
long
x,
y;
static MagickXPixelInfo
pixel;
static XStandardColormap
*map_info;
static XVisualInfo
*visual_info = (XVisualInfo *) NULL;
static MagickXWindowInfo
window_info;
unsigned int
status;
unsigned int
height,
width;
Window
root_window;
XGCValues
context_values;
MagickXResourceInfo
resources;
XWindowAttributes
window_attributes;
/*
Determine target window.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
resources=(*resource_info);
window_info.id=(Window) NULL;
root_window=XRootWindow(display,XDefaultScreen(display));
if (LocaleCompare(resources.window_id,"root") == 0)
window_info.id=root_window;
else
{
if (isdigit((int) *resources.window_id))
window_info.id=MagickXWindowByID(display,root_window,
(Window) strtol((char *) resources.window_id,(char **) NULL,0));
if (window_info.id == (Window) NULL)
window_info.id=
MagickXWindowByName(display,root_window,resources.window_id);
}
if (window_info.id == (Window) NULL)
{
MagickError(XServerError,NoWindowWithSpecifiedIDExists,
resources.window_id);
return(False);
}
/*
Determine window visual id.
*/
window_attributes.width=XDisplayWidth(display,XDefaultScreen(display));
window_attributes.height=XDisplayHeight(display,XDefaultScreen(display));
(void) strcpy(visual_type,"default");
status=XGetWindowAttributes(display,window_info.id,&window_attributes);
if (status != False)
FormatString(visual_type,"0x%lx",
XVisualIDFromVisual(window_attributes.visual));
if (visual_info == (XVisualInfo *) NULL)
{
/*
Allocate standard colormap.
*/
map_info=XAllocStandardColormap();
if (map_info == (XStandardColormap *) NULL)
MagickFatalError(ResourceLimitError,MemoryAllocationFailed,
MagickMsg(XServerFatalError,UnableToCreateStandardColormap));
map_info->colormap=(Colormap) NULL;
pixel.pixels=(unsigned long *) NULL;
/*
Initialize visual info.
*/
resources.map_type=(char *) NULL;
resources.visual_type=visual_type;
visual_info=MagickXBestVisualInfo(display,map_info,&resources);
if (visual_info == (XVisualInfo *) NULL)
MagickFatalError(XServerFatalError,UnableToGetVisual,
resources.visual_type);
/*
Initialize window info.
*/
window_info.ximage=(XImage *) NULL;
window_info.matte_image=(XImage *) NULL;
window_info.pixmap=(Pixmap) NULL;
window_info.matte_pixmap=(Pixmap) NULL;
}
/*
Free previous root colors.
*/
if (window_info.id == root_window)
(void) MagickXDestroyWindowColors(display,root_window);
/*
Initialize Standard Colormap.
*/
resources.colormap=SharedColormap;
MagickXMakeStandardColormap(display,visual_info,&resources,image,map_info,&pixel);
/*
Graphic context superclass.
*/
context_values.background=pixel.background_color.pixel;
context_values.foreground=pixel.foreground_color.pixel;
pixel.annotate_context=XCreateGC(display,window_info.id,GCBackground |
GCForeground,&context_values);
if (pixel.annotate_context == (GC) NULL)
MagickFatalError(XServerFatalError,UnableToCreateGraphicContext,
(char *) NULL);
/*
Initialize Image window attributes.
*/
MagickXGetWindowInfo(display,visual_info,map_info,&pixel,(XFontStruct *) NULL,
&resources,&window_info);
/*
Create the X image.
*/
window_info.width=(unsigned int) image->columns;
window_info.height=(unsigned int) image->rows;
FormatString(geometry,"%ux%u+0+0>",window_attributes.width,
window_attributes.height);
width=window_info.width;
height=window_info.height;
x=window_info.x;
y=window_info.y;
{
unsigned long
geometry_width=width,
geometry_height=height;
(void) GetMagickGeometry(geometry,&x,&y,&geometry_width,&geometry_height);
width=(unsigned int) geometry_width;
height=(unsigned int) geometry_height;
}
window_info.width=(unsigned int) width;
window_info.height=(unsigned int) height;
window_info.x=(int) x;
window_info.y=(int) y;
status=MagickXMakeImage(display,&resources,&window_info,image,window_info.width,
window_info.height);
if (status == False)
MagickFatalError(XServerFatalError,UnableToCreateXImage,(char *) NULL);
window_info.x=0;
window_info.y=0;
if (IsEventLogging())
{
(void) LogMagickEvent(X11Event,GetMagickModule(),
"Image: %.1024s[%lu] %lux%lu ",image->filename,image->scene,
image->columns,image->rows);
if (image->colors != 0)
(void) LogMagickEvent(X11Event,GetMagickModule(),"%uc ",image->colors);
(void) LogMagickEvent(X11Event,GetMagickModule(),"%.1024s",image->magick);
}
/*
Adjust image dimensions as specified by backdrop or geometry options.
*/
width=window_info.width;
height=window_info.height;
if (resources.backdrop)
{
/*
Center image on window.
*/
window_info.x=(window_attributes.width/2)-
(window_info.ximage->width/2);
window_info.y=(window_attributes.height/2)-
(window_info.ximage->height/2);
width=window_attributes.width;
height=window_attributes.height;
}
if (resources.image_geometry != (char *) NULL)
{
char
default_geometry[MaxTextExtent];
int
flags,
gravity;
XSizeHints
*size_hints;
/*
User specified geometry.
*/
size_hints=XAllocSizeHints();
if (size_hints == (XSizeHints *) NULL)
MagickFatalError3(ResourceLimitFatalError,MemoryAllocationFailed,
UnableToDisplayImage);
size_hints->flags=(long) NULL;
FormatString(default_geometry,"%ux%u",width,height);
flags=XWMGeometry(display,visual_info->screen,resources.image_geometry,
default_geometry,window_info.border_width,size_hints,&window_info.x,
&window_info.y,(int *) &width,(int *) &height,&gravity);
if (flags & (XValue | YValue))
{
width=window_attributes.width;
height=window_attributes.height;
}
(void) XFree((void *) size_hints);
}
/*
Create the X pixmap.
*/
window_info.pixmap=XCreatePixmap(display,window_info.id,(unsigned int) width,
(unsigned int) height,window_info.depth);
if (window_info.pixmap == (Pixmap) NULL)
MagickFatalError(XServerFatalError,UnableToCreateXPixmap,(char *) NULL);
/*
Display pixmap on the window.
*/
if (((unsigned int) width > window_info.width) ||
((unsigned int) height > window_info.height))
(void) XFillRectangle(display,window_info.pixmap,
window_info.annotate_context,0,0,(unsigned int) width,
(unsigned int) height);
(void) XPutImage(display,window_info.pixmap,window_info.annotate_context,
window_info.ximage,0,0,window_info.x,window_info.y,
(unsigned int) window_info.width,(unsigned int) window_info.height);
(void) XSetWindowBackgroundPixmap(display,window_info.id,window_info.pixmap);
(void) XClearWindow(display,window_info.id);
MagickXDelay(display,10*image->delay);
(void) XSync(display,False);
return(window_info.id == root_window);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M a g i c k X D i s p l a y I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% MagickXDisplayImage() displays an image via X11. A new image is created and
% returned if the user interactively transforms the displayed image.
%
% The format of the MagickXDisplayImage method is:
%
% Image *MagickXDisplayImage(Display *display,MagickXResourceInfo *resource_info,
% char **argv,int argc,Image **image,unsigned long *state)
%
% A description of each parameter follows:
%
% o nexus: Method MagickXDisplayImage returns an image when the
% user chooses 'Open Image' from the command menu or picks a tile
% from the image directory. Otherwise a null image is returned.
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o resource_info: Specifies a pointer to a X11 MagickXResourceInfo structure.
%
% o argv: Specifies the application's argument list.
%
% o argc: Specifies the number of arguments.
%
% o image: Specifies an address to an address of an Image structure;
% returned from ReadImage.
%
%
*/
#define MagnifySize 256 /* must be a power of 2 */
#define MagickMenus 10
#define MagickTitle "Commands"
#define DestroyWindowsImage(windows,subwindow) \
{ \
if ((windows->subwindow.image != (Image *) NULL) && \
(windows->subwindow.destroy == True)) \
{ \
DestroyImage(windows->subwindow.image); \
windows->subwindow.image=(Image *) NULL; \
} \
}
MagickExport Image *
MagickXDisplayImage(Display *display,MagickXResourceInfo *resource_info,
char *argv[],int argc,Image **image,unsigned long *state)
{
const char
* const CommandMenu[]=
{
"File",
"Edit",
"View",
"Transform",
"Enhance",
"Effects",
"F/X",
"Image Edit",
"Miscellany",
"Help",
(char *) NULL
},
* const FileMenu[]=
{
"Open...",
"Next",
"Former",
"Select...",
"Save...",
"Print...",
"Delete...",
"New...",
"Visual Directory...",
"Quit",
(char *) NULL
},
* const EditMenu[]=
{
"Undo",
"Redo",
"Cut",
"Copy",
"Paste",
(char *) NULL
},
* const ViewMenu[]=
{
"Half Size",
"Original Size",
"Double Size",
"Resize...",
"Apply",
"Refresh",
"Restore",
(char *) NULL
},
* const TransformMenu[]=
{
"Crop",
"Chop",
"Flop",
"Flip",
"Rotate Right",
"Rotate Left",
"Rotate...",
"Shear...",
"Roll...",
"Trim Edges",
(char *) NULL
},
* const EnhanceMenu[]=
{
"Hue...",
"Saturation...",
"Brightness...",
"Gamma...",
"Spiff",
"Dull",
"Equalize",
"Normalize",
"Negate",
"Grayscale",
"Map...",
"Quantize...",
(char *) NULL
},
* const EffectsMenu[]=
{
"Despeckle",
"Emboss",
"Reduce Noise",
"Add Noise...",
"Sharpen...",
"Blur...",
"Threshold...",
"Edge Detect...",
"Spread...",
"Shade...",
"Raise...",
"Segment...",
(char *) NULL
},
* const FXMenu[]=
{
"Solarize...",
"Swirl...",
"Implode...",
"Wave...",
"Oil Paint...",
"Charcoal Draw...",
(char *) NULL
},
* const ImageEditMenu[]=
{
"Annotate...",
"Draw...",
"Color...",
"Matte...",
"Composite...",
"Add Border...",
"Add Frame...",
"Comment...",
"Launch...",
"Region of Interest...",
(char *) NULL
},
* const MiscellanyMenu[]=
{
"Image Info",
"Zoom Image",
"Show Preview...",
"Show Histogram",
"Show Matte",
"Background...",
"Slide Show...",
"Preferences...",
(char *) NULL
},
* const HelpMenu[]=
{
"Overview",
"Browse Documentation",
"About Display",
(char *) NULL
},
* const ShortCutsMenu[]=
{
"Next",
"Former",
"Open...",
"Save...",
"Print...",
"Undo",
"Restore",
"Image Info",
"Quit",
(char *) NULL
},
* const ImmutableMenu[]=
{
"Image Info",
"Print",
"Next",
"Quit",
(char *) NULL
};
const char
* const *Menus[MagickMenus]=
{
FileMenu,
EditMenu,
ViewMenu,
TransformMenu,
EnhanceMenu,
EffectsMenu,
FXMenu,
ImageEditMenu,
MiscellanyMenu,
HelpMenu
};
static const CommandType
CommandMenus[]=
{
NullCommand,
NullCommand,
NullCommand,
NullCommand,
NullCommand,
NullCommand,
NullCommand,
NullCommand,
NullCommand,
NullCommand,
},
FileCommands[]=
{
OpenCommand,
NextCommand,
FormerCommand,
SelectCommand,
SaveCommand,
PrintCommand,
DeleteCommand,
NewCommand,
VisualDirectoryCommand,
QuitCommand
},
EditCommands[]=
{
UndoCommand,
RedoCommand,
CutCommand,
CopyCommand,
PasteCommand
},
ViewCommands[]=
{
HalfSizeCommand,
OriginalSizeCommand,
DoubleSizeCommand,
ResizeCommand,
ApplyCommand,
RefreshCommand,
RestoreCommand
},
TransformCommands[]=
{
CropCommand,
ChopCommand,
FlopCommand,
FlipCommand,
RotateRightCommand,
RotateLeftCommand,
RotateCommand,
ShearCommand,
RollCommand,
TrimCommand
},
EnhanceCommands[]=
{
HueCommand,
SaturationCommand,
BrightnessCommand,
GammaCommand,
SpiffCommand,
DullCommand,
EqualizeCommand,
NormalizeCommand,
NegateCommand,
GrayscaleCommand,
MapCommand,
QuantizeCommand
},
EffectsCommands[]=
{
DespeckleCommand,
EmbossCommand,
ReduceNoiseCommand,
AddNoiseCommand,
SharpenCommand,
BlurCommand,
ThresholdCommand,
EdgeDetectCommand,
SpreadCommand,
ShadeCommand,
RaiseCommand,
SegmentCommand
},
FXCommands[]=
{
SolarizeCommand,
SwirlCommand,
ImplodeCommand,
WaveCommand,
OilPaintCommand,
CharcoalDrawCommand
},
ImageEditCommands[]=
{
AnnotateCommand,
DrawCommand,
ColorCommand,
MatteCommand,
CompositeCommand,
AddBorderCommand,
AddFrameCommand,
CommentCommand,
LaunchCommand,
RegionofInterestCommand
},
MiscellanyCommands[]=
{
InfoCommand,
ZoomCommand,
ShowPreviewCommand,
ShowHistogramCommand,
ShowMatteCommand,
BackgroundCommand,
SlideShowCommand,
PreferencesCommand
},
HelpCommands[]=
{
HelpCommand,
BrowseDocumentationCommand,
VersionCommand
},
ShortCutsCommands[]=
{
NextCommand,
FormerCommand,
OpenCommand,
SaveCommand,
PrintCommand,
UndoCommand,
RestoreCommand,
InfoCommand,
QuitCommand
},
ImmutableCommands[]=
{
InfoCommand,
PrintCommand,
NextCommand,
QuitCommand
};
static const CommandType
* const Commands[MagickMenus]=
{
FileCommands,
EditCommands,
ViewCommands,
TransformCommands,
EnhanceCommands,
EffectsCommands,
FXCommands,
ImageEditCommands,
MiscellanyCommands,
HelpCommands
};
char
command[MaxTextExtent],
geometry[MaxTextExtent],
resource_name[MaxTextExtent];
CommandType
command_type;
Image
*display_image,
*nexus;
int
entry,
id,
status;
long
x,
y;
KeySym
key_symbol;
MonitorHandler
handler,
monitor_handler;
register int
i;
static char
working_directory[MaxTextExtent];
static XPoint
vid_info;
static MagickXWindowInfo
*magick_windows[MaxXWindows];
static unsigned int
number_windows;
MagickStatStruct_t
file_info;
time_t
timer,
timestamp,
update_time;
unsigned int
context_mask;
unsigned long
height,
width;
WarningHandler
warning_handler;
Window
root_window;
XClassHint
*class_hints;
XEvent
event;
XFontStruct
*font_info;
XGCValues
context_values;
MagickXPixelInfo
*icon_pixel,
*pixel;
MagickXResourceInfo
*icon_resources;
XStandardColormap
*icon_map,
*map_info;
XVisualInfo
*icon_visual,
*visual_info;
XWindowChanges
window_changes;
MagickXWindows
*windows;
XWMHints
*manager_hints;
assert(image != (Image **) NULL);
assert((*image)->signature == MagickSignature);
display_image=(*image);
(void) TransformColorspace(display_image,RGBColorspace);
monitor_handler=(MonitorHandler) NULL;
warning_handler=(WarningHandler) NULL;
windows=MagickXSetWindows((MagickXWindows *) ~0);
if (windows != (MagickXWindows *) NULL)
{
/*
Change to the working directory.
*/
if (('\0' != working_directory[0]) && (chdir(working_directory) != 0))
{
MagickXNoticeWidget(display,windows,"Unable to restore directory:",
working_directory);
MagickFatalError(ConfigureFatalError,UnableToChangeToWorkingDirectory,
NULL);
}
/*
Set the progress monitor if progress monitoring is requested.
*/
if (resource_info->image_info->progress)
monitor_handler=SetMonitorHandler(MagickXMagickMonitor);
/*
Set the warning and signal handlers.
*/
warning_handler=resource_info->display_warnings ?
SetErrorHandler(MagickXWarning) : SetErrorHandler((ErrorHandler) NULL);
warning_handler=resource_info->display_warnings ?
SetWarningHandler(MagickXWarning) : SetWarningHandler((WarningHandler) NULL);
}
else
{
/*
Allocate windows structure.
*/
resource_info->colors=display_image->colors;
windows=MagickXSetWindows(MagickXInitializeWindows(display,resource_info));
if (windows == (MagickXWindows *) NULL)
MagickFatalError3(ResourceLimitError,MemoryAllocationFailed,
UnableToCreateXWindow);
/*
Initialize window id's.
*/
number_windows=0;
magick_windows[number_windows++]=(&windows->icon);
magick_windows[number_windows++]=(&windows->backdrop);
magick_windows[number_windows++]=(&windows->image);
magick_windows[number_windows++]=(&windows->info);
magick_windows[number_windows++]=(&windows->command);
magick_windows[number_windows++]=(&windows->widget);
magick_windows[number_windows++]=(&windows->popup);
magick_windows[number_windows++]=(&windows->magnify);
magick_windows[number_windows++]=(&windows->pan);
magick_windows[number_windows]=(MagickXWindowInfo *) NULL;
for (i=0; i < (int) number_windows; i++)
magick_windows[i]->id=(Window) NULL;
vid_info.x=0;
vid_info.y=0;
}
/*
Initialize font info.
*/
if (windows->font_info != (XFontStruct *) NULL)
(void) XFreeFont(display,windows->font_info);
windows->font_info=MagickXBestFont(display,resource_info,False);
if (windows->font_info == (XFontStruct *) NULL)
MagickFatalError(XServerFatalError,UnableToLoadFont,resource_info->font);
/*
Initialize Standard Colormap.
*/
map_info=windows->map_info;
icon_map=windows->icon_map;
visual_info=windows->visual_info;
icon_visual=windows->icon_visual;
pixel=windows->pixel_info;
icon_pixel=windows->icon_pixel;
font_info=windows->font_info;
icon_resources=windows->icon_resources;
class_hints=windows->class_hints;
manager_hints=windows->manager_hints;
root_window=XRootWindow(display,visual_info->screen);
nexus=(Image *) NULL;
if (IsEventLogging())
{
(void) LogMagickEvent(X11Event,GetMagickModule(),
"Image: %.1024s[%lu] %lux%lu ",display_image->filename,
display_image->scene,display_image->columns,display_image->rows);
if (display_image->colors != 0)
(void) LogMagickEvent(X11Event,GetMagickModule(),"%uc ",
display_image->colors);
(void) LogMagickEvent(X11Event,GetMagickModule(),"%.1024s",
display_image->magick);
}
MagickXMakeStandardColormap(display,visual_info,resource_info,display_image,
map_info,pixel);
display_image->taint=False;
/*
Initialize graphic context.
*/
windows->context.id=(Window) NULL;
MagickXGetWindowInfo(display,visual_info,map_info,pixel,font_info,
resource_info,&windows->context);
class_hints->res_name=(char *) "superclass";
class_hints->res_class=(char *) "Display";
manager_hints->flags=InputHint | StateHint;
manager_hints->input=False;
manager_hints->initial_state=WithdrawnState;
MagickXMakeWindow(display,root_window,argv,argc,class_hints,manager_hints,
&windows->context);
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),"Window id: 0x%lx (context)",
windows->context.id);
(void) memset(&context_values,0,sizeof(context_values));
context_values.background=pixel->background_color.pixel;
context_values.font=font_info->fid;
context_values.foreground=pixel->foreground_color.pixel;
context_values.graphics_exposures=False;
context_mask=GCBackground | GCFont | GCForeground | GCGraphicsExposures;
if (pixel->annotate_context != (GC) NULL)
(void) XFreeGC(display,pixel->annotate_context);
pixel->annotate_context=
XCreateGC(display,windows->context.id,context_mask,&context_values);
if (pixel->annotate_context == (GC) NULL)
MagickFatalError(XServerFatalError,UnableToCreateGraphicContext,
(char *) NULL);
context_values.background=pixel->depth_color.pixel;
if (pixel->widget_context != (GC) NULL)
(void) XFreeGC(display,pixel->widget_context);
pixel->widget_context=
XCreateGC(display,windows->context.id,context_mask,&context_values);
if (pixel->widget_context == (GC) NULL)
MagickFatalError(XServerFatalError,UnableToCreateGraphicContext,
(char *) NULL);
context_values.background=pixel->foreground_color.pixel;
context_values.foreground=pixel->background_color.pixel;
context_values.plane_mask=
context_values.background ^ context_values.foreground;
if (pixel->highlight_context != (GC) NULL)
(void) XFreeGC(display,pixel->highlight_context);
pixel->highlight_context=XCreateGC(display,windows->context.id,
context_mask | GCPlaneMask,&context_values);
if (pixel->highlight_context == (GC) NULL)
MagickFatalError(XServerFatalError,UnableToCreateGraphicContext,
(char *) NULL);
(void) XDestroyWindow(display,windows->context.id);
/*
Initialize icon window.
*/
MagickXGetWindowInfo(display,icon_visual,icon_map,icon_pixel,(XFontStruct *) NULL,
icon_resources,&windows->icon);
windows->icon.geometry=resource_info->icon_geometry;
MagickXBestIconSize(display,&windows->icon,display_image);
windows->icon.attributes.colormap=
XDefaultColormap(display,icon_visual->screen);
windows->icon.attributes.event_mask=ExposureMask | StructureNotifyMask;
class_hints->res_name=(char *) "icon";
manager_hints->flags=InputHint | StateHint;
manager_hints->input=False;
manager_hints->initial_state=IconicState;
MagickXMakeWindow(display,root_window,argv,argc,class_hints,manager_hints,
&windows->icon);
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),"Window id: 0x%lx (icon)",
windows->icon.id);
/*
Initialize graphic context for icon window.
*/
if (icon_pixel->annotate_context != (GC) NULL)
(void) XFreeGC(display,icon_pixel->annotate_context);
context_values.background=icon_pixel->background_color.pixel;
context_values.foreground=icon_pixel->foreground_color.pixel;
icon_pixel->annotate_context=XCreateGC(display,windows->icon.id,
GCBackground | GCForeground,&context_values);
if (icon_pixel->annotate_context == (GC) NULL)
MagickFatalError(XServerFatalError,UnableToCreateGraphicContext,
(char *) NULL);
windows->icon.annotate_context=icon_pixel->annotate_context;
/*
Initialize Image window.
*/
if (windows->image.id != (Window) NULL)
{
(void) CloneString(&windows->image.name,"");
(void) CloneString(&windows->image.icon_name,"");
}
MagickXGetWindowInfo(display,visual_info,map_info,pixel,font_info,
resource_info,&windows->image);
windows->image.shape=True; /* non-rectangular shape hint */
windows->image.shared_memory&=resource_info->use_shared_memory;
if ((resource_info->title != (char *) NULL) && !(*state & MontageImageState))
{
MagickFreeMemory(windows->image.name);
windows->image.name=TranslateText(resource_info->image_info,
display_image,resource_info->title);
MagickFreeMemory(windows->image.icon_name);
windows->image.icon_name=TranslateText(resource_info->image_info,
display_image,resource_info->title);
}
else
{
char
filename[MaxTextExtent],
image_name[MaxTextExtent];
register Image
*q;
unsigned long
count;
/*
Window name is the base of the filename.
*/
(void ) CloneString(&windows->image.name,"");
(void ) CloneString(&windows->image.icon_name,"");
GetPathComponent(display_image->filename,TailPath,filename);
FormatString(image_name,"%s: %.1024s[%lu]",MagickPackageName,
filename,display_image->scene);
(void) CloneString(&windows->image.name,image_name);
q=display_image;
while (q->previous != (Image *) NULL)
q=q->previous;
for (count=1; q->next != (Image *) NULL; count++)
q=q->next;
FormatString(image_name,"%s: %.1024s[%lu of %lu]",
MagickPackageName,filename,display_image->scene+1U,count);
(void) CloneString(&windows->image.name,image_name);
if ((display_image->previous == (Image *) NULL) &&
(display_image->next == (Image *) NULL) &&
(display_image->scene == 0))
{
FormatString(image_name,"%s: %.1024s",MagickPackageName,
filename);
(void) CloneString(&windows->image.name,image_name);
}
(void) CloneString(&windows->image.icon_name,filename);
}
if (resource_info->immutable)
windows->image.immutable=True;
windows->image.use_pixmap=resource_info->use_pixmap;
windows->image.geometry=resource_info->image_geometry;
FormatString(geometry,"%ux%u+0+0>!",
XDisplayWidth(display,visual_info->screen),
XDisplayHeight(display,visual_info->screen));
width=display_image->columns;
height=display_image->rows;
x=0;
y=0;
(void) GetMagickGeometry(geometry,&x,&y,&width,&height);
windows->image.width=(unsigned int) width;
windows->image.height=(unsigned int) height;
windows->image.attributes.event_mask=ButtonMotionMask | ButtonPressMask |
ButtonReleaseMask | EnterWindowMask | ExposureMask | KeyPressMask |
KeyReleaseMask | LeaveWindowMask | OwnerGrabButtonMask |
PropertyChangeMask | StructureNotifyMask | SubstructureNotifyMask;
MagickXGetWindowInfo(display,visual_info,map_info,pixel,font_info,
resource_info,&windows->backdrop);
if ((resource_info->backdrop) || (windows->backdrop.id != (Window) NULL))
{
/*
Initialize backdrop window.
*/
windows->backdrop.x=0;
windows->backdrop.y=0;
(void) CloneString(&windows->backdrop.name,"GraphicsMagick Backdrop");
windows->backdrop.flags=USSize | USPosition;
windows->backdrop.width=XDisplayWidth(display,visual_info->screen);
windows->backdrop.height=XDisplayHeight(display,visual_info->screen);
windows->backdrop.border_width=0;
windows->backdrop.immutable=True;
windows->backdrop.attributes.do_not_propagate_mask=ButtonPressMask |
ButtonReleaseMask;
windows->backdrop.attributes.event_mask=ButtonPressMask | KeyPressMask |
StructureNotifyMask;
windows->backdrop.attributes.override_redirect=True;
class_hints->res_name=(char *) "backdrop";
manager_hints->flags=IconWindowHint | InputHint | StateHint;
manager_hints->icon_window=windows->icon.id;
manager_hints->input=True;
manager_hints->initial_state=
resource_info->iconic ? IconicState : NormalState;
MagickXMakeWindow(display,root_window,argv,argc,class_hints,manager_hints,
&windows->backdrop);
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),
"Window id: 0x%lx (backdrop)",windows->backdrop.id);
(void) XMapWindow(display,windows->backdrop.id);
(void) XClearWindow(display,windows->backdrop.id);
if (windows->image.id != (Window) NULL)
{
(void) XDestroyWindow(display,windows->image.id);
windows->image.id=(Window) NULL;
}
/*
Position image in the center the backdrop.
*/
windows->image.flags|=USPosition;
windows->image.x=(XDisplayWidth(display,visual_info->screen)/2)-
(windows->image.width/2);
windows->image.y=(XDisplayHeight(display,visual_info->screen)/2)-
(windows->image.height/2);
}
if (resource_info->name == (char *) NULL)
class_hints->res_name=resource_info->client_name;
else
class_hints->res_name=resource_info->name;
manager_hints->flags=IconWindowHint | InputHint | StateHint;
manager_hints->icon_window=windows->icon.id;
manager_hints->input=True;
manager_hints->initial_state=
resource_info->iconic ? IconicState : NormalState;
if (windows->group_leader.id != (Window) NULL)
{
/*
Follow the leader.
*/
manager_hints->flags|=WindowGroupHint;
manager_hints->window_group=windows->group_leader.id;
(void) XSelectInput(display,windows->group_leader.id,StructureNotifyMask);
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),
"Window id: 0x%lx (group leader)",windows->group_leader.id);
}
MagickXMakeWindow(display,
(Window) (resource_info->backdrop ? windows->backdrop.id : root_window),
argv,argc,class_hints,manager_hints,&windows->image);
(void) XChangeProperty(display,windows->image.id,windows->im_protocols,
XA_STRING,8,PropModeReplace,(unsigned char *) NULL,0);
if (windows->group_leader.id != (Window) NULL)
(void) XSetTransientForHint(display,windows->image.id,
windows->group_leader.id);
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),"Window id: 0x%lx (image)",
windows->image.id);
/*
Initialize Info widget.
*/
MagickXGetWindowInfo(display,visual_info,map_info,pixel,font_info,resource_info,
&windows->info);
(void) CloneString(&windows->info.name,"Info");
(void) CloneString(&windows->info.icon_name,"Info");
windows->info.border_width=1;
windows->info.x=2;
windows->info.y=2;
windows->info.flags|=PPosition;
windows->info.attributes.win_gravity=UnmapGravity;
windows->info.attributes.event_mask=
ButtonPressMask | ExposureMask | StructureNotifyMask;
class_hints->res_name=(char *) "info";
manager_hints->flags=InputHint | StateHint | WindowGroupHint;
manager_hints->input=False;
manager_hints->initial_state=NormalState;
manager_hints->window_group=windows->image.id;
MagickXMakeWindow(display,windows->image.id,argv,argc,class_hints,manager_hints,
&windows->info);
windows->info.highlight_stipple=XCreateBitmapFromData(display,
windows->info.id,(char *) HighlightBitmap,HighlightWidth,HighlightHeight);
windows->info.shadow_stipple=XCreateBitmapFromData(display,
windows->info.id,(char *) ShadowBitmap,ShadowWidth,ShadowHeight);
(void) XSetTransientForHint(display,windows->info.id,windows->image.id);
if (windows->image.mapped)
(void) XWithdrawWindow(display,windows->info.id,windows->info.screen);
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),"Window id: 0x%lx (info)",
windows->info.id);
/*
Initialize Command widget.
*/
MagickXGetWindowInfo(display,visual_info,map_info,pixel,font_info,
resource_info,&windows->command);
windows->command.data=MagickMenus;
(void) MagickXCommandWidget(display,windows,CommandMenu,(XEvent *) NULL);
FormatString(resource_name,"%.1024s.command",resource_info->client_name);
windows->command.geometry=MagickXGetResourceClass(resource_info->resource_database,
resource_name,"geometry",(char *) NULL);
(void) CloneString(&windows->command.name,MagickTitle);
windows->command.border_width=0;
windows->command.flags|=PPosition;
windows->command.attributes.event_mask=ButtonMotionMask | ButtonPressMask |
ButtonReleaseMask | EnterWindowMask | ExposureMask | LeaveWindowMask |
OwnerGrabButtonMask | StructureNotifyMask;
class_hints->res_name=(char *) "command";
manager_hints->flags=InputHint | StateHint | WindowGroupHint;
manager_hints->input=False;
manager_hints->initial_state=NormalState;
manager_hints->window_group=windows->image.id;
MagickXMakeWindow(display,root_window,argv,argc,class_hints,manager_hints,
&windows->command);
windows->command.highlight_stipple=windows->info.highlight_stipple;
windows->command.shadow_stipple=windows->info.shadow_stipple;
(void) XSetTransientForHint(display,windows->command.id,windows->image.id);
if (windows->command.mapped)
(void) XMapRaised(display,windows->command.id);
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),"Window id: 0x%lx (command)",
windows->command.id);
/*
Initialize Widget window.
*/
if (windows->widget.id != (Window) NULL)
(void) CloneString(&windows->widget.name,"");
MagickXGetWindowInfo(display,visual_info,map_info,pixel,font_info,
resource_info,&windows->widget);
FormatString(resource_name,"%.1024s.widget",resource_info->client_name);
windows->widget.geometry=MagickXGetResourceClass(resource_info->resource_database,
resource_name,"geometry",(char *) NULL);
(void ) CloneString(&windows->widget.name,"");
windows->widget.border_width=0;
windows->widget.flags|=PPosition;
windows->widget.attributes.event_mask=ButtonMotionMask | ButtonPressMask |
ButtonReleaseMask | EnterWindowMask | ExposureMask | KeyPressMask |
KeyReleaseMask | LeaveWindowMask | OwnerGrabButtonMask |
StructureNotifyMask;
class_hints->res_name=(char *) "widget";
manager_hints->flags=InputHint | StateHint | WindowGroupHint;
manager_hints->input=True;
manager_hints->initial_state=NormalState;
manager_hints->window_group=windows->image.id;
MagickXMakeWindow(display,root_window,argv,argc,class_hints,manager_hints,
&windows->widget);
windows->widget.highlight_stipple=windows->info.highlight_stipple;
windows->widget.shadow_stipple=windows->info.shadow_stipple;
(void) XSetTransientForHint(display,windows->widget.id,windows->image.id);
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),"Window id: 0x%lx (widget)",
windows->widget.id);
/*
Initialize popup window.
*/
if (windows->popup.id != (Window) NULL)
(void) CloneString(&windows->popup.name,"");
MagickXGetWindowInfo(display,visual_info,map_info,pixel,font_info,
resource_info,&windows->popup);
(void) CloneString(&windows->popup.name,"");
windows->popup.border_width=0;
windows->popup.flags|=PPosition;
windows->popup.attributes.event_mask=ButtonMotionMask | ButtonPressMask |
ButtonReleaseMask | EnterWindowMask | ExposureMask | KeyPressMask |
KeyReleaseMask | LeaveWindowMask | StructureNotifyMask;
class_hints->res_name=(char *) "popup";
manager_hints->flags=InputHint | StateHint | WindowGroupHint;
manager_hints->input=True;
manager_hints->initial_state=NormalState;
manager_hints->window_group=windows->image.id;
MagickXMakeWindow(display,root_window,argv,argc,class_hints,manager_hints,
&windows->popup);
windows->popup.highlight_stipple=windows->info.highlight_stipple;
windows->popup.shadow_stipple=windows->info.shadow_stipple;
(void) XSetTransientForHint(display,windows->popup.id,windows->image.id);
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),"Window id: 0x%lx (pop up)",
windows->popup.id);
/*
Initialize Magnify window and cursor.
*/
if (windows->magnify.id != (Window) NULL)
(void) CloneString(&windows->magnify.name,"");
MagickXGetWindowInfo(display,visual_info,map_info,pixel,font_info,
resource_info,&windows->magnify);
windows->magnify.shared_memory&=resource_info->use_shared_memory;
FormatString(resource_name,"%.1024s.magnify",resource_info->client_name);
windows->magnify.geometry=MagickXGetResourceClass(resource_info->resource_database,
resource_name,"geometry",(char *) NULL);
(void) CloneString(&windows->magnify.name,"");
FormatString(windows->magnify.name,"Magnify %uX",resource_info->magnify);
windows->magnify.cursor=MagickXMakeCursor(display,windows->image.id,
map_info->colormap,resource_info->background_color,
resource_info->foreground_color);
if (windows->magnify.cursor == (Cursor) NULL)
MagickFatalError(XServerFatalError,UnableToCreateCursor,(char *) NULL);
windows->magnify.width=MagnifySize;
windows->magnify.height=MagnifySize;
windows->magnify.flags|=PPosition;
windows->magnify.min_width=MagnifySize;
windows->magnify.min_height=MagnifySize;
windows->magnify.width_inc=MagnifySize;
windows->magnify.height_inc=MagnifySize;
windows->magnify.data=resource_info->magnify;
windows->magnify.attributes.cursor=windows->magnify.cursor;
windows->magnify.attributes.event_mask=ButtonPressMask | ButtonReleaseMask |
ExposureMask | KeyPressMask | KeyReleaseMask | OwnerGrabButtonMask |
StructureNotifyMask;
class_hints->res_name=(char *) "magnify";
manager_hints->flags=InputHint | StateHint | WindowGroupHint;
manager_hints->input=True;
manager_hints->initial_state=NormalState;
manager_hints->window_group=windows->image.id;
MagickXMakeWindow(display,root_window,argv,argc,class_hints,manager_hints,
&windows->magnify);
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),"Window id: 0x%lx (magnify)",
windows->magnify.id);
(void) XSetTransientForHint(display,windows->magnify.id,windows->image.id);
/*
Initialize panning window.
*/
MagickXGetWindowInfo(display,visual_info,map_info,pixel,font_info,
resource_info,&windows->pan);
(void) CloneString(&windows->pan.name,"Pan Icon");
windows->pan.width=windows->icon.width;
windows->pan.height=windows->icon.height;
FormatString(resource_name,"%.1024s.pan",resource_info->client_name);
windows->pan.geometry=MagickXGetResourceClass(resource_info->resource_database,
resource_name,"geometry",(char *) NULL);
(void) XParseGeometry(windows->pan.geometry,&windows->pan.x,&windows->pan.y,
&windows->pan.width,&windows->pan.height);
windows->pan.flags|=PPosition;
windows->pan.immutable=True;
windows->pan.attributes.event_mask=ButtonMotionMask | ButtonPressMask |
ButtonReleaseMask | ExposureMask | KeyPressMask | KeyReleaseMask |
StructureNotifyMask;
class_hints->res_name=(char *) "pan";
manager_hints->flags=InputHint | StateHint | WindowGroupHint;
manager_hints->input=False;
manager_hints->initial_state=NormalState;
manager_hints->window_group=windows->image.id;
MagickXMakeWindow(display,root_window,argv,argc,class_hints,manager_hints,
&windows->pan);
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),"Window id: 0x%lx (pan)",
windows->pan.id);
(void) XSetTransientForHint(display,windows->pan.id,windows->image.id);
if (windows->info.mapped)
(void) XWithdrawWindow(display,windows->info.id,windows->info.screen);
if (!windows->image.mapped || (windows->backdrop.id != (Window) NULL))
(void) XMapWindow(display,windows->image.id);
/*
Set progress monitor if progress monitoring requested.
*/
if ((resource_info->image_info->progress) &&
(monitor_handler == (MonitorHandler) NULL))
monitor_handler=SetMonitorHandler(MagickXMagickMonitor);
/*
Set warning and signal handlers.
*/
if (warning_handler == (WarningHandler) NULL)
{
warning_handler=resource_info->display_warnings ?
SetErrorHandler(MagickXWarning) : SetErrorHandler((ErrorHandler) NULL);
warning_handler=resource_info->display_warnings ?
SetWarningHandler(MagickXWarning) : SetWarningHandler((WarningHandler) NULL);
}
/*
Initialize Image and Magnify X images.
*/
windows->image.x=0;
windows->image.y=0;
windows->magnify.shape=False;
status=MagickXMakeImage(display,resource_info,&windows->image,display_image,
(unsigned int) display_image->columns,(unsigned int) display_image->rows);
if (status == False)
MagickFatalError(XServerFatalError,UnableToCreateXImage,(char *) NULL);
if (windows->image.mapped)
MagickXRefreshWindow(display,&windows->image,(XEvent *) NULL);
handler=SetMonitorHandler((MonitorHandler) NULL);
status=MagickXMakeImage(display,resource_info,&windows->magnify,(Image *) NULL,
windows->magnify.width,windows->magnify.height);
(void) SetMonitorHandler(handler);
if (status == False)
MagickFatalError(XServerFatalError,UnableToCreateXImage,(char *) NULL);
if (windows->magnify.mapped)
{
(void) XMapRaised(display,windows->magnify.id);
MagickXMakeMagnifyImage(display,windows);
}
if (windows->image.mapped)
if (((int) windows->image.width < windows->image.ximage->width) ||
((int) windows->image.height < windows->image.ximage->height))
(void) XMapRaised(display,windows->pan.id);
(void) XWithdrawWindow(display,windows->info.id,windows->info.screen);
(void) XSync(display,False);
/*
Respond to events.
*/
if (resource_info->delay > 1)
display_image->delay=resource_info->delay;
update_time=0;
if (resource_info->update)
{
/*
Determine when file data was last modified.
*/
status=MagickStat(display_image->filename,&file_info);
if (status == 0)
update_time=file_info.st_mtime;
if (resource_info->delay <= 1)
display_image->delay=resource_info->update*100;
}
timer=time((time_t *) NULL)+(long) display_image->delay/100+1;
*state&=(~FormerImageState);
*state&=(~MontageImageState);
*state&=(~NextImageState);
do
{
/*
Handle a window event.
*/
if (windows->image.mapped && (display_image->delay > 1))
{
if (timer < time((time_t *) NULL))
{
if (!resource_info->update)
*state|=NextImageState | ExitState;
else
{
/*
Determine if image file was modified.
*/
status=MagickStat(display_image->filename,&file_info);
if (status == 0)
if (update_time != file_info.st_mtime)
{
/*
Redisplay image.
*/
FormatString(resource_info->image_info->filename,
"%.1024s:%.1024s",display_image->magick,
display_image->filename);
nexus=ReadImage(resource_info->image_info,
&display_image->exception);
if (display_image->exception.severity !=
UndefinedException)
MagickError2(display_image->exception.severity,
display_image->exception.reason,
display_image->exception.description);
if (nexus != (Image *) NULL)
*state|=NextImageState | ExitState;
}
timer=time((time_t *) NULL)+(long) display_image->delay/100+1;
}
}
if (XEventsQueued(display,QueuedAfterFlush) == 0)
{
/*
Do not block if delay > 0.
*/
MagickXDelay(display,SuspendTime << 2);
continue;
}
}
timestamp=time((time_t *) NULL);
(void) XNextEvent(display,&event);
if (!windows->image.stasis)
windows->image.stasis=(time((time_t *) NULL)-timestamp) > 0;
if (!windows->magnify.stasis)
windows->magnify.stasis=(time((time_t *) NULL)-timestamp) > 0;
if (event.xany.window == windows->command.id)
{
/*
Select a command from the Command widget.
*/
id=MagickXCommandWidget(display,windows,CommandMenu,&event);
if (id < 0)
continue;
(void) strlcpy(command,CommandMenu[id],MaxTextExtent);
command_type=CommandMenus[id];
if (id < MagickMenus)
{
/*
Select a command from a pop-up menu.
*/
entry=MagickXMenuWidget(display,windows,CommandMenu[id],Menus[id],
command);
if (entry < 0)
continue;
(void) strlcpy(command,Menus[id][entry],MaxTextExtent);
command_type=Commands[id][entry];
}
if (command_type != NullCommand)
nexus=MagickXMagickCommand(display,resource_info,windows,command_type,
&display_image);
continue;
}
switch (event.type)
{
case ButtonPress:
{
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),
"Button Press: 0x%lx %u +%d+%d",event.xbutton.window,
event.xbutton.button,event.xbutton.x,event.xbutton.y);
if ((event.xbutton.button == Button3) &&
(event.xbutton.state & Mod1Mask))
{
/*
Convert Alt-Button3 to Button2.
*/
event.xbutton.button=Button2;
event.xbutton.state&=(~Mod1Mask);
}
if (event.xbutton.window == windows->backdrop.id)
{
(void) XSetInputFocus(display,event.xbutton.window,RevertToParent,
event.xbutton.time);
break;
}
if (event.xbutton.window == windows->image.id)
{
switch (event.xbutton.button)
{
case Button1:
{
if (resource_info->immutable)
{
/*
Select a command from the Immutable menu.
*/
entry=MagickXMenuWidget(display,windows,"Commands",ImmutableMenu,
command);
if (entry >= 0)
nexus=MagickXMagickCommand(display,resource_info,windows,
ImmutableCommands[entry],&display_image);
break;
}
/*
Map/unmap Command widget.
*/
if (windows->command.mapped)
(void) XWithdrawWindow(display,windows->command.id,
windows->command.screen);
else
{
(void) MagickXCommandWidget(display,windows,CommandMenu,
(XEvent *) NULL);
(void) XMapRaised(display,windows->command.id);
}
break;
}
case Button2:
{
/*
User pressed the image magnify button.
*/
(void) MagickXMagickCommand(display,resource_info,windows,ZoomCommand,
&display_image);
MagickXMagnifyImage(display,windows,&event);
break;
}
case Button3:
{
if (resource_info->immutable)
{
/*
Select a command from the Immutable menu.
*/
entry=MagickXMenuWidget(display,windows,"Commands",ImmutableMenu,
command);
if (entry >= 0)
nexus=MagickXMagickCommand(display,resource_info,windows,
ImmutableCommands[entry],&display_image);
break;
}
if (display_image->montage != (char *) NULL)
{
/*
Open or delete a tile from a visual image directory.
*/
nexus=MagickXTileImage(display,resource_info,windows,
display_image,&event);
if (nexus != (Image *) NULL)
*state|=MontageImageState | NextImageState | ExitState;
vid_info.x=windows->image.x;
vid_info.y=windows->image.y;
break;
}
/*
Select a command from the Short Cuts menu.
*/
entry=MagickXMenuWidget(display,windows,"Short Cuts",ShortCutsMenu,
command);
if (entry >= 0)
nexus=MagickXMagickCommand(display,resource_info,windows,
ShortCutsCommands[entry],&display_image);
break;
}
default:
break;
}
break;
}
if (event.xbutton.window == windows->magnify.id)
{
int
factor;
const char
* const MagnifyMenu[]=
{
"2",
"4",
"5",
"6",
"7",
"8",
"9",
"3",
(char *) NULL,
};
static const KeySym
MagnifyCommands[]=
{
XK_2,
XK_4,
XK_5,
XK_6,
XK_7,
XK_8,
XK_9,
XK_3
};
/*
Select a magnify factor from the pop-up menu.
*/
factor=MagickXMenuWidget(display,windows,"Magnify",MagnifyMenu,command);
if (factor >= 0)
MagickXMagnifyWindowCommand(display,windows,0,MagnifyCommands[factor]);
break;
}
if (event.xbutton.window == windows->pan.id)
{
MagickXPanImage(display,windows,&event);
break;
}
timer=time((time_t *) NULL)+(long) display_image->delay/100+1;
break;
}
case ButtonRelease:
{
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),
"Button Release: 0x%lx %u +%d+%d",event.xbutton.window,
event.xbutton.button,event.xbutton.x,event.xbutton.y);
break;
}
case ClientMessage:
{
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),
"Client Message: 0x%lx 0x%lx %d 0x%lx",event.xclient.window,
event.xclient.message_type,event.xclient.format,(unsigned long)
event.xclient.data.l[0]);
if (event.xclient.message_type == windows->im_protocols)
{
if (*event.xclient.data.l == (long) windows->im_update_widget)
{
(void) CloneString(&windows->command.name,MagickTitle);
windows->command.data=MagickMenus;
(void) MagickXCommandWidget(display,windows,CommandMenu,
(XEvent *) NULL);
break;
}
if (*event.xclient.data.l == (long) windows->im_update_colormap)
{
/*
Update graphic context and window colormap.
*/
for (i=0; i < (int) number_windows; i++)
{
if (magick_windows[i]->id == windows->icon.id)
continue;
context_values.background=pixel->background_color.pixel;
context_values.foreground=pixel->foreground_color.pixel;
(void) XChangeGC(display,magick_windows[i]->annotate_context,
context_mask,&context_values);
(void) XChangeGC(display,magick_windows[i]->widget_context,
context_mask,&context_values);
context_values.background=pixel->foreground_color.pixel;
context_values.foreground=pixel->background_color.pixel;
context_values.plane_mask=
context_values.background ^ context_values.foreground;
(void) XChangeGC(display,magick_windows[i]->highlight_context,
context_mask | GCPlaneMask,&context_values);
magick_windows[i]->attributes.background_pixel=
pixel->background_color.pixel;
magick_windows[i]->attributes.border_pixel=
pixel->border_color.pixel;
magick_windows[i]->attributes.colormap=map_info->colormap;
(void) XChangeWindowAttributes(display,magick_windows[i]->id,
magick_windows[i]->mask,&magick_windows[i]->attributes);
}
if (windows->pan.mapped)
{
(void) XSetWindowBackgroundPixmap(display,windows->pan.id,
windows->pan.pixmap);
(void) XClearWindow(display,windows->pan.id);
MagickXDrawPanRectangle(display,windows);
}
if (windows->backdrop.id != (Window) NULL)
(void) XInstallColormap(display,map_info->colormap);
break;
}
if (*event.xclient.data.l == (long) windows->im_former_image)
{
*state|=FormerImageState | ExitState;
break;
}
if (*event.xclient.data.l == (long) windows->im_next_image)
{
*state|=NextImageState | ExitState;
break;
}
if (*event.xclient.data.l == (long) windows->im_retain_colors)
{
*state|=RetainColorsState;
break;
}
if (*event.xclient.data.l == (long) windows->im_exit)
{
*state|=ExitState;
break;
}
break;
}
if (event.xclient.message_type == windows->dnd_protocols)
{
Atom
selection,
type;
int
format;
unsigned char
*data;
unsigned long
after,
length;
/*
Display image named by the Drag-and-Drop selection.
*/
if ((*event.xclient.data.l != 2) && (*event.xclient.data.l != 128))
break;
selection=XInternAtom(display,"DndSelection",False);
status=XGetWindowProperty(display,root_window,selection,0L,
MaxTextExtent-1,False,(Atom) AnyPropertyType,&type,&format,
&length,&after,&data);
if ((status != Success) || (length == 0))
break;
if (*event.xclient.data.l == 2)
{
/*
Offix DND.
*/
(void) strlcpy(resource_info->image_info->filename,
(char *) data,MaxTextExtent);
}
else
{
/*
XDND.
*/
if (strncmp((char *) data, "file:", 5) != 0)
{
(void) XFree((void *) data);
break;
}
(void) strlcpy(resource_info->image_info->filename,
((char *) data)+5,MaxTextExtent);
}
nexus=
ReadImage(resource_info->image_info,&display_image->exception);
if (display_image->exception.severity != UndefinedException)
MagickError2(display_image->exception.severity,
display_image->exception.reason,
display_image->exception.description);
if (nexus != (Image *) NULL)
*state|=NextImageState | ExitState;
(void) XFree((void *) data);
break;
}
/*
If client window delete message, exit.
*/
if (event.xclient.message_type != windows->wm_protocols)
break;
if (*event.xclient.data.l != (long) windows->wm_delete_window)
break;
(void) XWithdrawWindow(display,event.xclient.window,
visual_info->screen);
if (event.xclient.window == windows->image.id)
{
*state|=ExitState;
break;
}
if (event.xclient.window == windows->pan.id)
{
/*
Restore original image size when pan window is deleted.
*/
windows->image.window_changes.width=windows->image.ximage->width;
windows->image.window_changes.height=windows->image.ximage->height;
(void) MagickXConfigureImage(display,resource_info,windows,
display_image);
}
break;
}
case ConfigureNotify:
{
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),
"Configure Notify: 0x%lx %dx%d+%d+%d %d",event.xconfigure.window,
event.xconfigure.width,event.xconfigure.height,event.xconfigure.x,
event.xconfigure.y,event.xconfigure.send_event);
if (event.xconfigure.window == windows->image.id)
{
/*
Image window has a new configuration.
*/
if (event.xconfigure.send_event != 0)
{
XWindowChanges
window_changes;
/*
Position the transient windows relative of the Image window.
*/
if (windows->command.geometry == (char *) NULL)
if (!windows->command.mapped)
{
windows->command.x=
event.xconfigure.x-windows->command.width-25;
windows->command.y=event.xconfigure.y;
MagickXConstrainWindowPosition(display,&windows->command);
window_changes.x=windows->command.x;
window_changes.y=windows->command.y;
(void) XReconfigureWMWindow(display,windows->command.id,
windows->command.screen,CWX | CWY,&window_changes);
}
if (windows->widget.geometry == (char *) NULL)
if (!windows->widget.mapped)
{
windows->widget.x=
event.xconfigure.x+event.xconfigure.width/10;
windows->widget.y=
event.xconfigure.y+event.xconfigure.height/10;
MagickXConstrainWindowPosition(display,&windows->widget);
window_changes.x=windows->widget.x;
window_changes.y=windows->widget.y;
(void) XReconfigureWMWindow(display,windows->widget.id,
windows->widget.screen,CWX | CWY,&window_changes);
}
if (windows->magnify.geometry == (char *) NULL)
if (!windows->magnify.mapped)
{
windows->magnify.x=
event.xconfigure.x+event.xconfigure.width+25;
windows->magnify.y=event.xconfigure.y;
MagickXConstrainWindowPosition(display,&windows->magnify);
window_changes.x=windows->magnify.x;
window_changes.y=windows->magnify.y;
(void) XReconfigureWMWindow(display,windows->magnify.id,
windows->magnify.screen,CWX | CWY,&window_changes);
}
if (windows->pan.geometry == (char *) NULL)
if (!windows->pan.mapped)
{
windows->pan.x=
event.xconfigure.x+event.xconfigure.width+25;
windows->pan.y=
event.xconfigure.y+windows->magnify.height+50;
MagickXConstrainWindowPosition(display,&windows->pan);
window_changes.x=windows->pan.x;
window_changes.y=windows->pan.y;
(void) XReconfigureWMWindow(display,windows->pan.id,
windows->pan.screen,CWX | CWY,&window_changes);
}
}
if ((event.xconfigure.width == (long) windows->image.width) &&
(event.xconfigure.height == (long) windows->image.height))
break;
windows->image.width=event.xconfigure.width;
windows->image.height=event.xconfigure.height;
windows->image.x=0;
windows->image.y=0;
if (display_image->montage != (char *) NULL)
{
windows->image.x=vid_info.x;
windows->image.y=vid_info.y;
}
if (windows->image.mapped && windows->image.stasis)
{
/*
Update Image window configuration.
*/
windows->image.window_changes.width=event.xconfigure.width;
windows->image.window_changes.height=event.xconfigure.height;
(void) MagickXConfigureImage(display,resource_info,windows,
display_image);
}
if ((event.xconfigure.width < windows->image.ximage->width) ||
(event.xconfigure.height < windows->image.ximage->height))
{
(void) XMapRaised(display,windows->pan.id);
MagickXDrawPanRectangle(display,windows);
}
else
if (windows->pan.mapped)
(void) XWithdrawWindow(display,windows->pan.id,
windows->pan.screen);
break;
}
if (event.xconfigure.window == windows->magnify.id)
{
unsigned int
magnify;
/*
Magnify window has a new configuration.
*/
windows->magnify.width=event.xconfigure.width;
windows->magnify.height=event.xconfigure.height;
if (!windows->magnify.mapped)
break;
magnify=1;
while ((int) magnify <= event.xconfigure.width)
magnify<<=1;
while ((int) magnify <= event.xconfigure.height)
magnify<<=1;
magnify>>=1;
if (((int) magnify != event.xconfigure.width) ||
((int) magnify != event.xconfigure.height))
{
window_changes.width=magnify;
window_changes.height=magnify;
(void) XReconfigureWMWindow(display,windows->magnify.id,
windows->magnify.screen,CWWidth | CWHeight,&window_changes);
break;
}
if (windows->magnify.mapped && windows->magnify.stasis)
{
handler=SetMonitorHandler((MonitorHandler) NULL);
status=MagickXMakeImage(display,resource_info,&windows->magnify,
display_image,windows->magnify.width,windows->magnify.height);
MagickXMakeMagnifyImage(display,windows);
(void) SetMonitorHandler(handler);
}
break;
}
if (event.xconfigure.window == windows->pan.id)
{
/*
Pan icon window has a new configuration.
*/
if (event.xconfigure.send_event != 0)
{
windows->pan.x=event.xconfigure.x;
windows->pan.y=event.xconfigure.y;
}
windows->pan.width=event.xconfigure.width;
windows->pan.height=event.xconfigure.height;
break;
}
if (event.xconfigure.window == windows->icon.id)
{
/*
Icon window has a new configuration.
*/
windows->icon.width=event.xconfigure.width;
windows->icon.height=event.xconfigure.height;
break;
}
break;
}
case DestroyNotify:
{
/*
Group leader has exited.
*/
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),"Destroy Notify: 0x%lx",
event.xdestroywindow.window);
if (event.xdestroywindow.window == windows->group_leader.id)
{
*state|=ExitState;
break;
}
break;
}
case EnterNotify:
{
/*
Selectively install colormap.
*/
if (map_info->colormap != XDefaultColormap(display,visual_info->screen))
{
if (event.xcrossing.mode != NotifyUngrab)
{
XInductColormap(display,map_info->colormap);
}
}
break;
}
case Expose:
{
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),
"Expose: 0x%lx %dx%d+%d+%d",event.xexpose.window,
event.xexpose.width,event.xexpose.height,event.xexpose.x,
event.xexpose.y);
/*
Refresh windows that are now exposed.
*/
if (event.xexpose.window == windows->image.id)
if (windows->image.mapped)
{
MagickXRefreshWindow(display,&windows->image,&event);
timer=time((time_t *) NULL)+(long) display_image->delay/100+1;
break;
}
if (event.xexpose.window == windows->magnify.id)
if (event.xexpose.count == 0)
if (windows->magnify.mapped)
{
MagickXMakeMagnifyImage(display,windows);
break;
}
if (event.xexpose.window == windows->pan.id)
if (event.xexpose.count == 0)
{
MagickXDrawPanRectangle(display,windows);
break;
}
if (event.xexpose.window == windows->icon.id)
if (event.xexpose.count == 0)
{
MagickXRefreshWindow(display,&windows->icon,&event);
break;
}
break;
}
case KeyPress:
{
int
length;
/*
Respond to a user key press.
*/
length=XLookupString((XKeyEvent *) &event.xkey,command,sizeof(command),
&key_symbol,(XComposeStatus *) NULL);
*(command+length)='\0';
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),
"Key press: %d 0x%lx (%.1024s)",event.xkey.state,key_symbol,
command);
if (event.xkey.window == windows->image.id)
{
command_type=MagickXImageWindowCommand(display,resource_info,windows,
event.xkey.state,key_symbol,&display_image);
if (command_type != NullCommand)
nexus=MagickXMagickCommand(display,resource_info,windows,command_type,
&display_image);
}
if (event.xkey.window == windows->magnify.id)
MagickXMagnifyWindowCommand(display,windows,event.xkey.state,key_symbol);
if (event.xkey.window == windows->pan.id)
{
if (key_symbol == XK_q)
(void) XWithdrawWindow(display,windows->pan.id,
windows->pan.screen);
else
if ((key_symbol == XK_F1) || (key_symbol == XK_Help))
MagickXTextViewWidgetNDL(display,resource_info,windows,False,
"Help Viewer - Image Pan",
ImagePanHelp,
sizeof(ImagePanHelp));
else
MagickXTranslateImage(display,windows,*image,key_symbol);
}
timer=time((time_t *) NULL)+(long) display_image->delay/100+1;
break;
}
case KeyRelease:
{
/*
Respond to a user key release.
*/
(void) XLookupString((XKeyEvent *) &event.xkey,command,sizeof(command),
&key_symbol,(XComposeStatus *) NULL);
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),
"Key release: 0x%lx (%c)",key_symbol,*command);
break;
}
case LeaveNotify:
{
/*
Selectively uninstall colormap.
*/
if (map_info->colormap != XDefaultColormap(display,visual_info->screen))
{
if (event.xcrossing.mode != NotifyUngrab)
{
XUninductColormap(display,map_info->colormap);
}
}
break;
}
case MapNotify:
{
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),"Map Notify: 0x%lx",
event.xmap.window);
if (event.xmap.window == windows->backdrop.id)
{
(void) XSetInputFocus(display,event.xmap.window,RevertToParent,
CurrentTime);
windows->backdrop.mapped=True;
break;
}
if (event.xmap.window == windows->image.id)
{
if (windows->backdrop.id != (Window) NULL)
(void) XInstallColormap(display,map_info->colormap);
if (LocaleCompare(display_image->magick,"LOGO") == 0)
{
if (LocaleCompare(display_image->filename,"Untitled") == 0)
nexus=MagickXOpenImage(display,resource_info,windows,False);
else
*state|=NextImageState | ExitState;
}
if (((int) windows->image.width < windows->image.ximage->width) ||
((int) windows->image.height < windows->image.ximage->height))
(void) XMapRaised(display,windows->pan.id);
windows->image.mapped=True;
break;
}
if (event.xmap.window == windows->magnify.id)
{
MagickXMakeMagnifyImage(display,windows);
windows->magnify.mapped=True;
(void) XWithdrawWindow(display,windows->info.id,
windows->info.screen);
break;
}
if (event.xmap.window == windows->pan.id)
{
MagickXMakePanImage(display,resource_info,windows,display_image);
windows->pan.mapped=True;
break;
}
if (event.xmap.window == windows->info.id)
{
windows->info.mapped=True;
break;
}
if (event.xmap.window == windows->icon.id)
{
unsigned int
taint;
/*
Create an icon image.
*/
taint=display_image->taint;
MagickXMakeStandardColormap(display,icon_visual,icon_resources,
display_image,icon_map,icon_pixel);
(void) MagickXMakeImage(display,icon_resources,&windows->icon,
display_image,windows->icon.width,windows->icon.height);
display_image->taint=taint;
(void) XSetWindowBackgroundPixmap(display,windows->icon.id,
windows->icon.pixmap);
(void) XClearWindow(display,windows->icon.id);
(void) XWithdrawWindow(display,windows->info.id,
windows->info.screen);
windows->icon.mapped=True;
break;
}
if (event.xmap.window == windows->command.id)
{
windows->command.mapped=True;
break;
}
if (event.xmap.window == windows->popup.id)
{
windows->popup.mapped=True;
break;
}
if (event.xmap.window == windows->widget.id)
{
windows->widget.mapped=True;
break;
}
break;
}
case MappingNotify:
{
(void) XRefreshKeyboardMapping(&event.xmapping);
break;
}
case NoExpose:
break;
case PropertyNotify:
{
Atom
type;
int
format;
unsigned char
*data;
unsigned long
after,
length;
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),
"Property Notify: 0x%lx 0x%lx %d",event.xproperty.window,
event.xproperty.atom,event.xproperty.state);
if (event.xproperty.atom != windows->im_remote_command)
break;
/*
Display image named by the remote command protocol.
*/
status=XGetWindowProperty(display,event.xproperty.window,
event.xproperty.atom,0L,MaxTextExtent-1,False,(Atom) AnyPropertyType,
&type,&format,&length,&after,&data);
if ((status != Success) || (length == 0))
break;
(void) strlcpy(resource_info->image_info->filename,(char *) data,
MaxTextExtent);
nexus=ReadImage(resource_info->image_info,&display_image->exception);
if (display_image->exception.severity != UndefinedException)
MagickError2(display_image->exception.severity,
display_image->exception.reason,
display_image->exception.description);
if (nexus != (Image *) NULL)
*state|=NextImageState | ExitState;
(void) XFree((void *) data);
break;
}
case ReparentNotify:
{
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),
"Reparent Notify: 0x%lx=>0x%lx",event.xreparent.parent,
event.xreparent.window);
break;
}
case UnmapNotify:
{
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),"Unmap Notify: 0x%lx",
event.xunmap.window);
if (event.xunmap.window == windows->backdrop.id)
{
windows->backdrop.mapped=False;
break;
}
if (event.xunmap.window == windows->image.id)
{
windows->image.mapped=False;
break;
}
if (event.xunmap.window == windows->magnify.id)
{
windows->magnify.mapped=False;
break;
}
if (event.xunmap.window == windows->pan.id)
{
windows->pan.mapped=False;
break;
}
if (event.xunmap.window == windows->info.id)
{
windows->info.mapped=False;
break;
}
if (event.xunmap.window == windows->icon.id)
{
if (map_info->colormap == icon_map->colormap)
MagickXConfigureImageColormap(display,resource_info,windows,
display_image);
(void) MagickXFreeStandardColormap(display,icon_visual,icon_map,
icon_pixel);
windows->icon.mapped=False;
break;
}
if (event.xunmap.window == windows->command.id)
{
windows->command.mapped=False;
break;
}
if (event.xunmap.window == windows->popup.id)
{
if (windows->backdrop.id != (Window) NULL)
(void) XSetInputFocus(display,windows->image.id,RevertToParent,
CurrentTime);
windows->popup.mapped=False;
break;
}
if (event.xunmap.window == windows->widget.id)
{
if (windows->backdrop.id != (Window) NULL)
(void) XSetInputFocus(display,windows->image.id,RevertToParent,
CurrentTime);
windows->widget.mapped=False;
break;
}
break;
}
default:
{
if (IsEventLogging())
(void) LogMagickEvent(X11Event,GetMagickModule(),"Event type: %d",
event.type);
break;
}
}
}
while (!(*state & ExitState));
if (!(*state & ExitState))
(void) MagickXMagickCommand(display,resource_info,windows,FreeBuffersCommand,
&display_image);
else
{
/*
Query user if image has changed.
*/
if (!resource_info->immutable && display_image->taint)
{
status=MagickXConfirmWidget(display,windows,"Your image changed.",
"Do you want to save it");
if (status == 0)
*state&=(~ExitState);
else
if (status > 0)
(void) MagickXMagickCommand(display,resource_info,windows,SaveCommand,
&display_image);
}
}
if ((windows->visual_info->class == GrayScale) ||
(windows->visual_info->class == PseudoColor) ||
(windows->visual_info->class == DirectColor))
{
/*
Withdraw pan and Magnify window.
*/
if (windows->info.mapped)
(void) XWithdrawWindow(display,windows->info.id,windows->info.screen);
if (windows->magnify.mapped)
(void) XWithdrawWindow(display,windows->magnify.id,
windows->magnify.screen);
if (windows->command.mapped)
(void) XWithdrawWindow(display,windows->command.id,
windows->command.screen);
}
if (windows->pan.mapped)
(void) XWithdrawWindow(display,windows->pan.id,windows->pan.screen);
if (!resource_info->backdrop)
if (windows->backdrop.mapped)
{
(void) XWithdrawWindow(display,windows->backdrop.id,
windows->backdrop.screen);
(void) XDestroyWindow(display,windows->backdrop.id);
windows->backdrop.id=(Window) NULL;
(void) XWithdrawWindow(display,windows->image.id,windows->image.screen);
(void) XDestroyWindow(display,windows->image.id);
windows->image.id=(Window) NULL;
}
/*
Enable application cursor if progress indication enabled.
*/
if (resource_info->image_info->progress)
MagickXSetCursorState(display,windows,True);
MagickXCheckRefreshWindows(display,windows);
if (!resource_info->immutable || (display_image->next != (Image *) NULL))
if ((*state & FormerImageState) || (*state & NextImageState))
*state&=(~ExitState);
if (*state & ExitState)
{
/*
Free Standard Colormap.
*/
(void) MagickXFreeStandardColormap(display,icon_visual,icon_map,icon_pixel);
if (resource_info->map_type == (char *) NULL)
(void) MagickXFreeStandardColormap(display,visual_info,map_info,pixel);
/*
Free X resources.
*/
if (resource_info->backdrop)
(void) XFreeCursor(display,windows->backdrop.cursor);
if (resource_info->copy_image != (Image *) NULL)
{
DestroyImage(resource_info->copy_image);
resource_info->copy_image=(Image *) NULL;
}
MagickXDestroyXWindows(windows);
}
DestroyWindowsImage(windows,icon);
DestroyWindowsImage(windows,pan);
DestroyWindowsImage(windows,magnify);
(void) XSync(display,False);
/*
Restore our progress monitor and warning handlers.
*/
(void) SetMonitorHandler(monitor_handler);
(void) SetErrorHandler(warning_handler);
(void) SetWarningHandler(warning_handler);
/*
Change to home directory.
*/
if (getcwd(working_directory,MaxTextExtent-1) == NULL)
MagickFatalError(ConfigureFatalError,UnableToGetCurrentDirectory,
NULL);
if ((strlen(resource_info->home_directory) > 0) &&
(chdir(resource_info->home_directory) != 0))
{
MagickFatalError(ConfigureFatalError,UnableToRestoreCurrentDirectory,
resource_info->home_directory);
}
*image=display_image;
return(nexus);
}
#endif
|